简体   繁体   中英

basic php form doesnt work

I am new in PHP and trying to save input to a text file, but POST action does nothing:

<form method="POST" action="<?php $_SERVER["PHP_SELF"]; ?>">
Name: <input type="text" name="usersname"/><br/>
<input type="submit" value="Write" name="submitwrite"/>
</form>

and in the same file on the top:

<?php
    // Check if the user submitted this form
if (isset($_POST["submitwrite"])) {
    // Open the file in write mode
    $handle = fopen("writetest.txt","a+"); 

    // If successful
    if ($handle) {
        // Write to that handle the username submitted in the form and the date
        fwrite($handle,$_POST["usersname"] . " - " . date("Y-m-d"));

        // Close the file
        fclose($handle);
    }
}
?>

I click button and it doesnt POST to itself.... how to fix it??

UPDATE: Thank you for your answers.. A problem was with file permissions... server does not allow me to set 777, only 755. There was nothing wrong with this code. I am glad you helped me to spot this !!

What does <?php $_SERVER["PHP_SELF"]; ?> <?php $_SERVER["PHP_SELF"]; ?> do? It doesn't print anything, so your form doesn't have a place to submit to.

Try using <?php echo $_SERVER["PHP_SELF"]; ?> <?php echo $_SERVER["PHP_SELF"]; ?> or <?php print($_SERVER["PHP_SELF"]); ?> <?php print($_SERVER["PHP_SELF"]); ?> instead.


Also, if that won't help, maybe changing fopen("writetest.txt","a+"); to fopen("writetest.txt","w"); might help?

You forgot to echo the action. But it doesn't matter, since you should omit the attribute completely if you want to POST to the same URL.

For me your code works fine, but, I think that you doesn't work because the directory haven't permission for write.

run chmod 0777 diretory_name

I suspect <?php $_SERVER["PHP_SELF"]; ?> <?php $_SERVER["PHP_SELF"]; ?> isn't doing what you expect it to.

If I recall correctly if you can avoid the problem by removing the action attribute, then the form will default to posting to "itself" (the same URL).

You have to set your permissions to read/write for both User and IUSR on "writetest.txt" if you're testing locally.

Steps to Fix it:

  • Right click the file "writetest.txt"
  • Go to Properties.
  • Click Security.
  • Click Edit. Select IUSR and USER
  • Check the "Write" box on both users.
  • Save the settings.

You are missing an echo in the action php statement. However the form should still post to itself.

Try:

if (isset($_POST)) {
    var_dump($_POST);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM