Security Best Practices For PHP Development

Security Best Practices For PHP Development

In this free article, I'll share the most effective PHP website security best practices to protect your website and users from threats. It's essential for new developers, students, security professionals, networking experts, and website owners to follow these practices to keep their web application safe.

As a coding expert, I'll share the most effective measures to protect your PHP website from threats. It's crucial to follow recent security best practices to keep your website and users safe. I'll discuss secure coding practices, robust authentication, and authorization mechanisms, and regular security audits and penetration testing.

Introduction

OWASP states: “The total number of websites today has reached 1.8 billion. And nearly 80% of websites are written in PHP” Being as popular as PHP is, it can also be insecure because nothing is 100% safe, especially online. There is no programming language without security vulnerabilities. The chance of getting hacked online has less to do with a programming language and more with how it is implemented. As a developer, it is your responsibility to ensure that your PHP website meets the best practices that the experts in the industry recommend. This blog is for everybody interested in PHP security, especially web developers and website owners who value security as their top priority. So keep reading to learn more about PHP web development best practices.?




Is PHP Secure?

Tim Cook once said: "If you put a key under the mat for the cops, a burglar can find it, too. Criminals are using every technology tool to hack into people's accounts. If they know there's a key hidden somewhere, they won't stop until they find it". ?So, the problem is not the PHP language but how you use it. Using an old version of PHP and expecting it to be secure is not practical.


How to Secure PHP Applications?

I will cover some of the top security methods to secure PHP websites. Although elementary, these solutions can protect your websites from most cyber attacks. This section will share general security best practices you should apply.?


General Security Best Practices in PHP Websites

#1 Update Your PHP Version?

I highly recommend updating your PHP version manually. Because automatic updates sometimes break your existing functions. Since PHP 8.1 is currently the most recent version. Therefore, I strongly recommend you use it. If you are still using PHP 5.6 or 7.0, you will likely experience many deprecations when upgrading PHP systems. Besides version updates, you must also revise your code and modify some functional logic.

Before you update your PHP version:

  1. You should always backup your data?
  2. Test the site on a separate staging server
  3. Maintain Schedules?

For more on updating your PHP site, and you must read: Keeping Up With PHP Updates blog.


#2 Update Your PHP Backed CMS?

According to WordPress, more than 8% of users still use PHP 5.6 or the lower version. And if we combine the usage of PHP 7.0 and 7.1, 7.2, 7.3, and 7.4, it makes an 84% user base. Meaning that the majority is still using something outdated.

ee the following usage stats:

No alt text provided for this image
Fig 1: Wordpress Usage By PHP Version

#3 Use Secure Plugins, Themes, and Extensions?

A 100% secure WordPress plugin or theme is either a dream or a virtual impossibility. Let's accept the fact that developers are humans, and they do occasionally make coding errors. But how can we blame developers when most admins forget to update their PHP versions?

The use of vulnerable software components such as plugins and themes is still one of the top two causes of website infection.


How to Secure PHP Web Applications & Prevent Attacks?

In the former section, we discussed general best practices that can mitigate security risks right from the beginning. For severe coding vulnerabilities and learning about how you can defend your applications from the frequent attacks hackers use, you should rely on this section.?The following 7 best practices can help secure your PHP code. I

I recommend applying all of these best practices while developing your PHP apps to get the best results.


#1 Cross-Site Scripting (XSS) Explained?

Cross-site scripting XSS attacks are the most vulnerable threats to the safety of your PHP websites. This kind of attack occurs when attackers inject client-side code (usually JavaScript) into the output of your PHP script.

According to owasp.org, there are three types of XSS:


#1 Reflected XSS - Malicious script comes from the current HTTP request.

#2 Stored XSS - Attackers send malicious scripts from the website's database.

#3 DOM-Based XSS - The attack payload is executed as a consequence of modifying the DOM environment in the victim's browser that the original client-side script used.?


Note: Stored XSS and Reflected XSS were initially classified as the two main types of XSS. But in 2005, Amit Klein unveiled DOM Based XSS, a third kind of XSS.


Keeping PHP Applications From XSS Attacks?

#Sanitizing HTML?

Sanitizing HTML input and output is a best practice for removing potentially dangerous HTML that might threaten users viewing information on your PHP website. For example, if your website outputs HTML that has been maliciously generated, the user viewing it may be in danger. Hence, sanitizing user input before displaying it on your PHP website is another best practice you should consider.?There are built-in methods in PHP that allow us to sanitize user input and ensure it will not affect our websites. In the following example, you will learn about two best practices for HTML escaping.?


#1 Use the htmlentities() function – If your website needs to escape HTML completely, you can use PHP's built-in htmlentities() function.?Since it only escapes everything instead of validating the HTML, it is quicker than HTML Purifier.?

