Sei sulla pagina 1di 11

Handling forms in PHP

This is a simple tutorial on how to handle forms in PHP. I wasn‟t planning to post anything
this basic on the website, but since then, have come across a number of forums where
newcomers have posted questions regarding handling form submissions. I guess this is
the most common obstacle faced by most new comers to PHP.

Before continuing with the article, download the PHP form handling sample code from the
link given.

Anatomy of HTML form elements

Take a look at the source code of form.php file. As you can see most HTML form
elements have three attributes in common.

1. name
2. id
3. value

The “id” attribute is not required right now but will come in handy when you start using
JavaScript. Each element should have a unique name and id. We will use the element‟s
name to access its value in PHP.

HTML form tag

The form tag has two attributes which are of interest to us. The method attribute and the
action attribute. The method attribute can have two values “POST” and “GET”. The main
difference between the two is how the data is sent when the form is submitted.

In the GET method, the data is sent as a URL string. The amount of data that can be sent
is limited and this limit depends on the browser being used. For Internet Explorer this limit
is 2Kb. That is, you can not send more than 2048 characters through Internet Explorer
using GET method.

In the POST method, the data is sent as a part of the request to the server. That is, it is
embedded in the message body. There are no limits to the amount of data that can be
sent.

A search for “POST vs. GET” on Google will give you a lot of useful resources on the
usage and difference of the above two methods.

Simple Rule of Thumb


Use POST method for data manipulation: Adding and editing data.
Use GET method for displaying data: Searching, sorting, pagination etc.
The action attribute simply points to the script that will handle form submission. In this
case, it is form-exec.php

Form handler script

Like I mentioned earlier, we will use the element‟s name to access its value in PHP. For
example, to access the value of field named “pname”, we will use $_POST[„pname‟].

If we were using GET as the submission method, we can get the value of the “pname” field as
$_GET[„pname‟].

You can get any form elements value by using the $_GET or $_POST arrays.

<?php
//To access the value of a field named "gender"
$gender = $_POST['gender']; //If using POST method
$gender = $_GET['gender']; //If using GET method
?>

Select list with multiple selections

Handling of select lists with multiple selections is slightly different from other form
elements. In the example form, the interests select list allows multiple selections and
hence requires special handling.

If we name this select list simply as “interests” and try to retrieve its value using
$_POST[„interests‟] we will only get the last selected option. We need to name this select
list as interests[] . This tells PHP to treat the values coming from this element as an array.

Now, $_POST[„interests‟] will give us an associative array which is populated with the
selections made by the user.

Multiple checkboxes

Suppose you want to allow the user to select multiple checkboxes as shown in the image
below. The logic we applied to the select list above will also apply here. All the
checkboxes in the group will have the same name but will have different values.
All the checkboxes should have the same name but append [] to this name. For example,
utilities[]. Now, $_POST[„utilities‟] will give us an associative array which will be populated with the
values of the checkboxes selected by the user.

Note: Only the name attribute is important here. You can set the id attribute to any value you
want. You need not append the [] to the checkboxes ids. Moreover, the ids need not be same.

<html>
<input name="utilities[]" value="Community Fees" type="checkbox"
id="commfees">Community Fees <br />

<input name="utilities[]" value="Water" type="checkbox"


id="water">Water<br />

<input name="utilities[]" value="Electricity" type="checkbox"


id="electricity">Electricity<br />

<input name="utilities[]" value="Gas" type="checkbox" id="gas">Gas


</html>

Note

1. Variables are case sensitive in PHP. $_POST[„pname‟] is not same as $_POST[„PNAME‟]


2. Value of checkbox is available only if its checked

Handling HTML forms with PHP

» Simple contact form

<html>
<body>
<form action="myform.php" method="post">
<p>Your Name: <input type="text" name="yourname" /><br />
E-mail: <input type="text" name="email" /></p>

<p>Do you like this website?


<input type="radio" name="likeit" value="Yes" checked="checked" /> Yes
<input type="radio" name="likeit" value="No" /> No
<input type="radio" name="likeit" value="Not sure" /> Not sure</p>

<p>Your comments:<br />


<textarea name="comments" rows="10" cols="40"></textarea></p>

<p><input type="submit" value="Send it!"></p>


</form>
</body>
</html>

See the example HTML code above? This is a simple HTML form with two input fields,
one radio box group and a text area for comments. Let's say we save this code in a file
called "test.html". When submitted data is sent to the "myform.php" file using POST HTTP
method.

All variables passed to the current script via the HTTP POST method are stored in associative
array $_POST. In other words, in PHP you can access data from each field using
$_POST['NAME'], where NAME is the actual field name. If you submit the form above you would
have access to a number of $_POST array values inside the myform.php file:

Variable Holds value of


$_POST['yourname'] text field "yourname"
$_POST['email'] text field "email"
$_POST['likeit'] selected radio box group "likeit"
$_POST['comments'] textarea "comments"

With register_globals activated all form data is automatically stored in variable $name (where
name is field name, for example $yourname or $email), but this can lead to various security
issues and should be avoided at all cost! This feature is now officially depreciated and disabled by
default.

