PHP Free Tutorial

Input Validation in PHP

In PHP, Programming by Baqir AliLeave a Comment

What is input validation?

Most of the time input validations are done using javascript but PHP also provides us the functionality to validate the user’s input. In order to validate the user input, we use a regular expression. There are many ways to use a regular expression but we can use it with setters and getters during class member value assignments.

There are some programming terms discussed in this code

  • HTML Form
  • Regular Expression
  • Exception Handling
  • PHP Sessions
  • Superglobal Variables
  • PHP Classes

First, we create an HTML form to take three inputs from the user. This form works as a View for the program.

Input validation in PHP

index.php

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css"></style>
</head>
<body>
	<?php
		session_start();
		// require_once("user.php");
		if(isset($_SESSION['errors']))
		{
			$errors = $_SESSION['errors'];
		}
	?>
	<form action="process.php" method="POST">
		User Name: <br>
			<input type="text" name="fuserName" value=""> 
			<span id="NameError"><?php if(isset($errors['errorName'])){echo($errors['errorName']);} ?></span> 
			<br>
		User Email: <br>
			<input type="text" name="fuserEmail"  value=""> 
			<span id="EmailError"><?php if(isset($errors['errorEmail'])){echo($errors['errorEmail']);} ?></span> 
			<br>
		User Password: <br>
			<input type="password" name="fuserPassword"  value=""> 
			<span id="PasswordError"><?php if(isset($errors['errorPassword'])){echo($errors['errorPassword']);} ?></span> 
			<br>
			<input type="submit" value="Save Data">
	</form>
</body>
</html>

In the above line

<form action=”process.php” method=”POST”>

IN the POST(Superglobal variable) method we have used to pass form values to process.php after clicking the submit button therefore we need the process.php file as well as user.php with user’s attributes.

process.php

<?php
	require_once("user.php");
	session_start();

	$objUser = new User();
	$errors = array();

	// Call for magical method of __set()
	try
	{
		$objUser->__set("Name", $_POST['fuserName']);	
	}
	catch(Exception $ex)
	{
		$errors['errorName'] = $ex->getMessage();
	}
	// Call for magical method of __set()
	try
	{
		$objUser->__set("Email", $_POST['fuserEmail']);
	}
	catch(Exception $ex)
	{
		$errors['errorEmail'] = $ex->getMessage();
	}
	// Call for magical method of __set()
	try
	{
		$objUser->__set("Password", $_POST['fuserPassword']);
	}
	catch(Exception $ex)
	{
		$errors['errorPassword'] = $ex->getMessage();
	}
	$_SESSION['objUser'] = serialize($objUser);
	//check if you have faced any error
	if(count($errors) == 0)
	{
			//if no errors detected or $errors is empty, then do the following
			echo "<h2>Congratulations You Are Now Registered</h2>";
	}
	else
	{
			//if $errors array is not empty create a session of erros and redirect back to registration form
		$_SESSION['errors'] = $errors;
		header("Location:index.php");
	}
?>

__set() and __get() magical methods

We use the __set() function when writing data to inaccessible (protected or private) or non-existing properties as well as the __get() function to read data from inaccessible (protected or private) or non-existing properties.

user.php

<?php

	class User 
	{
		private $userId;
		private $userName;
		private $userEmail;
		private $userPassword;

		public function __construct()
		{
			$this->userName = NULL;
			$this->userEmail = NULL;
			$this->userPassword = NULL;
		}
		public function __set($name, $value)
		{
			$method = "set_" . $name;
			if(!method_exists($this, $method))
			{
				throw new Exception("Property $name does not exist");	
			}
			$this->$method($value);
		}
		public function __get($name)
		{
			$method = "get_" . $name;
			if(!method_exists($this, $method))
			{
				throw new Exception("Property $name does not exist");	
			}
			return $this->$method();
		}

		//Setters and Getters for Name
		private function set_Name($name)
		{
			$regName = "/^[a-z]+$/i";
			
			if(!preg_match($regName, $name))
			{
				throw new Exception("Invalid / Missing Name");	
			}
			$this->userName = ucfirst(strtolower($name));
		}
		private function get_Name()
		{
			return $this->userName;	
		}
		//Setters and getter or Email
		private function set_Email($email)
		{
			$reg = "/^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zAZ]\.)+[a-zA-Z]{2,4})$/";
			if(!preg_match($reg, $email))
			{
				throw new Exception("The Email is Invalid");	
			}
			$this->userEmail = $email;
		}
		
		private function get_Email()
		{
			return $this->userEmail;
		}
		//Settters and getters for password
		private function set_Password($password)
		{
			$reg = "/^[a-z][a-z0-9]{5,15}$/i";
			if(!preg_match($reg, $password))
			{
				throw new Exception("Invalid / Missing User Password");	
			}
			$this->userPassword = md5($password);
			//md5 Encryption
		}
		private function get_Password()
		{
			return $this->userPassword;
		}
	}
?>

All the setters and getters are set private so we create another public function in order to check if the functions exist or not, if exist then access them.

Support us by sharing this post

About the Author

Baqir Ali

Facebook Twitter

Hi, I am Baqir Ali ---- Blogger, Programmer, and a Teacher. I am currently working as a Programmer for Softnat Technologies. I have tons of ideas and data to share with you all via blogging.

Leave a Comment