Jun
26
2011

PHP Form: Validation and Security

This article is the continuation of our PHP Form Tutorial Series. If you are not yet familiar with our previous stones, it is highly recommended you go through them first: Inserting, Retrieving and Security. The scripts that you saw in our previous stones were solely for introduction purposes only; we highly discourage using those scripts in any live application. Now, in this article, we introduce validation of form data including security and filtering.

Download File

form.php


<html>

<?php 

function escape_value( $data ) {
	if( ini_get ( 'magic_quotes_gpc') ) {
		$data = stripslashes($data);
        }
	return mysql_real_escape_string($data);
}

function output ( $data ) {
	return stripslashes(htmlentities($data, ENT_QUOTES) );
}

// check if form is submitted
if ( isset ( $_POST['submit'] ) )
	{
		// connect to database
		$link = mysql_connect ( "localhost", "root", "root" );
		$db = mysql_select_db ( "db_table", $link );

		// check for name;
		if ( eregi ("^[a-zA-Z][a-zA-Z ]+$", stripslashes( trim ( $_POST['txt_name'] ) ) ) ) {
			$pname = escape_value ( $_POST['txt_name'] );
		}
		else {
			$pname = FALSE;
			$pname = escape_value ( $_POST['txt_name'] );
			echo output( $pname );

			echo "Invalid Name<br>";
		}

		//check for class
		if ( eregi ("^[a-zA-Z][a-zA-Z ]+$", stripslashes( trim ( $_POST['txt_class'] ) ) ) ) {
			$pclass = escape_value ( $_POST['txt_class'] );
		}
		else {
			$pclass = FALSE;
			echo "Invalid Class<br>";
		}

		//check for section
		if ( eregi ("^[a-zA-Z]+$", stripslashes( trim ( $_POST['txt_sec'] ) ) ) ) {
			$psec = escape_value ( $_POST['txt_sec'] );
		}
		else {
			$psec = FALSE;
			echo "Invalid Section<br>";
		}

		// check for gender
		if ( $_POST['opt_gen'] != "") {
			$poptgen = escape_value ( $_POST['opt_gen'] );
		}
		else {
			$poptgen = FALSE;
			echo "Pick Gender<br>";
		}

		// check for description
		if ( strlen ( $_POST['txt_yourself'] )  > 0 )  {
			$pdesc = escape_value ( $_POST['txt_sec'] );
		}
		else {
			$pdesc = FALSE;
			echo "Invalid Description<br>";
		}

	// if all fields are fine
	if ($pname && $pclass && $psec && $poptgen && $pdesc) {

	$sql = "INSERT INTO tbl_test VALUES('','$pname','$pclass','$psec','$poptgen', '$pdesc')";
	mysql_query($sql) or die(mysql_error());

	$affRows = mysql_affected_rows();

		if( $affRows == 1) {
			echo "Profile added successfully";
		}

		else {
			echo "Profile cannot be added";
		}

	mysql_close();
	} else {
		echo "Some error occured. Please try again.";
	}

}
?>

<head>
	<link rel="stylesheet" type="text/css" href="style.css" />
	<title>Simple Form</title>
</head>

<body>

<table border="0" width="400">
<form action="<?php echo $PHP_SELF; ?>" method="post" name="index">

<tr>
	<td colspan="2" align="center">FORM</td>
</tr>

<tr>
	<td>Name: </td>
	<td><input type="text" name="txt_name" size="30" maxlength="30" value="<?php if ( isset($_POST['txt_name']) ) echo output( $_POST['txt_name'] ); ?>" /></td>
</tr>

<tr>
	<td>Stream: </td>
	<td><input type="text" name="txt_class" value="<?php if ( isset($_POST['txt_class']) ) echo output( $_POST['txt_class'] ); ?>" /></td>
</tr>