Now, if you wanted to display submitted data you could simply echo all the variables as shown
below, but do not! Why? Read further.

<html>
<body>
Your name is: <?php echo $_POST['yourname']; ?><br />
Your e-mail: <?php echo $_POST['email']; ?><br />
<br />
Do you like this website? <?php echo $_POST['likeit']; ?><br />
<br />
Comments:<br />
<?php echo $_POST['comments']; ?>
</body>
</html>

If you saved this code in a file called "myform.php", filled the fields in the test.html form and hit the
Submit button, the myform.php output would look something like this:

Your name is: John Doe


Your email: john@doe.com
Do you like this website? Yes
Comments:
This is my comment...

Quite simple, isn't it? But the most important thing is still missing! You need to validate submitted
data to protect your script (and thus your website and server) from malicious code.

Let's say you display all data submitted with the form in a HTML file (like a guestbook does for
example). Now consider someone types this code instead of his name:
<script>location.href('http://www.SPAM.com')</script>

If this is stored in a HTML file anyone who tried to view it would be redirected to
http://www.SPAM.com! And this is the least that can happen! Failure to properly validate input
data is the main reason for most vulnerabilities and exploits in PHP scripts. You wouldn't want
someone to hack your website, erase all data and upload his/her own "u \/\/3R3 H4><0r3d!"
homepage, would you?

Prevent Duplicate Form Submission

You can use the method below to prevent duplicate form submission or form re-submission using
PHP. This method is simple to implement and does not require JavaScript.

I will assume that the form is in the form.php file and the form submission is being handled by the
form-exec.php script.

Modifying your form

Add this PHP code to the top of the form.php script:

<?php
session_start();
$secret=md5(uniqid(rand(), true));
$_SESSION['FORM_SECRET']=$secret;
?>

In the PHP code above we create a unique ID using the uniqid() function and then create a 32
character hash of this unique ID using md5() function. Next we store this unique ID in the session
for later use in the form-exec.php script. Remember to use a different session variable for each
form.

Then add a hidden field anywhere in your form:

<input type="hidden" name="form_secret" id="form_secret"


value="<?php echo $_SESSION['FORM_SECRET'];?>" />

Handling form submission

Compare the value of the hidden field with the value stored in the session. If the values match,
process the form data. After processing the form data unset the value stored in the session. Now
if the user refreshes the page, the form processing code will be skipped. See the sample code
below.

<?php
session_start();
//Retrieve the value of the hidden field
$form_secret=$_POST['form_secret'];
if(isset($_SESSION['FORM_SECRET'])) {
if(strcasecmp($form_secret,$_SESSION['FORM_SECRET'])===0) {
/*Put your form submission code here
After processing the form data,
unset the secret key from the session
*/
unset($_SESSION['FORM_SECRET']);
}else {
//Invalid secret key
}
}else {
//Secret key missing
echo 'Form data has already been processed!';
}
?>

PHP Sessions

As you may know HTTP is a stateless protocol which means that each server request knows
nothing about the others. What does it mean in our case?

Suppose a login system where a visitor can log in and the logged in users have more rights on the
site. It means that the login page, let's say login.php has information about the user. However if
the user visits a page eg.: myprofile.php then you lose all of the data you have on login.php. So
on each page load all old datav will be lost.

To solve this problem the sessions were introduced in PHP. Using sessions you can transfer data
between various pages. If you are using sessions then each of your visitors will got a unique id.
This id will identify various visitors and with the help of this id are the user data stored on the
server.

Session handling can be fine tune with PHP parameters. Just run the following small code and
you will get you actual PHP settings:

Code:

1. <?PHP
2. phpinfo();
3. ?>

If you scroll down in the output you will find a complete section with session settings like this:

Session
Session Support enabled
Registered save handlers files user
Registered serializer handlers php php_binary wddx
Directive Local Value Master Value
session.auto_start Off Off
session.bug_compat_42 Off Off

Most important session parameters

In this section I will explain the most important session parameters. If one or more example from
this tutorial doesn't work then you need to check these session parameters.

 session.auto_start : specifies whether the session module starts a session automatically


on request startup. Defaults to 0 (disabled).

 session.name : specifies the name of the session which is used as cookie name. It
should only contain alphanumeric characters. Defaults to PHPSESSID.

 session.save_handler : defines the name of the handler which is used for storing and
retrieving data associated with a session. Defaults to files.

 session.save_path : defines the argument which is passed to the save handler. If you
choose the default files handler, this is the path where the files are created. Defaults to
/tmp.

 session.use_cookies : specifies whether the module will use cookies to store the session
id on the client side. Defaults to 1 (enabled).

 session.use_only_cookies : specifies whether the module will only use cookies to store
the session id on the client side. Enabling this setting prevents attacks involved passing
session ids in URLs.

 session.cookie_lifetime : specifies the lifetime of the cookie in seconds which is sent to


