Tutorials

Center Image of Mission image


 

PHP Security - Protect Your Data

Here are ways to protect your data before saving to a database and displaying it on your screen.  When I created my contact form plugin for WordPress.org.  I've learned that you have to escape and sanitize your form data before inserting it into a database.

You also need to do it when you are displaying your database data to a screen.  This protects your clients from code insertion.  Hackers will find a way to insert code into your form that could potentially damage your database.

This means that you have to start with the client-side.  It is the first level of defense.  You start with JavaScript form validation before it goes to the server.

Once JavaScript validates your data and it sends it to the server, PHP will escape and sanitize the data before being inserted into a database.  This is the second level of defense.

Now when it reaches the database mySQL will provide the third level of defense by using the "prepare statement".  See below for "prepare" statement.

Here are some of my security command statements that you need to secure your data before storing into your database.

Use mySQL escape string command to escape your form database after JavaScript validates data.

    mysql_real_escape_string($con, arg1);

We assign $con with the connection string.

    arg1 = $_POST['name'];

This is how you get the name that was entered in the form. Since the form method attribute was set to "post".

You want to check if the form data is empty by using the empty command.  You must be wondering, if we're using JavaScript validation then why should we worry about it if we are going to validate on the server-side, PHP does a great job doing this.

We need to do this just in case someone turns off the JavaScript on the their computer. I know, I know this is 2019 - No one turns off JavaScript.  For the most part, people just don't care and will turn off JavaScript.

You have to use JavaScript for form validation making it the first level of defense.  Now, that you know that the form validation is needed, let's check to see if any of the input elements are empty by using the "empty()" function.

    empty($_POST['name']);

Another thing you want to do is to trim off empty spaces by using the "trim()" command which trims the spaces from both sides of your data.  You have the "ltrim()" that takes out spaces from the left side and the "rtrim()" that cuts out spaces from the right side.

    trim($_POST['name']);

Note: JavaScript also uses their own version of the trim() command.

I mentioned earlier that we can use regular expressions to help with phone validation.

This is one of the best ways to validate phone data.  It helps you cut on the number of lines of code to use.  We're going to use several other functions to help with validation a little later.

    pre_match("/^[a-zA-Z]*$/", $name);

The first part of the function is the actual pattern that the function compares with the value of the form.

    /^[a-zA-Z]*$/ = pattern

    $name = "sally";

Here is how you do it in JavaScript.

    $name.match("/^[a-zA-Z]*$/");

How do you want to validate emails used to PHP "filter_var()" function?

    Filter_var($email, FILTER_VALIDATE_EMAIL);

To validate password use the "password_hash()" function.

    password_hash($pwd, PASSWORD_DEFAULT);

Now to read a hashed and verify password use the "password_verify()" function.

    password_verify($pwd, < from dbase >);

The "$pwd" comes from the form password via "$_POST[]".  This function compares the form password with the password that was hashed from the database.

If it is true you will get a 1 and of course a 0 if it is false.

You can also use the sha function 2 test your password, this is a command that runs under mySQL I hardly ever use it but I know it works.

The SHA-1 function calculates the hash of a string.

    sha1($pwd) - The value is returned as a string of 40 hexadecimal digits

Example:

$str = "Security";
echo sha1($str);

Also, try to escape all data.  There are several different ways to escape.  Even if you're using Wordpress Escape all your data.


Wp_kses

WordPress is written with PHP so whatever you use when you just using regular PHP will work in WordPress.

WordPress also has several sanitizing function and the one that I use is called "wp_kses()".  This function filters content and strips out all "html" tags.  You can allow some "html" element if you choose to do so by using an array as part of this function parameter.

This function makes sure that only the allowed HTML element names, attribute names, attribute values, and HTML entities will occur in the given text string.

Example:

    $scfp_secure_section = wp_kses($scfp_secure_section, array(
     'section' => array('class' => array()),
     'div' => array('class' => array()),
     'img' => array('id' => array(), 'src' => array())
     ));



