You are on page 1of 34

VKS-LEARNING HUB

PHP-FORM VALIDATION

VKS-LEARNING HUB

PHP-6: PHP Forms


When a forms Submit button is clicked, the form is submitted. Where?
How? What happens then?
Where? - The form is submitted to the URL mentioned in the Action attribute
of the form. Usually this URL refers to a web page on the server.
How? The forms data is sent to the server. This data is sent by Get or
Post method, whichever is mentioned in the Method attribute of the form.
What happens then? The web page (on the server) processes this data
and performs the requisite operation. This requisite operation may be to
generate another relevant web page and to send it to the user, or just to
prepare an acknowledgement and send it to the user, or any other
operation.

VKS-LEARNING HUB

The superglobal $_SERVER can be used to check the method used for form
submission. To understand this, create an HTML file with two forms one to
be submitted by POST method and one to be submitted by GET method.
Sample code is given below:

VKS-LEARNING HUB

A form can be submitted to the page containing the form itself by specifying the
files URL in action attribute. To avoid any mistake in specifying the URL, we can
use:
<?php echo $_SERVER[PHP_SELF] ?>
<?php
echo "form submitted by ".$_SERVER["REQUEST_METHOD"]." method"; ?>
<html>
<body>
<form name="f1" method= POST" action="<?php echo $_SERVER[PHP_SELF];?>">
Name: <input type= "text" name="uName" value = "<?php echo $_POST [uName] ;?>">
<input type= submit>
</form>
<form name="f2" method=GET" action="<?php echo $_SERVER[PHP_SELF];?>>
Name: <input type=" text" name="uName" value = "<?php echo $_GET [uName];?>">
<input type= submit>
</form>
</body> </html>

VKS-LEARNING HUB

Observe the Last line of the output


which states that Form submitted
using GET method. The page is just
loaded and the user has not clicked any
submit button, even then the page is
reporting that Form submitted using
GET method. The reason is that
$_SERVER[REQUEST_METHOD] takes
the default value GET even if no form is
submitted. If we submit the form after
loading the page, it will work as
expected.

The $_POST variable is used to


collect values from a form with
method="post
Information sent from a form with
the POST method is invisible to
others and has no limits on the
amount of information to send

VKS-LEARNING HUB

The $_GET variable is used to collect values from a form with