Example:<?php

$escape_html = '<div onclick="preventXSS();">Escaping HTML </div>';

// Using ENT_QUOTES to escape single and double quotations

// Use UTF-8 character encoding if you have stored the text in this format

$Make_it_safe = htmlentities($evilHtml, ENT_QUOTES, 'UTF-8');

?>


You can read more about UTF-8 in this OWASP documentation on Unicode UTF-8 and others.?


#2 Use HTML purifier – Escaping HTML might not be practical for many PHP web applications. If you want to escape all HTML or just let a tiny portion of HTML in. Use the HTML Purifier Library. Unlike htmlentities() function, it is used for complex requirements.?


Example:<?php

//

require_once('htmlpurifier-4.6.0/HTMLPurifier.auto.php');

$escape_html = '<div onclick="preventXSS();">Escaping HTML</div>';

// Set up the HTML Purifier object with the default configuration.

$htmlpurifier=new HTMLPurifier(HTMLPurifier_Config::createDefault());

$Make_it_safe = $htmlpurifier->purify($escape_html);?


?>


#2 SQL Injection Explained?

SQL is a popular database solution for PHP websites.

Since it has been established that nothing online is completely secure. The same is true for SQL. Since SQL injection is one of the most common threats to the overall security of your PHP website, you should try your best to avoid SQL injection risks.


According to OWASP, you must either stop constructing dynamic queries with string concatenated or stop user-supplied input containing malicious SQL.?


Prevent SQL Injection and Secure PHP Websites???

No matter which database you use for your PHP apps. The best way to secure an SQL injection attack is to separate the data from SQL. It means that the data always remains data. And it must not be interpreted as commands by the SQL parser.

Before you jump to a conclusion, I want you to please have a look at the following best practices:


  • Sanitize user input before it enters into your database (Refer to section 1.1)
  • Never display errors to the user?
  • Create error logs for additional security (Refer to section 5)
  • Study more about PHP data objects?
  • Use test-driven development (TDD) approach


Experts suggest using SQL-prepared statements because these are SQL statements that are delivered to the database server without any parameters.?

If you properly link SQL with your PHP files, your website will be more secure than most, and attackers will find it very difficult to hack you. If it sounds confusing, you should see the following code block to learn how to use a prepared statement.?


#1 PHP Document Object PDO

PDO (PHP data objects) is a widely used database abstraction layer that supports MySQL, among many other databases. In other words, it is a simplified, reliable method of accessing databases that developers consider to be more secure. Also, developers can write portable code much more easily because of its flexibility.


PDO Example:


$Query = $pdo->prepare('SELECT * FROM users WHERE user_name = :user_name'); $Query->execute([ 'user_name'' => $user_name' ]);?


#2 MySqli:

The MySQLi is an extension of the MySQL relational database driver. It is very popular for developing PHP apps.

As compared to MySQL and PDO, it is faster. Otherwise, there is no security difference between PDO and MySQLi. But it is safe to say that using MySQLi is much better than MySQL, and PDO is better than MySQLi.??

?

SQL Query:


// This example uses a driver-specific method used for DB connection. Which is also somewhat secure compared to traditional methods

$Query = $dbConnection->prepare('SELECT * FROM users WHERE user_name'= ?');?

$Query->bind_param('s', $user_name);

?// Note the 's' specifies the variable type => 'string' $Query->execute();?



$result = $Query->get_result();

while ($r = $result->fetch_assoc())?

{

?// ?Now you can do something with the $r}



#3 Don’t Forget to Validate User Input

Think of input validation as the customs clearance at airports. Before entering any country, visitors must abide by a set of rules. Similarly, each PHP web application must set rules that best suit its needs. Because allowing users to submit random inputs is unrealistic and unsafe. Hence, your web application must have a restriction on what it will accept and what it won't.


Input Validation

PHP experts often use regular expressions to validate user input. This validation can be set on phone numbers, email addresses, data of births, and so on.?


Example// Validate DOB

$date="2012-09-12"; if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date)) { return true; } else { return false; }


// Validate Phone Numbers

$number = "Input USA Number";

preg_match("/[0-9]{3}-[0-9]{3}-[0-9]{4}/", $number);?


Note: Besides PHP validation, you should also want to use HTML and JavaScript validation, but we recommend you always use PHP validation based on your PHP form requirements.?


#4 Always Store Hashed Passwords?

PHP’s password_hash() function is an authentic way to store passwords. So, we recommend you use this function. Suppose you have the following input from the user:?


# Step 1 (User Input)$pass = $_POST['userpassword'];?

First, you need to hash this password:


# Step 2 (Password Hashing)$pass_hashed= password_hash($pass, PASSWORD_DEFAULT);