the browser. The value 0 means "until the browser is closed." Defaults to 0.

 session.cookie_path : specifies path to set in session_cookie. Defaults to /.

 session.use_trans_sid : whether transparent sid support is enabled or not. Defaults to 0


(disabled).

The only you maybe need to change is the session.save_path. Choose a valid and writeable
directory.

Starting a session

After the introduction it's time to implement your first session based web site.

First of all you need to start the session with the session_start() function. Note that this function
should be called before any output is generated! This function initialise the $_SESSION
superglobal array where you can store your data. So for example let's store user name in the
session. You can do it as follows:
Code: session.php

1. <?php
2. session_start();
3. $_SESSION['username'] = 'John';
4. ?>

Now if you create a new file where you want to display the username you need to start the
session again. In this case PHP checks whether session data are sored with the actual id or not. If
it can find it then initialise the $_SESSION array with that values else the array will be empty. So a
code which displays the username looks like this:
Code: session2.php

1. <?php
2. session_start();
3. echo "User : ".$_SESSION['username'];
4. ?>

That's it. If it doesn't work then check your session settings.

Check sessions

In the previous example I used 2 different files to demonstarte basic session behaviour. However
by checking session status we can create a much better code. To check whether a session
variable exists or not you can use the isset() function.

So in the next code we will first check if the username is set or not. If it is not set yet then we will
set it else we will display it. As result if call the code twice you will get different output. The code is
the following:

Code:

1. <?php
2. session_start();
3. if (isset($_SESSION['username'])){
4. echo "User : ".$_SESSION['username'];
5. } else {
6. echo "Set the username";
7. $_SESSION['username'] = 'John';
8. }
9. ?>

However if you have executed the first example as well then you will never get the message "Set
the username" as you have done it in your very first call. If you wait until the session is expired
and execute the code again you will get the set message.

In the next step you will learn how to clean session data.

Clean and destroy session


Sometimes it is important to remove a session variable or destroy the complete session.
Such mechanism is used for example during a user logs out from a site.

To remove a variable from a session is quite easy. You just have to call the unset()
function to do this. Now you can extend our example code to unset the username as
follows:

Code:

1. session_start();
2. if (isset($_SESSION['username'])){
3. echo "User : ".$_SESSION['username'];
4. unset($_SESSION['username']);
5. } else {
6. echo "Set the username";
7. $_SESSION['username'] = 'John';
8. }

The result of this code is similar to a login/logout system. If the user is logged in then we display
the name than log him off. In the next execution we log him in again.
You can use the session_destroy() function if you want to remove all session data, but be careful
with it.
Code:

1. <?PHP
2. session_start();
3. if (isset($_SESSION['username'])){
4. echo "User : ".$_SESSION['username'];
5. session_destroy();
6. } else {
7. echo "Set the username";
8. $_SESSION['username'] = 'John';
9. }
10. ?>

PHP Cookies - Background

Cookies have been around for quite some time on the internet. They were invented to allow
webmaster's to store information about the user and their visit on the user's computer.

At first they were feared by the general public because it was believed they were a serious privacy
risk. Nowadays nearly everyone has cookies enabled on their browser, partly because there are
worse things to worry about and partly because all of the "trustworthy" websites now use cookies.

This lesson will teach you the basics of storing a cookie and retrieving a cookie, as well as
explaining the various options you can set with your cookie.
Creating Your First PHP Cookie

When you create a cookie, using the function setcookie, you must specify three arguments. These
arguments are setcookie(name, value, expiration):

1. name: The name of your cookie. You will use this name to later retrieve your cookie, so
don't forget it!
2. value: The value that is stored in your cookie. Common values are username(string) and
last visit(date).
3. expiration: The date when the cookie will expire and be deleted. If you do not set this
expiration date, then it will be treated as a session cookie and be removed when the
browser is restarted.

In this example we will be creating a cookie that stores the user's last visit to measure
how often people return to visit our webpage. We want to ignore people that take longer
than two months to return to the site, so we will set the cookie's expiration date to two
months in the future!

PHP Code:

<?php
//Calculate 60 days in the future
//seconds * minutes * hours * days + current time
$inTwoMonths = 60 * 60 * 24 * 60 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $inTwoMonths);
?>

Don't worry if you can't follow the somewhat involved date calculations in this example.
The important part is that you know how to set a cookie, by specifying the three important
arguments: name, value and expiration date.

Retrieving Your Fresh Cookie

If your cookie hasn't expired yet, let's retrieve it from the user's PC using the aptly named
$_COOKIE associative array. The name of your stored cookie is the key and will let you
retrieve your stored cookie value!

PHP Code:

<?php
if(isset($_COOKIE['lastVisit']))
$visit = $_COOKIE['lastVisit'];
else
echo "You've got some stale cookies!";

echo "Your last visit was - ". $visit;


?>
This handy script first uses the isset function to be sure that our "lastVisit" cookie still
exists on the user's PC, if it does, then the user's last visit is displayed. If the user visited
our site on February 28, 2008 it might look something like this:

Display:

Your last visit was - 11:48 - 02/28/08

Potrebbero piacerti anche