method="get"
Information sent from a form with the GET method is visible to
everyone (it will be displayed in the browser's address bar) and it
has limits on the amount of information to send Data sent by GET
method is restricted to 1024 characters.

VKS-LEARNING HUB

A forms data is received by the php file (specified in the


Action attribute of the form) in the superglobals $_POST
and $_GET depending on the method used to submit the
form.
The data is also received in the Superglobal $_REQUEST
irrespective of the method used to submit the form.
$_POST, $_GET, and $_REQUEST are associative arrays
with the indices represented by the names of the controls on
the form and the values are the values of the controls on the
form. This is shown in the following example:

VKS-LEARNING HUB
<html> <body>
<form name="f1 method="post" action="<?php echo $_SERVER[PHP_SELF]; ?>">
Name: <input type= "text" name="uName" value="<?php echo $_POST[uName];?>">
Age: <input type= "text" name="uAge" value = "<?php echo $_POST[uAge];?>">
<input type= submit>
</form>

<form name="f2" method="get" action="<?php echo $_SERVER[PHP_SELF] ?>">


Name: <input type=" text" name="uName" value="<?php echo $_GET[uName];?>">
Age: <input type= "text" name="uAge" value = "<?php echo $_GET[uAge];?>">
<input type= submit>
</form>
<?php
echo $_POST[uName]."<br>";
echo $_POST[uAge]."<br>";
echo $_GET[uName]."<br>";
echo $_GET[uAge]."<br>";
echo $_REQUEST[uName]."<br>";
echo $_REQUEST[uAge]."<br>"; ?>
</body> </html>

VKS-LEARNING HUB

VKS-LEARNING HUB
There is another way to check whether a form is submitted or not. If submitted,
then by which method. This is done by using the function function isset() along
with superglobals $_GET and $_POST Following code shows how to do it.
<?php
if(isset($_POST['submit']))
echo "For Submitted by POST method";
else if (isset($_GET['submit']))
echo "For Submitted by GET method";
else echo " Please Fill the form and submit";
?>

<html><body>
<form name="f2" method="get" action="<?php echo $_SERVER[PHP_SELF] ?>">
Name: <input type=" text" name="uName" value="<?php echo $_POST[uName];?>">
<input type= submit name=submit>
</form>
<form name="f2" method= "get" action="<?php echo $_SERVER[PHP_SELF] ?>">
Name: <input type=" text" name="uName" value = "<?php echo $_GET[uName] ;?>">
<input type= submit name="submit">
</form>
</body></html>

VKS-LEARNING HUB

VKS-LEARNING HUB

The function isset() is used to check if a variable is declared and has some
value assigned to it. The function empty() is used to check whether a
variable is empty. The function empty() and isset() are opposite of each
other as shown in following example:

VKS-LEARNING HUB
There are multiple uses of the function preg_match(). Here it is used to check
whether a given string is in a particular pattern or not. It is done for two cases:
To check that name contains alphabets and spaces only
To check that age (or any other numeric value) contains digits only
For this purpose preg_match() uses regular expressions. Regular expressions
are not in our syllabus and there these are not discussed here in details. The
regular expression /^[a-zA-z ]+$/ specifies a string of one or more alphabets
(any combination of small and capital alphabets) and spaces. The regular
expression /^[0-9]{1,3}$/ specifies a string of digits, the length of the string
can be 1 to 3 digits.
/ / start & end of regular expression
^ starts with
$ ends with
{start, end } indicates length between start and end
[ ] group
/[a-zA-z ]/ represent any alphabet upper or lower case only
[0-9] represent any number from 0 to 9
Example:

VKS-LEARNING HUB

Basic Regular Expression


/abc/

in PHP, regexes are strings that


begin and end with /
the simplest regexes simply match a
particular substring
the above regular expression
matches any string containing "abc":
YES: "abc", "abcdef", "defabc",
".=.abc.=.", ...
CS380
14
NO: "fedcba", "ab c", "PHP", ...

VKS-LEARNING HUB

Wildcards
A dot . matches any character
except a \n line break
"/.oo.y/" matches "Doocy", "goofy",
"LooNy", ...

A trailing i at the end of a regex


(after the closing /) signifies a
case-insensitive match
"/is/i" matches Tennis", His",
Isotopes CS380
15

VKS-LEARNING HUB

Special characters: |, (), ^, \


| means OR
"/abc|def|g/" matches "abc", "def", or
"g"
There's no AND symbol. Why not?

() are for grouping


"/(FAIPS|DPS) Kuwait/" matches FAIPS
Kuwait" or DPS Kuwait"

^ matches the beginning of a line; $


the end
"/^<!--$/"matches
a line that 16consists
CS380

VKS-LEARNING HUB

Special characters: |, (), ^, \


\ starts an escape sequence
many characters must be escaped
to match them literally: / \ $ . [ ] ( )
^*+?
"/<br \/>/" matches lines containing
<br /> tags

CS380

17

VKS-LEARNING HUB

Quantifiers: *, +, ?
* means 0 or more occurrences
"/abc*/" matches "ab", "abc", "abcc",
"abccc", ...
"/a(bc)*/" matches "a", "abc", "abcbc",
"abcbcbc", ...
"/a.*a/" matches "aa", "aba", "a8qa", "a!?
_a", ...

+ means 1 or more occurrences


"/a(bc)+/" matches "abc", "abcbc",
"abcbcbc", ...
"/Goo+gle/" matches "Google", "Gooogle",
18
"Goooogle", ...CS380

VKS-LEARNING HUB

More quantifiers:
{min,max}

{min,max} means between min and


max occurrences (inclusive)
"/a(bc){2,4}/" matches "abcbc",
"abcbcbc", or "abcbcbcbc

min or max may be omitted to


specify any number
{2,} means 2 or more
{,6} means up to 6
{3} means exactly
3
CS380

19

VKS-LEARNING HUB

Character sets: []
[] group characters into a character set;
will match any single character from the
set
"/[bcd]art/" matches strings containing "bart",
"cart", and "dart"
equivalent to "/(b|c|d)art/" but shorter

inside [], many of the modifier keys act as


normal characters
"/what[!*?]*/" matches "what", "what!", "what?
**!", "what??!"

What regular expression matches DNA


20
(strings of A, C, G, or T)?

VKS-LEARNING HUB

<?php
if( preg_match("/test/", "a test of preg_match")==1)
echo "match found";
else
echo "match not found";
if( preg_match("/tutorial/", "a test of
preg_match")==1)
echo "\nmatch found";
else
echo "\nmatch not found";
# replace vowels with stars
$str = "the quick brown fox";
$str = preg_replace("/[aeiou]/", "*", $str);
echo "<br>".$str;
?>

VKS-LEARNING HUB

VKS-LEARNING HUB

VKS-LEARNING HUB

Filter_var() function is used to check whether a variable is a correct email


address, URL, or integer etc. For this purpose, Filter_var() uses some
predefined filters.
filter_var() will do, both, sanitize and validate data. What's the difference
between the two?
Sanitizing will remove any illegal character from the data.
Validating will determine if the data is in proper form.
Some of the most frequently used filters for Validate are:
FILTER_VALIDATE_EMAIL: Validates whether the value is a valid email
address.
FILTER_VALIDATE_FLOAT: Validates whether the value is a floating point
number, and converts to float on success.
FILTER_VALIDATE_INT: Validates whether the value is an integer number,
and converts to float on success.
FILTER_VALIDATE_IP: Validates whether the value is an IP address.
FILTER_VALIDATE_URL: Validates whether the value is a URL.

VKS-LEARNING HUB
Some of the most frequently used filters for Sanitize are:
FILTER_SANTIZE_EMAIL: Remove all illegal characters from an email address
FILTER_SANTIZE_URL: Remove all illegal characters from a URL.
FILTER_SANTIZE_FLOAT: Remove all characters except digits, +- and ,eE.
FILTER_SANTIZE_INT: Remove all characters except digits, plus and minus sign.
FILTER_SANTIZE_IP: Remove all illegal characters from IP address.
<?php
$a="vks@faips.ed";
$b="www.cbse.nic.in";
$c="http://www.cbse.nic.in";
$d="vks@faips";
$e=123;
$f=123.55;
$ip="127.0.0.1";
$ip1="123.0.1.1.1";
if(!FILTER_VAR($a,FILTER_VALIDATE_EMAIL))
echo "<B>$a</B > is not a valid email id<BR>";
else echo "<B>$a</B > is a valid email id<BR>";
if(!FILTER_VAR($b,FILTER_VALIDATE_EMAIL))
echo "<B>$b</B > is not a valid email id<BR>";
else echo "<B>$b</B > is a valid email id<BR>";

VKS-LEARNING HUB
if(!FILTER_VAR($d,FILTER_VALIDATE_INT))
echo "<B>$d</B > is not a valid INT<BR>";
else echo "<B>$d</B > is a valid INT<BR>";
if(!FILTER_VAR($e,FILTER_VALIDATE_INT))
echo "<B>$e</B > is not a valid INT<BR>";
else echo "<B>$e</B > is a valid INT<BR>";
if(!FILTER_VAR($c,FILTER_VALIDATE_URL))
echo "<B>$c</B > is not a valid URL<BR>";
else echo "<B>$c</B > is a valid URL<BR>";
if(!FILTER_VAR($d,FILTER_VALIDATE_URL))
echo "<B>$d</B > is not a valid URL<BR>";
else echo "<B>$d</B > is a valid URL<BR>"
if(!FILTER_VAR($f,FILTER_VALIDATE_FLOAT))
echo "<B>$f</B > is not a valid FLOAT<BR>";
else echo "<B>$f</B > is a valid FLOAT<BR>";
if(!FILTER_VAR($a,FILTER_VALIDATE_FLOAT))
echo "<B>$a</B > is not a valid FLOAT<BR>";
else echo "<B>$a</B > is a valid FLOAT<BR>";

VKS-LEARNING HUB
if(!FILTER_VAR($ip,FILTER_VALIDATE_IP))
echo "<B>$ip</B > is not a valid IP<BR>";
else echo "<B>$ip</B > is a valid IP<BR>";
if(!FILTER_VAR($ip1,FILTER_VALIDATE_IP))
echo "<B>$ip1</B > is not a valid IP<BR>";
else echo "<B>$ip1</B > is a valid IP<BR>";
?>
<?php
$str ="<h1>Hello World!</h1>";
// Remove HTML tags from string
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo$newstr;
?>
<?php
$email = "faips(.kwt)@exa//mple.com";
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $email; ?>

VKS-LEARNING HUB
<?php
$var="http://www.faipskuwait.com";
$url =filter_var($var, FILTER_SANITIZE_URL));
echo $url;
?>

Validating Example
Just because the data is sanitized does not ensure that it's properly formatted. In the example
below, the data need to be sanitized, but it's obvious that the user input is not an email or url.

Note: why sanitize and not just validate? It's possible the user accidentally typed in a
wrong character or maybe it was from a bad copy and paste. By sanitizing the data, you
take the responsibility of hunting for the mistake off of the user.

VKS-LEARNING HUB
<?php
if (isset($_POST['email'])) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "$email is a valid email address.<br/><br/>"; }
else { echo "$email is <strong>NOT</strong> a valid email address.<br/><br/>"; }
}
if (isset($_POST['homepage'])) {
$homepage = filter_var($_POST['homepage'], FILTER_SANITIZE_URL);
if (filter_var($homepage, FILTER_VALIDATE_URL)) {
echo "$homepage is a valid URL.<br/><br/>";}
else { echo "$homepage is <strong>NOT</strong> a valid URL.<br/><br/>"; }
}
?>
<html><body>
<form name="form1" method="post" action="<?php echo($_SERVER["PHP_SELF"]);?>">
Email Address: <br/>
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="50"/>
<br/><br/> Home Page: <br/>
<input type="text" name="homepage" value="<?php echo $_POST['homepage']; ?>"
size="50" /> <br/> <br/>
<input type="submit" />
</form>
</body></html>