// To see the output

var_dump($pass_hashed);


And when a user asks to log them in, you check the password input with this hash value in the database by doing this:


#Step 3 (Password Check)

//Insert hashed password into your database

if(password_verify($pass, $pass_hashed)) {

// Do something if the user's given password matches the stored password?

}

else {

// Redirect user or display error

}


Note: Make sure your password column is big enough to contain the hash (at least 60 characters or more).

#5?Logging Errors in PHP

A web developer can quickly debug errors using the available error logs. Logs are important for the security of your PHP applications.

Furthermore, error logs?help keep track of any problems that users may be experiencing. I recommend that you should always maintain a separate copy of error logs.


Usually, developers use functions like print_r() and var_dump() for debugging and logging on to the browsers. Which is not a big deal; it must be flexible. But before you go live, you should use PHP’s: error_log() function –?It sends an error message to the defined error handling routines, which can be a log, an email account, or a file.


Syntax:error_log(message, type, destination, headers);


Here is a complete error logs example:


<?php

// Send an error message to the server log, if a database connection error occurs

if (!mysqli_connect("localhost","user","password","db_name")) {

?error_log("Customize your error message!", 0); // Default: Message is sent to PHP's system logger

}

// Why not send an email to the admin?

if (!($something = do_something())) {

?error_log("Customize your error message", 1, "[email protected]"); // Optional: Message will be sent to an email account

// You can customize the log based on your requirements here?

}

?>


Error Logging in PHP.ini File?

You can log error in PHP.ini file. Follow these steps to enable error reporting for your website or application:


  • #1 Search the PHP.ini file on your server???
  • #2 Locate the code line with the error_reporting entry

#3 Make sure the entry doesn't have a (;) in front of it

  • #4 Set the desired level of logging in the error reporting entry,


For example, you can put the following code:


error_reporting = E_ALL & ~E_NOTICE

error_reporting = E_ALL & ~E_NOTICE | E_STRICT

error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ER... _ERROR

error_reporting = E_ALL & ~E_NOTICE



Aside from that, you can also set error logs in individual PHP files:


ini_set('display_errors', 1);

ini_set('display_startup_errors', 1);

error_reporting(E_ALL);


Then, go the php.ini file to parse the log errors by simply enabling single statement:?display_errors = on

You can read more on error_log() here.?


#6 Use a PHP Security Scanner

There are tools you can use to scan PHP, and using them before going live with your PHP website is important. At the same time, these scanners can enhance the overall security of your website. Here is the list of tools you can use to scan vulnerabilities and security threats in your application:


#7 Cross-Site Request Forgery (Csrf)?

?

A CSRF attack can be a nightmare for web developers and website owners. Simply put,?a CSRF attack is when a hacker tricks a user into taking action against a website where a user is signed in. Hackers use phishing and social engineering techniques to execute a dirty CSRF attack.

Sounds complicated? Not to worry. I?also designed a diagram to see exactly how it works:

No alt text provided for this image
Fig 2 Demonstrating Cross Site Request Forgery

?Illustrating cross-site forgery request CSRF (Diagram Source)

Imagine that you accidentally visit a dangerous website while logged into a secure site in one tab. In that instance, the malicious website may attempt to delete the user's account by sending a post request to your safe website. This can be something like:


<script>

Var x = new XMLHttpRequest();

x.open("POST", 'securesysteem.com', true);

x.send('deleteACCOUNT');

</script>


Since you are logged in to the other tab, it is the rule on the internet that you submit all cookies along with every post request. Additionally, when that malicious website requests to delete your account, it will check your cookies to see if you are logged in and then delete your account. This is only one such example. There are many ways hackers can initiate CSRF attacks on your PHP websites. So what is the most convenient solution to prevent such attacks??



I recommend you check if your framework comes with a built-in CSRF Protector. If it does not, use the OWASP CSRF Protector Project. It is a well-researched project tested rigorously by experts in the industry. It can provide you with all the necessary security your site needs against csrf attacks. The OWASP CSRF Protector project has two main components:


  • An easily configurable Apache module?
  • A powerful and standalone PHP library that you can integrate with any PHP web application.?


The CSRF Protector protects the following:


  • HTML forms including POST and GET methods?
  • Normal Get requests?
  • XHR requests (AJAX)?
  • Dynamically generated HTML forms.?



Besides, if you are interested in creating a custom PHP csrf token mechanism, you should check this GitHub Project.??


Final Thoughts?

PHP website security is not only about making one smart decision. But it is more about accountability for your web applications from early development until deployment. It also includes routine PHP database and server maintenance while securing your code against malicious attacks. If you adhere to these security best practices for PHP web development, your PHP application will be less likely to be the victim of attacks.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了