PHP: How can I take an input from the user, store it, and display it back?
I've been trying to create some php code that would let me take input from a user using a text box. I want to then store that input (probably like 7 characters long) and then display it on a page in a list format ( eg 1 2 3 )
I've been at this for hours reading tutorials and what not but everything I find only shows me the fwrite function and when I try to append I still end up deleting data.
I would like the newest inputs to show up on top of the list if possible.
Can someone help me? I am really frustrated and I know almost no php.. kind of playing around with it and can't figure this out =/
I was thinking of storing the input from users in an array, then display the array.. But that开发者_JS百科 doesn't work for me either.
So you want to have a form, let the users enter text, then display all the text entered by all the users, sort of like a wall or guestbook.
I'm presuming you've managed to fetch the user's input by looking at $_POST
after the form submission. To store it in a file without overwriting the existing file contents the easiest way is file_put_contents
with the special FILE_APPEND
flag.
Lets say your HTML form has a textbox with name="newData"
. Then, in the form submission target script:
//store all user input in a file called data.txt in the current directory
$filename = "./data.txt" ;
$newData = $_POST['newData'] . "\n" ;
file_put_contents($filename, $newData, FILE_APPEND);
//now fetch all data and display it
$lines = file($filename) ;
echo '<ul>' ;
foreach ($lines as $line) {
echo "<li>$line</li>" ;
}
echo '</ul>' ;
Get started like that to see the basics in action and then you can look into:
- filtering user input so that you don't store and display any nasty stuff
- storing the data file outside the web root so that it's not accessible via the browser
- prettifying the output list
If they're submitting the data via form, it will POST to the server; meaning you can use:
<form action="target.php" method="post">
<input type="text" name="username" value="" />
<input type="submit" name="submit value="Submit" />
</form>
for the markup, and then for the PHP (on target.php):
<?php
if (isset($_POST['submit']) { //to check if the form was submitted
$username= $_POST['username'];
}
?>
At this point you can then use <?php echo $username ?>
anywhere you want to echo the data entered from the previous page.
I'm no PHP expert either (I recommend the Lynda.com training videos, "PHP & MySQL Essential Training" and "PHP & MySQL Beyond The Basics" with Kevin Skoglund) but maybe this helps.
As said above, you can use $_POST
to get the data, however it is worth noting that if you are actually using this in a web application, you need to sanitize for XSS. You can do this quite simply with PHP's htmlspecialchars()
try this for taking input from user in php
$variablname = fgets(STDIN); echo $variable;
file_put_contents('/path/to/file','contents',FILE_APPEND);
精彩评论