<tr>
	<td>Section: </td>
	<td><input type="text" name="txt_sec" maxlength="2" value="<?php if ( isset($_POST['txt_sec']) ) echo output( $_POST['txt_sec'] ); ?>" /></td>
</tr>

<tr>
	<td>Gender: </td>
	<td><input type="radio" name="opt_gen" value="M" <?php if ( isset($_POST['opt_gen']) && $_POST['opt_gen'] == 'M') echo "checked"; ?> />Male
		<input type="radio" name="opt_gen" value="F" <?php if ( isset($_POST['opt_gen']) && $_POST['opt_gen'] == 'F') echo "checked"; ?> />Female</td>
</tr>

<tr>
	<td>Short Description about yourself</td>
	<td><textarea name ="txt_yourself" cols="30" rows="5"  ><?php if ( isset($_POST['txt_yourself']) ) echo output( $_POST['txt_yourself'] ); ?></textarea></td>
</tr>

<tr>
	<td> <input type="submit" name="submit" value="submit" /></td>
	<td> <input type="button" name="view_list" value="view list"
	onClick="javascript:  document.location='viewform_list.php';"> </td>
</tr>

</form>
</table>

</body>
</html>

Explanation

If you are not yet familiar with the working of this script, you can go check out the simpler version
in PHP Forms for Absolute Beginners. It is recommended you to go through that first.

mysql_real_escape_string() input function

function escape_value( $data ) {
	if( ini_get ( 'magic_quotes_gpc') ) {
		$data = stripslashes($data);
        }
	return mysql_real_escape_string($data);
}

As discussed in Form Security, we use an escape_value() function to all the data that are to be inserted/updated in to database table. To know more about escape_value(), please refer to our previous stone..

htmlentities() output function

function output ( $data ) {
	return stripslashes(htmlentities($data, ENT_QUOTES) );
}

We use htmlentities() function to output the database data for security reasons. htmlentities() converts all the special characters into HTML entity equivalents. Thus, the browser interprets the converted HTML equivalent in a special way so that it doesn’t change the script of our code and original values are preserved. For more, read Form Security.

Validation using Regular Expression

// check for name;
		if ( eregi ("^[a-zA-Z][a-zA-Z ]+$", stripslashes( trim ( $_POST['txt_name'] ) ) ) ) {
			$pname = escape_value ( $_POST['txt_name'] );
		}
		else {
			$pname = FALSE;
			$pname = escape_value ( $_POST['txt_name'] );
			echo output( $pname );

			echo "Invalid Name<br>";
		}

We use regular expression to check if the string has alphabets (alpha numberic) and spaces only. We have used different regular expression for different validation. For more regular expression, check Regular Expression.

Checking if all validations are ok

if ($pname && $pclass && $psec && $poptgen && $pdesc) {

}

In Line 28,

$pname = FALSE;

We initialized the variable to FALSE if the validation fails. If all the variables are initialized (not FALSE), we proceed to inserting values to the database.

Output other values when validation fails

<td><input type="text" name="txt_name" size="30" maxlength="30" value="<?php if ( isset($_POST['txt_name']) ) echo output( $_POST['txt_name'] ); ?>" /></td>

This is for user-friendliness so that the user doesn’t need to type all the values again if any one validation fails.


viewform_list.php

<html>

<?php

function output ( $data ) {
	return stripslashes(htmlentities($data, ENT_QUOTES) );
}

?>

<head>
	<link rel="stylesheet" type="text/css" href="style.css" />
	<title>List</title>
</head>

<body>

<table border="0" width"400">
<tr>
	<td colspan="5" align="center">List of Entries</td>