WordPress Nonce

You need to use a "nonce" function that WordPress provides. You can add this function to your forms for extra security.   The two functions that I use are called "wp_create_nonce()" and "wp_verify_nonce()".

The "wp_create_nonce()" function creates a cryptographic token and ties it to a specific action, user, and user session.  You add the below to your contact form input element as hidden.

Example:

    wp_create_nonce('scfp_input_nonce');

The "wp_verify_nonce()" function verifies that a correct security nonce was used with a time limit.

Example:

    if( wp_verify_nonce($_POST['scfp_input_hidden'],'scfp_input_nonce') ) {}


Salt

You need to protect your WordPress website login from hackers.  All hackers need to do is enter "/wp-admin" and your login screen is expose.  You have to create a "username" and "password" that is hard to crack.  You have to make sure your password is secure, making it hard to crack.

WordPress uses a special key to protect your password. It is called "SALT".  This key sits in the wp-config file and you can change it by using .   Your "SALT" keys will keep your password safe even if a hacker gains access to your data.

The "SALT" keys are cryptographic elements used to hash your data and keep them secure.  The way it works is the "SALT" keys encrypt your WordPress password.  The password will not be shown as plaintext even if they somehow gain access to your database.

The "SALT" will sign your website’s cookies.  This is done to stop malicious hackers from being able to gain access, even if they take over your cookies.

This happens in the background.  You will not share your WordPress "SALT" keys with a third party.  It doesn't mean that a hacker couldn't take control.

This is why it is recommended to change your WordPress "SALT" keys.  You should change it from time to time to avoid risk.  You will need to edit the wp-config file to change.

Let’s take a look at how you can do this.

Go to this link "Salt Key" and you will be displayed with something like this.

Example:

define('AUTH_KEY', 'A?fjWDy_S]-+d[-+#./'); define('NONCE_KEY', 'qVK7yow$UQ`Jc =xd/&2~S|XQ+6K ^Sl_#=mvvz3i-0/n@K]iU_u3kON(7>@dd;'); define('AUTH_SALT', '[/VTq>fW{=17@z6Z?pPZ[&/;w!f|Y%Ci1~Rv~dJVk8>R2[F&gP!wwV>EbI-(|U:8'); define('SECURE_AUTH_SALT', ']}q&WXam*ez|tZC4l&?sP=c1c 3b_OrIBtWzpT2&F q`mW7BQq/B~h4s9i/$]j-L'); define('LOGGED_IN_SALT', 'f+-~6M~IA5-re-+Gz^:A+OuShEJhQS.rujU[zM~N-zkP'); define('NONCE_SALT', '+nx7D`br:rw}Fc|iF}3HM):s>(Ml9Yc:=fr>WtMyVgeq-Ca:R6%w>mF?^R^qTV|?');

Then edit the "wp-config" file and replace what's in the file with the "WordPress" API provides.

Check out "WordPress and search for "secret-key service" for more information".  If you are nervous to do it yourself.  Check out article - Knox secret key.


Form Validation

I mentioned earlier that you have to provide form validation on the client-side as well as the server-side.  If you are just developing using PHP and not in a CMS environment, use the "real_escape_string()", then escape everything by using several different "esc_" functions.

You can use "esc_html()", "esc_url()" and "esc_attr()".  You can strip all tags by using "strip_tags()".  Under the WordPress environment also use the sanitizes functions.  The sanitization will only remove code, text or characters from the form data from data that are not allowed.

Remember, "Sanitizing" and "Escaping" are two different things.  Sanitizing will only remove code, text or characters from the data.

To "Escape" is to take the data you may already have and help secure it before rendering it for the end-user.

This is done to prevent XSS attack and also to make sure that the data is displayed the way the user expects it to be.

Escaping converts the special HTML characters to HTML entities so that they are displayed, instead of being executed.

