faqts : Computers : Programming : Languages : PHP : Common Problems : Forms and User Input

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

28 of 42 people (67%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

What's the best way to design a single PHP page for a form and it's submission?
How can I check if a form was submitted to trigger a page?

Aug 4th, 2000 14:43
Ben Munoz, Loren Siebert, Nathan Wallace, John Steele, Daniel Convissor


It's nice to have only one file, with the variable names all in one
place.  No interdependancies, you can rename the file and it still
works.  Here is an example of a single file to show a form and process
it when submitted
<?php /* someform.php3 */
if ($REQUEST_METHOD == 'POST') {
  // process the form - validate, insert into database, mail user, etc.
  if ($some_error) {
    echo "Oops!<br>";
    exit;
    }
  else
    echo "Thank you $name, we've emailed you at $email<br>\n";
  }
else {
?>
  <!-- here's our form output, and any other stuff on this page needed
-->
  <form name="whatever" method="post" action=<? echo $PHP_SELF ?>">
    Your Name: <input type="text" name="name"><br>
    Email: <input type="text" name="email"><br>
  </form>
<?
  }
?>
----------------------------------------------------------------
An easy way to check if a form was submitted is to insert a hidden 
input field, such as <input type=hidden name=submitted value=1>.
Then: 
<?
    if ($submitted) {
        # Form was submitted.
    } else {
        # Form was not submitted.
    }
?>
Another way to check if a form was submitted is to see if the submit
button's name variable exists.  So, let's say your form has the
following submit button:
    <input type="submit" name="SubmitFoo" value="Submit this Form">
You can see if it was submitted by checking the $SubmitFoo variable:
    if (!$SubmitFoo) {
        # Form hasn't been submitted.  Draw up the form.
    } else {
        # Form was submitted, do the script and print thank you message.
    }
***********
I used to use the SubmitFoo method shown above until I realized that 
IE5.0 does not always send the SubmitFoo name/value pair! If you have a 
form with only one input element (e.g., an input box and a submit 
button), and if you submit the form from IE5.0 by simply hitting 
<RETURN> rather than explicitly mouse-clicking the submit button, then 
the SubmitFoo value will NOT be passed to the server and the above 
check will not work. You can get around this by also passing in a 
hidden field called SubmitFoo with some arbitrary value. I don't know 
which versions of IE5.x do this, but I see it in 5.00.2314.1003 without 
fail. -Loren