</tr>

  <tr>
    <td>Sn. </td>
    <td>Name</td>
    <td>Stream</td>
	<td>Section</td>
    <td>Action</td>

  </tr>
	<?php $link = mysql_connect ( "localhost", "root", "root" );
			  $db = mysql_select_db ( "db_table", $link );
			  $querry = "SELECT * FROM tbl_test";
			  $result = mysql_query ( $querry );
			  $i = 1;
			  while ( $row = mysql_fetch_array ( $result ) ) {
	?>

  <tr>
    <td><?php echo $i; ?></td>
    <td><?php echo output ( $row['profile_name'] ); ?></td>
    <td><?php echo output ( $row['profile_class'] ); ?></td>
	<td><?php echo output ( $row['profile_sec'] ); ?></td>

	<td>
	[<a href ="viewform.php?pid=<?php echo output ( $row['profile_id'] ); ?>">View</a>]
	[<a href ="editform.php?pid=<?php echo output ( $row['profile_id'] ); ?>">Edit</a>]
	[<a href ="deleteform.php?pid=<?php echo output ( $row['profile_id'] ); ?>">Delete</a>]
	</td>
  </tr>

	<?php
		$i++;
		}
	?>

  <tr>
	<td colspan="5" align="center"><input type="submit" name="btnsubmit"
	 value="add more profile" onClick="javascript:  document.location='form.php';"></td>
	</tr>
  </table>

</body>
</html>

Explanation

If you are not familiar with retrieving data from database, the premature version of this script is available in PHP View post. It is recommended you to go through PHP View post first.

htmlentities output function

function output ( $data ) {
	return stripslashes(htmlentities($data, ENT_QUOTES) );
}

Output values

    <td><?php echo output ( $row['profile_name'] ); ?></td>
    <td><?php echo output ( $row['profile_class'] ); ?></td>
	<td><?php echo output ( $row['profile_sec'] ); ?></td>

We use htmlentities() function to output the database data for security reasons. htmlentities() converts all the special characters into HTML entity equivalents. Thus, the browser interprets the converted HTML equivalent in a special way so that it doesn’t change the script of our code and original values are preserved. For more, read Form Security.


viewform.php

<html>

<?php

function output ( $data ) {
	return stripslashes(htmlentities($data, ENT_QUOTES) );
}

?>

<head>
	<link rel="stylesheet" type="text/css" href="style.css" />
	<title>View Entry</title>
</head>

<body>

<?php
	$link = mysql_connect ( "localhost", "root", "root" );
	$db = mysql_select_db ( "db_table", $link );

	$pID = $_GET['pid'];
	$querry ="SELECT * FROM tbl_test WHERE profile_id = '$pID'";

	$result = mysql_query($querry);
	$row = mysql_fetch_array($result);

?>

<table border="1" width-"400">
<tr>
<td colspan="2"> Entry list number: <?php echo $pID; ?></td>
</tr>

<tr>
<td>Name: </td>
<td><?php echo output (  $row['profile_name'] ); ?> </td>
</tr>

<tr>
<td>Class: </td>
<td> <?php echo output ( $row['profile_class'] ); ?> </td>
</tr>

<tr>
<td>Sec: </td>
<td> <?php echo output ( $row['profile_sec']  );?> </td>
</tr>

<tr>
<td>Gender: </td>
<td> <?php if (  output ( $row['profile_gender'] == 'M') ) {
		echo "Male";
	} else {
		echo "Female";
	} ?>

</td>
</tr>

<tr>
<td>About: </td>
<td> <?php echo output ( $row['profile_desc'] ); ?> </td>
</tr>

<tr>
<td colspan="2" align="center"> <input type="button" name="view_list" value="view list" onClick="javascript:  document.location='viewform_list.php';"> </td>
</tr>
</table>
</body>

Explanation

If you are not familiar with retrieving data from database, the premature version of this script is available in PHP View post. It is recommended you to go through PHP View post first.

Output values

<td>Name: </td>
<td><?php echo output (  $row['profile_name'] ); ?> </td>
</tr>

We first pass the data to the output() function before displaying the data. For more, read Form Security.

Subscribe to fortystones.
Follow @fortystones on Twitter.
Get updated from our Facebook Fanpage.

Share

6 Comments + Add Comment

Leave a comment

*