VKS-LEARNING HUB

The function count() is used to count


the number of elements in an array.
Example:

VKS-LEARNING HUB
First let us take an example where some data about the salary of an employee is
filled in a form and the form is submitted to a php file. The php file takes this data
and performs some caculations to calculate detailed salary. The complete data is
then displayed on the browser.

VKS-LEARNING HUB

VKS-LEARNING HUB
The Query String
When a form is submitted using GET method, the forms data is sent to the
server in the form of (variable=value) pairs. A variable and its value are
separated by equality sign (=) and different (variable=value) pairs are
separated by ampersand sign (&).This complete set of (variable=value) pairs is
called Query String and is visible in the URL as shown below:

Notice that the query string is specified by the values following the question
mark (?). When a form is submitted by GET method, this query string is visible in
the URL. A PHP script retrieves this string in $_SERVER[QUERY_SRING].

VKS-LEARNING HUB
Query Strings are used to pass information from a browser to a web server.
Several different processes can generate a query string. Query strings are
generated by sending a form, by a user typing a query in the address box of the
browser or in the anchor tag as shown in the following example:
<HTML> <body>
Select your favourite color: <p>
<a href ="http://localhost/12/choiceclr.php?favclr=red"?> RED</a> <BR>
<a href ="http://localhost/12/choiceclr.php?favclr=green"?> GREEN</a> <BR>
<a href = "http://localhost/Test for Notes/choiceclr.php?favclr=blue"?> BLUE</a>
</body> </html>
This page contains three hyperlinks each of which contains a query string. This
query string is passed to the page choiceclr.php when a hyperlink is clicked. The
code for choiceclr.php is given below:
<!-- choiceclr.php -->
<HTML>
<BODY>
Your favourite color is <font color = <?php echo $_GET["favclr"]; ?> >
<?php echo $_GET["favclr"]; ?> </font>
</BODY>