Yogesh Chauhan's Blog

Clean Form Input With These PHP Functions Before Inserting into Database

in PHP on December 4, 2019

Many times we see user inserts lots of spaces and dots and what not. And sometimes they are meaningful, I agree, but many times it's just by mistake. If the user is a hacker then slashes inserted by him/her is not a mistake. It's a deliberate attempt to breach into your website. So, in all those cases we, as a website owner or developers, need to check for those special characters and remove them before even applying the INSERT statement.

In this article I am going to show you how to clean user input entries before adding it to database.

Let's take a look at the functions one by one and then discuss the code as a part of a form.

trim()

This function removes white spaces and other characters (that you tell it to remove) from both sides (left and right) of a string.

Syntax:


trim(string $str,characters you want to remove-OPTIONAL)

If you don't specify the second optional part then it will remove the white spaces only.

To learn more about it, use the official PHP manual HERE.

stripslashes()

This function removes backslashes.

Syntax:


stripslashes(string $str)

It is very simple and very helpful in cleaning up the data.

To learn more about it, use the official PHP manual HERE.

htmlspecialchars()

I've wrote down a very big advantage of using this while getting user inputs in the following blog post.

An Example of Cross-site Scripting (XSS) Attack in PHP and How to Avoid It?

Basically, it converts HTML special characters to HTML entities.

For example, & (ampersand) becomes & and " (double quote) becomes "

Syntax:


htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = TRUE ]]] ) : string

That's a bit scary syntax from the official manual. Let's simplify it:


htmlspecialchars(string,flags-OPTIONAL,character-set-OPTIONAL,double_encode-OPTIONAL)

A bit better.

In the function above, all we need is string inside and it will do the job. If you want to learn about this function in death, use this official manual, HERE.

Now lets write down a PHP function in which we will apply all those functions to the user inputs we get from HTML form.


function clean($userInput) {
  $userInput= trim($userInput);
  $userInput= stripslashes($userInput);
  $userInput= htmlspecialchars($userInput);
  return $userInput;
}

You can go ahead and remove whichever you want but I insist you to keep all those functions in order to clean the data nicely.

In the function above, we are passing a parameter called $userInput which we will get from user. Let's see how we can send the form inputs into the function.


if(isset($_POST['submit'])){
  $first_name = test_input($_POST["first_name"]);
  $last_name = test_input($_POST["last_name "]);
}

Lets understand it one by one. The "isset" determines if any variable has been set or declared. If so, it will return TRUE if the variable has been set or declared. We can use isset with _POST to determine if a variable was posted or not. Many times, we use this with a submit button in a form. So, to wrap this up "isset($_POST['submit'])" part will check if the form was submitted using the submit button or not. And we are using if to check if that condition is TRUE. So, whenever the user submits the form it will return TRUE and send the data inside it. 

Now, let's checkout the form as well to understand it better.


<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  First Name: <input type="text" name="first_name" required>
  <br>
  Last Name: <input type="text" name="last_name" required>
  <br>
  <input type="submit" name="submit" value="Submit">  
</form>

To understand the action part in form please read this article.

An Example of Cross-site Scripting (XSS) Attack in PHP and How to Avoid It?

Now, user will enter the info and click on submit button. Then the submitted data will go inside the isset condition and from there, it will get cleaned up and assigned to the variable itself. 

NOTE: THIS CODE IS NOT COMPLETE CODE. DIFFERENT PARTS ARE EXPLAINED IN ORDER TO CLEAN UP THE USER INPUTS.


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Learn to Implement Estimated Reading Time using PHP Part 1: The BasicsPHPDebugging in WordPress Part 2: WP_DEBUG_LOG and WP_DEBUG_DISPLAYWordPressIntroduction to components and templates Part 4: Pipes and DirectivesAngularWhat does useEffect do in React?ReactWhat is PostgreSQL? How similar or different it is from SQL?PostgresThe substr() method in JavaScript and how it’s different from substring()JavaScript