Question

I have drop down menu as such:

<form id="page" name="page" mode="post" action="display.php">
    <select name="car" id="car">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select> 
</form>

I have this example of display.php from another user on here to display text contents:

 <?php
$file = $_POST['car'].'.txt';
$contents = file($file); 
$string = implode("<br>", $contents);
echo $string;
echo "<br><br>";
?>

This causes the page to change to the display.php but not display any .txt file contents. When I use the foreach(glob *.txt it displays all the text files contents, for obvious reasons. But I cannot locate the error in my current config that would display just the chosen one. Please advise.

Was it helpful?

Solution

To make this work you will need to have the data in the select box to be posted to the PHP file.

HTML code in theForm.php:

<form action="someFile.php" method="POST">
    <select name="car" id="car">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
    </select>
    <input type="submit value="Go"/>
</form>

This tells the browser that when the user click "Go", to send the data from the drop-down box to someFile.php where it can be used by PHP.

PHP code in someFile.php:

<?php
$file = $_POST['car'] . '.txt';
$contents = file($file); 
$string = implode("<br>", $contents);
echo $string;
?>

The $_POST array is a built-in PHP variable containing information sent to the server from a form. The PHP then uses that text to figure out which .txt file should be read. That file is then read from the file and echoed to the user.

So if the user selected Volvo, this code will return the contents of a file named volvo.txt.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top