how to secure form submission in php

How to secure form submission in php?

In this article we will learn how to secure form submission in PHP. PHP is a server side scripting language used to develop dynamic websites. Sometimes, we need to add forms in our website like contact form, query form, booking form, registration form etc.

But to secure our website we should have our form secure and there is some methods by using these we can secure our form submission in php.

  • Validate the form method like GET, POST etc.
  • Validate the input of the forms like alphabets only, numbers only, email only, some special characters only.
  • Sanitize the input of the forms like remove unwanted html characters, special characters or coding characters from the input of the form.
  • Process the form for only specific variables only.
  • Using the secure SQL Queries like Object-Oriented or PDO.

Here is a sample code where we are submitting the form using the PHP and MYSQL.

This is our dbCon.php file for Database Connection.

<?php
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'phpform';

/*Database connection*/

try{

$conn = new PDO("mysql:host=$server;dbname=$database",$username,$password);

/*Set PDO Error to Exception*/

$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

}catch(PDOException $e){
die('DB Error : '. $e->getMessage());
}

/*Database connection*/


?>
  • In the above code we have used the PDO Class for database connection.
  • We set the PDO Error to Exception for reading errors as exception in our catch block.

This is our form.php file.

<?php

/*Basic Settings*/
error_reporting(E_ALL & ~E_NOTICE); // Hide Notices on Browser
date_default_timezone_set('UTC'); //UTC Timezone
/*Basic Settings*/

/*include db connection file*/

require_once('dbCon.php');

/*include db connection file*/

/*countries variable*/
$countries = [
	'India' => 'India',
	'United States' => 'United States',
	'United Kingdom'	=> 'United Kingdom'
];
/*countries variable*/


/*********functions**********/

/*
* Accepts only alphabets
*/
function alphaOnly($string){

	if (preg_match("/^[A-Za-z-_., ]+$/", $string))
	{
		return true;
	}

	return false;

}

/*
*Accepts only phone number
*/

function phoneOnly($string){

	if (preg_match("/^[0-9+-]+$/", $string))
	{
		return true;
	}

	return false;

}

/*
* Accepts only email
*/
function emailOnly($email){
    // Validate email
	if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
		return true;
	} else {
		return false;
	}
}

/*
* Sanitize the input string
* Accepts only some character defined in function
*/
function sanitizeString($str){

	$str = filter_var($str, FILTER_SANITIZE_STRING);

	$str = strip_tags($str);

	$str = htmlspecialchars($str);

	$res = str_replace( array( '\'', '"',
		',' , ';', '<', '>', '*', ':', '@', '$', '(', '`', '~', ')', '[', ']', '.' ), ' ', $str);

	return $str;
}

/*
* Sanitize the input email
*/
function sanitizeEmail($email){
	$email = filter_var($email, FILTER_SANITIZE_EMAIL);

	$email = str_replace( array( '\'', '"' , ';', '<', '>', '*', '`', '~', '[', ']' ), ' ', $email);

	return $email;
}


/*********functions**********/

/*************processing form*************/

$errors = [];
$success = false;