esc_html() - This functions escapes HTML specific characters.

esc_textarea() - This function esc_textarea() instead of esc_html() while displays text in textarea.  Because esc_textarea() can double encode entities.

esc_attr() - This function encodes the <,>, &, " and ' characters.  This function is used to escape the value of HTML tags attributes.

esc_url() - Hacker can inject JavaScript code into your URLs and it can cause an XSS attack.  To prevent this from happening you need to use this function.  This will help you display a URL or a complete "a" tag.

You can validate by checking your user input to see if the user has entered a valid value.

You can validate your email by using the "is_email()" function.  This function is provided by WordPress to check if the email address is valid.

To check if the data being pass is either a string or not use the "is_serialized()" function.  And if a value is not a string WordPress serializes it before storing it in a database.


Sanitation

When you "Sanitize" you are removing text, characters or code from the input value that is not allowed protecting your data from html injection.

sanitize_email() = This function strips out all characters that are not allowed in an email address.

sanitize_text_field() = This function removes invalid UTF-8 characters, converts HTML specific characters to entities, strips all tags, and removes line breaks, tabs and extra whitespace, strip octets.


Prepare Statement

Whereas validation requires user input to conform to a certain rule or rules put forth by the developer, sanitization only cares about removing code, text or characters from data that are not allowed.  Sanitizing and escaping data are two different things.

Use the "Prepare" statement to format a more secure insert statement.

Here are the steps:

  • escape_string all value
  • initiate the database connections
  • prepare the statement
  • bind the statement
  • execute the statement

For a prepared statement, you have to make sure that you assign a MySQL connection to a variable.

Here is how I read a database with a prepared statement.

First, create your variables and assign the database connection and open with the mysql_connect() function.

    $dbServer = "localhost;
    $dbUsername = "";
    $dbPassword = "";
    $dbName = "";

    $connection = mysqli_connect(a,b,c,d);

    $sql = "SELECT * FROM <'tablename'> ORDER BY <'item'> DESC;";

This line initializes the database connection.

    $stmt = mysqli_stmt_init($connection);

The prepared statement is a feature used to execute the same or similar SQL statements repeatedly with high efficiency.

    mysqli_stmt_prepare($stmt, $sql);

The below line executes the connection.

    mysqli_stmt_execute($stmt);

This line gets the results from the database.

    $result = mysqli_stmt_get_results($stmt);

Use the while loop to read through what you fetched.  Use the "mysqli_fetch_assoc()" function.

    While($row = mysqli_fetch_assoc($result)) {

      $row['name'] . " and " .$row['subject'];

    }

Now, the below statements are used to create the "insert" statement with placeholders for the values.  Then the "bind" statement connects the actual value with the placeholders.

Now, to execute the SQL statements directly.  The "Prepare" statements have three main advantages.

  • 1. The prepared statement reduces parsing time as the preparation on the query is done only once even if the statement is executed multiple times.
  • 2. The bound parameters minimizes the bandwidth to the server as you need to send only the parameters and not the whole query.
  • 3. The purpose statements are very useful against SQL injections because parameter values don't have to correctly be escaped.

if the original statement template is not derived from external input value it will not be injected.

Here is how it is done. Create the SQL "Insert" statement.

  • $sql = "INSERT into <'tables_name'> (name, subject) value (?,?);";
  • mysql_stmt_prepare(stmt,$sql);
  • mysqli_stmt_bind_param($stmt, "ss", $name, $subject);
  • mysqli_stmt_execute($stmt);

Center Image of Mission image
Image of a dark blue phone that you can click to make a call.  Will only work on a mobil phone.
Enter Your Information

An image of reCapture icon

Thanks for your interest in our services. Please, leave detail Information regarding your creative needs. Someone from our professional team will get back to you at their earliest convenience.

Please, make sure you leave your name, address and your phone number or you can contact us direct at (201) 486-9155.

Note: Your email address will not be distributed in anyway.