erfan.sajjadie erfan.sajjadie - 1 year ago 65
PHP Question

post method don't work in html form

I have this simple html form and using post method.

<form action = "read.php" method="post">
<input type="text" name ="name">
<input type="submit">

and here is my php :

echo "sent";
echo "not sent";

when I run the code "not sent" message will appear.It seems everything is ok
but it doesn't work whereas GET method work correctly and show the "sent" message.what is the problem?

Answer Source

Firstly, make sure your markup is valid. Note that you have some spaces where there should not be spaces (e.g. name ="name"). At a minimum you should have a blank HTML document, with your contents inside a <body> tag:

<!DOCTYPE html>
    <form action="read.php" method="post">
        <input type="text" name="name">
        <input type="submit">

It's unclear from your question whether the above form is inside read.php or a separate script?

If they are separate (e.g. the form is in index.php) then run index.php in your browser. It should post to read.php which must be in the same relative directory. If the form and PHP is inside the same script, then run read.php in your browser.

With the PHP itself you are best off trying to debug this by outputting the contents of the post, e.g.


If it works, you will get an array which contains the form contents after posting. This will only appear after you have filled in the name field and pressed the Submit button, e.g.

array(1) { ["name"]=> string(4) "andy" }

Going back to the code in your question...If all of your code is in the same script, it will say "not sent" on page load, because nothing has been posted at that point. It will only output "sent" once you've filled in the name field and pressed the Submit button.

You were wondering why this "works" with the GET method. Well, the reason is because GET will append the form fields to the URL. On page load you run index.php. There's no $_GET parameters. After submitting the form, the URL would be manipulated (e.g. index.php?name=andy). So on page load it says "not sent" but then once it has ?name=andy in the URL it will say "sent" because that's a GET parameter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download