if (isset($_POST) && isset($_POST['submit']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
	

	extract($_POST);

	/*full name*/
	if (alphaOnly($full_name)) {
		$full_name = sanitizeString($full_name);
	}else{
		$errors['full_name'] = 'Enter valid name';
	}
	/*full name*/

	/*mobile number*/
	if (phoneOnly($mobile_number)) {
		$mobile_number = sanitizeString($mobile_number);
	}else{
		$errors['mobile_number'] = 'Enter valid mobile number';
	}
	/*mobile number*/

	/*email id*/
	if (!empty($email_id)) {
		if (emailOnly($email_id)) {
			$email_id = sanitizeEmail($email_id);
		}else{
			$errors['email_id'] = 'Enter valid email';
		}
	}
	/*email id*/

	/*country*/
	if (alphaOnly($country)) {
		$country = sanitizeString($country);
	}else{
		$errors['country'] = 'Select valid country';
	}
	/*country*/


	if (count($errors) == 0) {

		try {
			
			$sql = "INSERT INTO `form_data`(full_name, mobile_number, email_id, country, created_at) VALUES(:full_name, :mobile_number, :email_id, :country, :created_at)";

			$stmt = $conn->prepare($sql);

			$stmt->bindParam(':full_name', $f_name);
			$stmt->bindParam(':mobile_number', $m_number);
			$stmt->bindParam(':email_id', $e_id);
			$stmt->bindParam(':country', $country_name);
			$stmt->bindParam(':created_at', $created_at);

			$f_name = $full_name;
			$m_number = $mobile_number;
			$e_id = $email_id;
			$country_name = $country;
			$created_at = date('Y-m-d H:i:s');

			if($stmt->execute()){
				$success = true;
			}

		} catch (PDOException $e) {
			echo "<br>";
			echo ('SQL Error : '.$sql);
			echo "<br>";
			die('Error : '.$e->getMessage());
		}

	}

}

/**************processing form**********************/


?>

<!DOCTYPE html>
<html>
<head>
	<title>Submitting Secure PHP Form</title>

	<style type="text/css">

	/*styling form*/
	.contain{
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
	}

	.alert{
		padding: 1rem;
		margin-top:1rem;
		margin-bottom: 1rem;
	}

	.alert-success{
		color: #FFF;
		background: #1bb343;
	}

	.alert-error{
		color: #FFF;
		background: #ce2f2f;
	}

	input, select{
		height: 30px;
		width: 100%;
		padding: 0.3rem;
	}
	/*styling form*/

</style>
</head>
<body>

	<div class="contain">

		<?php if($success): ?>
			<div class="alert alert-success">
				<p class="m-0">Form Submitted Successfully!</p>
			</div>
		<?php endif; ?>

		<?php if(count($errors) > 0): ?>
			<div class="alert alert-error">
				<?php foreach($errors as $error): ?>
					<p class="m-0"><?php echo $error ;?></p>
				<?php endforeach; ?>
			</div>
		<?php endif; ?>

		<h2>Submitting PHP Form</h2>
		
		<form method="POST" name="phpForm">

			<p>
				<input type="text" name="full_name" placeholder="Enter Full Name" value="<?php echo ($full_name && $success == false)?$full_name:'';?>" required/>
			</p>
			
			
			<p>
				<input type="text" name="mobile_number" placeholder="Enter Mobile Number" value="<?php echo ($mobile_number && $success == false)?$mobile_number:''; ?>" required/>
			</p>

			<p>
				<input type="email" name="email_id" placeholder="Enter Email ID" value="<?php echo ($email_id && $success == false)?$email_id:''; ?>"/>
			</p>

			<p>
				<select name="country" required="">
					<option disabled="" selected="">--Select Country--</option>
					<?php
					foreach ($countries as $key => $value) {
						?>
						<option value="<?php echo $value; ?>" <?php echo ($country == $value && $success == false)?'selected=""':'';?>>
							<?php echo $value;?>
						</option>
						<?php
					}
					?>
				</select>
			</p>

			<p>
				<input type="submit" name="submit" />
			</p>

		</form>

	</div>

	<script>
		if ( window.history.replaceState ) {
			window.history.replaceState( null, null, window.location.href );
		}
	</script>

</body>
</html>
  • In the above code we set the error_reporting to E_ALL & ~E_NOTICE to hide notices on browser.
  • Used the require_once to include the database connection file.
  • Created the functions alphaOnly – for alphabets only, phoneOnly – for numberic only, emailOnly – for email only, sanitizeString – to remove special characters from string, sanitizeEmail – to remove special characters from email.
  • Used the $_SERVER to check request method and $_POST to check the post variables.
  • In PDO we used the prepare, bind and execute methods.
  • To get the errors we used PDOException in catch block.
  • In Javascript we used the window.history,replaceState to prevent the forms from resubmission.

For more PHP Tutorials Visit PHP Page.

If you like this, share this.

Follow us on FacebookTwitterTumblrLinkedIn.

ReadyMadeCode
Author: ReadyMadeCode

ReadyMadeCode.com is a website where you can find Free Online Tutorials - Website Development Tutorials, App Development Tutorials, Coding Tutorials,Website Designing and Development From popular programming languages or scripts or framework like php, laravel, html, css, javascript, nodejs, java, angularjs etc. Download Emails | E-Books.

View All Posts From ReadyMadeCode
Author Website : https://www.readymadecode.com
Scroll to top

Subscribe For Latest Updates

Enter your email address to subscribe and receive notifications of posts & updates by email.


Want a Website / App / Digital Marketing Solution

Website & App Development Packages

%d bloggers like this:
We have updated our memberships. Please check here
Close X