2-PHP Form
2-PHP Form
FORM PHP
L. Erawan
Sistem Informasi - Fasilkom
Contents
PHP Form Handling .......................................................................................................................... 4
PHP - A Simple HTML Form ...................................................................................................... 4
Example ........................................................................................................................................... 4
Example ........................................................................................................................................... 4
GET vs. POST ................................................................................................................................. 5
When to use GET?........................................................................................................................ 5
When to use POST? ..................................................................................................................... 6
PHP Form Validation ........................................................................................................................ 7
PHP Form Validation .................................................................................................................... 7
Text Fields ....................................................................................................................................... 7
Radio Buttons ................................................................................................................................ 7
The Form Element ........................................................................................................................ 8
Big Note on PHP Form Security .............................................................................................. 8
How To Avoid $_SERVER["PHP_SELF"] Exploits? ............................................................ 9
Validate Form Data With PHP .................................................................................................. 9
Example ......................................................................................................................................... 10
PHP Forms - Required Fields ...................................................................................................... 11
PHP - Required Fields ............................................................................................................... 11
PHP - Display The Error Messages....................................................................................... 12
Example ......................................................................................................................................... 12
PHP Forms - Validate E-mail and URL .................................................................................... 13
PHP - Validate Name ................................................................................................................. 13
PHP - Validate E-mail ................................................................................................................ 13
PHP - Validate URL..................................................................................................................... 13
PHP - Validate Name, E-mail, and URL .............................................................................. 14
Example ......................................................................................................................................... 14
PHP Complete Form Example .................................................................................................... 15
PHP - Keep The Values in The Form ................................................................................... 15
PHP Sessions .................................................................................................................................... 16
PHP Session Variables .............................................................................................................. 16
Starting a PHP Session ............................................................................................................. 16
Storing a Session Variable ...................................................................................................... 16
Page 2
Destroying a Session ................................................................................................................ 17
Page 3
PHP Form Handling
The PHP superglobals $_GET and $_POST are used to collect form-data.
Example
<html>
<body>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The "welcome.php" looks
like this:
<html>
<body>
</body>
</html>
Welcome John
Your email address is [email protected]
The same result could also be achieved using the HTTP GET method:
Example
<html>
<body>
Page 4
</body>
</html>
<html>
<body>
</body>
</html>
The code above is quite simple. However, the most important thing is missing. You need to
validate form data to protect your script from malicious code.
This page does not contain any form validation, it just shows how you can send and
retrieve form data.
However, the next pages will show how to process PHP forms with security in mind! Proper
validation of form data is important to protect your form from hackers and spammers!
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that
they are always accessible, regardless of scope - and you can access them from any function, class
or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
Note: GET should NEVER be used for sending passwords or other sensitive information!
Page 5
When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request) and has no limits on the amount of information
to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while
uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the
page.
Page 6
PHP Form Validation
This and the next chapters show how to use PHP to validate form data.
These pages will show how to process PHP forms with security in mind. Proper validation
of form data is important to protect your form from hackers and spammers!
The HTML form we will be working at in these chapters, contains various input fields: required and
optional text fields, radio buttons, and a submit button:
First we will look at the plain HTML code for the form:
Text Fields
The name, email, and website fields are text input elements, and the comment field is a textarea.
The HTML code looks like this:
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Page 7
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
When the form is submitted, the form data is sent with method="post".
The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the
currently executing script.
So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of
jumping to a different page. This way, the user will get error messages on the same page as the
form.
The htmlspecialchars() function converts special characters to HTML entities. This means
that it will replace HTML characters like < and > with < and >. This prevents
attackers from exploiting the code by injecting HTML or Javascript code (Cross-site
Scripting attacks) in forms.
If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site
Scripting (XSS) commands to execute.
Now, if a user enters the normal URL in the address bar like
"http://www.example.com/test_form.php", the above code will be translated to:
Page 8
So far, so good.
However, consider that a user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/scrip
t%3E
This code adds a script tag and an alert command. And when the page loads, the JavaScript code
will be executed (the user will see an alert box). This is just a simple and harmless example how
the PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the <script> tag! A hacker can
redirect the user to a file on another server, and that file can hold malicious code that can alter the
global variables or submit the form to another address to save the user data, for example.
The htmlspecialchars() function converts special characters to HTML entities. Now if the user tries
to exploit the PHP_SELF variable, it will result in the following output:
<form method="post"
action="test_form.php/"><script>alert('hacked')</script>">
When we use the htmlspecialchars() function; then if a user tries to submit the following in a text
field:
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code, like this:
<script>location.href('http://www.hacked.com')</script>
Page 9
We will also do two more things when the user submits the form:
1. Strip unnecessary characters (extra space, tab, newline) from the user input data (with
the PHP trim() function)
2. Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
The next step is to create a function that will do all the checking for us (which is much more
convenient than writing the same code over and over again).
Now, we can check each $_POST variable with the test_input() function, and the script look like
this:
Example
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Notice that at the start of the script, we check whether the form has been submitted using
$_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has been
submitted - and it should be validated. If it has not been submitted, skip the validation and display
a blank form.
However, in the example above, all input fields are optional. The script works fine even if the user
do not enter any data.
The next step is to make input fields required and create error messages if needed.
Page
10
PHP Forms - Required Fields
This chapter show how to make input fields required and create error messages if needed.
In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and
$websiteErr. These error variables will hold error messages for the required fields. We have also
added an if else statement for each $_POST variable. This checks if the $_POST variable is empty
(with the PHP empty() function). If it is empty, an error message is stored in the different error
variables, and if it is not empty, it sends the user input data through the test_input() function:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}
if (empty($_POST["website"]))
{$website = "";}
else
{$website = test_input($_POST["website"]);}
if (empty($_POST["comment"]))
Page
11
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
if (empty($_POST["gender"]))
{$genderErr = "Gender is required";}
else
{$gender = test_input($_POST["gender"]);}
}
?>
Example
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
</form>
The next step is to validate the input data, that is "Does the Name field contain only letters and
whitespace?", and "Does the E-mail field contain a valid e-mail address syntax?", and if filled out,
"Does the Website field contain a valid URL?".
Page
12
PHP Forms - Validate E-mail and URL
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
The preg_match() function searches a string for pattern, returning true if the
pattern exists, and false otherwise.
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-
a-z0-9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
Page
13
PHP - Validate Name, E-mail, and URL
Now, the script looks like this:
Example
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"]))
{$website = "";}
else
{
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also
allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
if (empty($_POST["gender"]))
{$genderErr = "Gender is required";}
else
{$gender = test_input($_POST["gender"]);}
}
?>
Page
14
PHP Complete Form Example
This chapter show how to keep the values in the input fields when the user hits the submit
button.
Then, we also need to show which radio button that was checked. For this, we must manipulate
the checked attribute (not the value attribute for radio buttons):
Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
Page
15
PHP Sessions
A PHP session variable is used to store information about, or change settings for a user
session. Session variables hold information about one single user, and are available to all
pages in one application.
A PHP session solves this problem by allowing you to store user information on the server for later
use (i.e. username, shopping items, etc). However, session information is temporary and will be
deleted after the user has left the website. If you need a permanent storage you may want to
store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID.
The UID is either stored in a cookie or is propagated in the URL.
Note: The session_start() function must appear BEFORE the <html> tag:
<html>
<body>
</body>
</html>
The code above will register the user's session with the server, allow you to start saving user
information, and assign a UID for that user's session.
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
Page
16
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
Output:
Pageviews=1
In the example below, we create a simple page-views counter. The isset() function checks if the
"views" variable has already been set. If "views" has been set, we can increment our counter. If
"views" doesn't exist, we create a "views" variable, and set it to 1:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy()
function.
<?php
session_start();
if(isset($_SESSION['views']))
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
Note: session_destroy() will reset your session and you will lose all your stored session data.
Page
17