Science Library - free educational site

PHP form handling

PHP comes into its own when processing form information. Users enter information into specific fields in an online form. This data can be loaded into a database on the server, retrieved, updated and deleted at will, by using the powerful form handling techniques offered by PHP.

An HTML form is created with the form tag:


<form action="form_manage.php" method="post">



There are two methods available for sending form information to the handling page (nominated in the action attribute): post and get.

post is used when an action is carried out upon submission of the form. This might be sending an email, updating a database, or an on-page update using AJAX.

get is used to change the URL. Searches are nearly always conducted using get (look at the URL next time you search for something in Google or Googlemaps). It adds one or more name-value pairs to the URL: e.g.

The raison d'être of forms is the facility of editing the form's fields. These can be any number of text boxes, radio buttons, select menus (dropdowns), and check boxes. These are placed between the opening and closing form tags. Forms can also contain upload fields (e.g. member account photos) for files of various types.

PHP can store the data inserted into a form element in special variables. A form defines an input as follows: e.g.

<input type="text" name="customer_name" />

The information entered into the input field will be passed to the PHP handling form via a variable called $_REQUEST['customer_name']. The variable name is case sensitive.

Magic Quotes

Magic quotes are a now redundant feature of earlier versions of PHP. It inserts backslashes (\) into submitted form data before single and double quote marks. This was to prevent unintended clashes in the use of quote marks intended as an integral part of a string rather than functional characters. However, to avoid these backslashes appearing in the text when it is printed out, they can be removed using:

\$variable = stripslashes($variable);

Single-Page Form Handling

When a form is submitted, it needs to be validated (checked for completed mandatory fields, and correctness of input type). The data is then submitted to a PHP in a multi-dimensional array called \$_POST, if the method is specified as post.

To have a single page both display and handle a form, create a hidden form input. This will not be displayed, so cannot be altered by the user, but submits an element to the POST array containing the value '1' (i.e. true) for the element called 'submitted':

<input type="hidden" name="submitted" value="1" />

if (isset($_POST['submitted'])) {

// process form info

} else {

// display form



If the form has been submitted, \$_POST['submitted'] contains the value '1', so the form data is processed. If the form has not been submitted the else clause will be executed - and the form will be displayed instead, waiting for submission. To have the form submit and the page display the form again, leave out the else clause.

Sticky Forms

A sticky form is one that remembers the data in input fields, and selections made from drop-downs and radio buttons, after submission. This is useful to avoid the inconvenience of the user needing to re-enter all the data because the form failed a validation test on one field.

The value attribute in a form's input tag presets a default value:

<input type="text" name="hobby" value="science" />

PHP can preset the value by printing it:

<input type="text" name="hobby" value="<?php echo $hobby; ?>" />

Text areas can be preset:

<textarea name="message" rows="20" cols="40"><?php echo $message; ?>


Radio buttons and checkboxes can be preset:

<input type="text" name="gender" value="M" <?php if ($gender == 'M') {

echo 'checked="checked"';

} ?> />

Pull-down menus can be preset:

echo '<select name="DOB">';

for (\$date = 1950; \$date <= 2016; \$date++) {

echo "<option value=\"\$date\";

if (\$DOB == \$date) {

echo ' selected="selected"';


echo ">\$date</option>\n"'


echo '</select>';

Echoing Input

After data has been input and a form submitted, the data can be echoed in the form again quite simply:

if (isset(\$_POST['input'])) {

echo \$_POST['input'];


Double quotes around HTML attributes, such as the value attribute in a form input, ensures that strings with white space are stored fully.

File Upload

Uploading files requires two directories: a temporary and a final directory.

It is a good first step to run a phpinfo() function to check PHP has been set up correctly to permit uploads, and that a temporary tmp file exists with write permissions. These can be edited in the php.ini file on a local server.

Create an uploads folder and place it in the root of the domain. Make sure this folder has full permissions for anyone to read/write.

The upload system has two parts: the HTML form and the PHP script which handles the submitted form and file.

<form enctype="multipart/form-data" action="form_upload.php" method="post">

<input type="hidden" name="MAX_FILE_SIZE" value="5000000" />

File <input type="file" name="upload" />

The above code results in this form element:


When submitted the uploaded file is available within the \$_FILES superglobal array variable, containing the array elements: name, type, size, tmp_name, error.

The file_upload.php will contain instructions as to what to do with the uploaded file. This is to move it from the temporary folder to a destination folder, and to name it something sensible:

move_uploaded_file (temp_filename, /path/to/destination/final_filename);

The PHP upload handling script

if (isset($_POST['submitted'])) {

if (isset($_FILES['upload'])) {

$allowed = array ('image/jpg', 'image/png', 'application/pdf', 'audio/mp3', 'video/mp4', 'text/html');

if (in_array(\$_FILES['upload']['type'], $allowed)) {

if (move_uploaded_file(\$_FILES['upload']['temp_name'], "../uploads/{\$_FILES['upload']['name']}")) {

echo '<p>File upload successful</p>';


The \$allowed array restricts the allowed file types to the MIME (Multipurpose Internet Mail Extensions) types specified. This is for security, to ensure that executable files are not loaded.

Content © Renewable.Media. All rights reserved. Created : August 12, 2014 Last updated :October 14, 2015

Latest Item on Science Library:

The most recent article is:


View this item in the topic:

Vectors and Trigonometry

and many more articles in the subject:

Subject of the Week


Environmental Science is the most important of all sciences. As the world enters a phase of climate change, unprecedented biodiversity loss, pollution and human population growth, the management of our environment is vital for our futures. Learn about Environmental Science on

Environmental Science

Great Scientists

Maurice Wilkins

1916 - 2004

Maurice Wilkins, 1916 - 2004, molecular biologist, was 'the third man of the double helix', as his biography title declares. Born in New Zealand, but did most of his professional work in England, Wilkins shared the Nobel Prize with Crick and Watson.

Maurice Wilkins
Lugano English

Quote of the day...

Injustice anywhere is a threat to justice everywhere.

Renewable.Media Internet Promotions

Science Library