PHP Form that Submits to same page

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Suppose you have a PHP with this basic form…

basic form

basic form

And you want it to post to the same PHP page so that you don’t have to create a separate PHP page to process that form.

No problem.  Note that normally the form tag has the “method” attribute (which we have as “post”) and it often will have the “action” attribute which would be the destination PHP page that the form posts to.  But in our case, we omitted the “action” method in which case it posts to itself by default.  It will post to the same PHP page.

But then we need to add if-else logic to determine whether an visitor is seeing the page the first time or whether they have posted the form.  We detect that they posted the form by seeing if “$_POST[‘userinput’]” is set.  Note that “userinput” is the name attribute of one of the submitted form values.   If the post of that value exists the form was posted and we process the form.

For this tutorial, we simply echo the value that was submitted (but not before passing it through htmlspecialchars() because we always need to sanitize user inputs).   Like this…

form post to itself

form post to itself

The else portion of the condition is when visitor is seeing the page for the first time. And hence this is where we display the form.