Skip to content

Instantly share code, notes, and snippets.

@abedsujan
Created February 12, 2012 20:39
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save abedsujan/1810764 to your computer and use it in GitHub Desktop.
Save abedsujan/1810764 to your computer and use it in GitHub Desktop.
PHP::Basic form validation using PHP (username, number, string, email)
<?php
/**
* This function can be used to check the sanity of variables
*
* @access private
*
* @param string $type The type of variable can be bool, float, numeric, string, array, or object
* @param string $string The variable name you would like to check
* @param string $length The maximum length of the variable
*
* return bool
*/
function sanityCheck($string, $type, $length){
// assign the type
$type = 'is_'.$type;
if(!$type($string))
{
return FALSE;
}
// now we see if there is anything in the string
elseif(empty($string))
{
return FALSE;
}
// then we check how long the string is
elseif(strlen($string) > $length)
{
return FALSE;
}
else
{
// if all is well, we return TRUE
return TRUE;
}
}
/**
* This function if the $_POST vars are set
*
* @access private
*
* return bool
*/
function checkSet(){
return isset($_POST['userName'], $_POST['userAddress'], $_POST['userCity'], $_POST['userZip'], $_POST['userEmail']);
}
/**
* This function checks a number is greater than zero
* and exactly $length digits. returns TRUE on success.
*
* @access private
*
* @param int $num The number to check
* @param int $length The number of digits in the number
*
* return bool
*/
function checkNumber($num, $length){
if($num > 0 && strlen($num) == $length)
{
return TRUE;
}
}
/**
* This function checks if an email address in a valid format
*
* @access private
*
* @param string $email The email address to check
*
* return bool
*/
function checkEmail($email){
return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}
// check all our variables are set
if(checkSet() != FALSE)
{
// check the POST variable userName is sane, and is not empty
if(empty($_POST['userName'])==FALSE && sanityCheck($_POST['userName'], 'string', 25) != FALSE)
{
//If all is well we can assign the value of POST field to a variable
$userName = $_POST['userName'];
}
else
{
// if all is not well, we echo an error and exit the script
echo 'Username is not set';
exit();
}
// here we test for the sanity of userAddress, we dont need to stop the
// the script if it is empty as it is not a required field.
if(sanityCheck($_POST['userAddress'], 'string', 100) != FALSE)
{
// if all is well we assign the userAddress to a variable
$userAddress = $_POST['userAddress'];
}
else
{
// if all is not well, we simply give the userAddress a blank value
$userAddress = '';
}
// here we test for the sanity of userCity, we dont need to stop the
// the script if it is empty as it is not a required field.
if(sanityCheck($_POST['userCity'], 'string', 25) != FALSE)
{
// again we assign the POSTed value to a variable
$userCity = $_POST['userCity'];
}
else
{
// or give the variable a blank value
$userCity = '';
}
// check the sanity of the number and that it is greater than zero and 5 digits long
if(sanityCheck($_POST['userZip'], 'numeric', 5) != FALSE && checkNumber($_POST['userZip'], 5) == TRUE)
{
// if the number is valid, we assign it to a variable
$userZip = $_POST['userZip'];
}
else
{
// or give the variable a blank value
$userZip='';
}
// check the sanity of the userEmail sent from the form
if(sanityCheck($_POST['userEmail'], 'string', 5) != FALSE && checkEmail($_POST['userEmail']) != FALSE)
{
// if the checks are ok for the email we assign the email address to a variable
$userEmail = $_POST['userEmail'];
}
else
{
// if all is not well we echo an error message
echo 'Invalid Email Address Supplied';
// and exit the script
exit();
}
// Connect to the MySQL
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link)
{
die('Not connected : ' . mysql_error());
}
// select test as the current db
$db_selected = mysql_select_db('test', $link);
if (!$db_selected)
{
die ("Database not selected : " . mysql_error());
}
// Build our query here and check each variable with mysql_real_escape_string()
$query = sprintf("INSERT INTO people (userName, userAddress, userCity, userZip, userEmail)
VALUES( '%s', '%s','%s','%s','%s')",
mysql_real_escape_string($userName),
mysql_real_escape_string($userAddress),
mysql_real_escape_string($userCity),
mysql_real_escape_string($userZip),
mysql_real_escape_string($userEmail));
// run the query
if(!mysql_query($query))
{
echo 'Query failed '.mysql_error();
exit();
}
else
{
// if all is well we mail off a little thank you email. We know it is
// safe to do so because we have validated the email address.
$subject = 'Submission';
$msg= 'Thank you for submitting your information';
if(!mail($userEmail,$subject,$msg, "From: $userEmail\nReply-To: $userEmail\nX-Mailer: PHP/" . phpversion()))
{
echo 'Unable to send confirmation mail';
}
else
{
echo 'Thank you for your submission, a confirmation email has bee sent to '.$userEmail;
}
}
}
else
{
// this will be the default message if the form accessed without POSTing
echo '<p>Please fill in the form above</p>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Validating User Input.</title>
<style type="text/css">
<!--
label,input {
display: block;
width: 150px;
float: left;
margin-bottom: 10px;
}
label {
text-align: right;
width: 75px;
padding-right: 20px;
}
br {
clear: left;
}
-->
</style>
</head>
<body>
<h3>* denotes required field!</h3>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<p>
<label for="name">Name</label>
<input id="name" type="text" name="userName" maxlength="25" />*<br />
<label for="address">Address</label>
<input id="address" type="text" name="userAddress" maxlength="100" /><br />
<label for="city">City</label>
<input id="city" type="text" name="userCity" maxlength="25" /><br />
<label for="zip">Zip</label>
<input id="zip" type="text" name="userZip" maxlength="5" /><br />
<label for="email">Email</label>
<input id="email" type="text" name="userEmail" maxlength="50" />*<br />
<label for="submit">Submit</label>
<input id="submit" type="submit" value="Mail It!" /><br />
</p>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment