Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Secure PHP Programming: Two Common Mistakes to Avoid

DZone's Guide to

Secure PHP Programming: Two Common Mistakes to Avoid

Want to learn more about securely using PHP for web applications? Check out this post to learn how to avoid these two common mistakes made by PHP programmers!

· Security Zone ·
Free Resource

Discover how to provide active runtime protection for your web applications from known and unknown vulnerabilities including Remote Code Execution Attacks.

PHP (Hypertext Preprocessor) is a server-side scripting language that has matured over the years — it was first released in 1995! The latest stable version of the language, which was released in June 2018, is PHP 7.2.7.

Despite the attempts to make the programming language secure, PHP is still full of twists, turns, and hacks that, if not correctly mastered, can introduce security vulnerabilities in your web applications.

Onko, who boasts of more than 20 years of web development experience and currently uses these skills to teach people about secure PHP programming, says that “the amazing thing about PHP is that programmers can realize simple goals very easily and swiftly. However, the problem is that most of them do not care about what is taking place behind the curtains — and they subtly expose their code to attacks.”

In this article, I’m going to illustrate two common mistakes to avoid if you want to code in PHP securely.

1. Failing to Perform Input Data Validation

Validating and sanitizing user input data are important practices for achieving PHP programming security. Essentially, it means verifying the data provided by the users of your web application so that malicious inputs can be avoided.

Here is the rule of thumb: avoid trusting any user input. Even though your application or website could be intended to collect user input for the good reasons, you never know if someone will try to enter bad input and harm your services.

For example, here is a secure HTML code that processes form data using PHP:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

As you can see from the code, the form data is processed using the “post” method. The $_SERVER["PHP_SELF"] (introduced in PHP 4) is a superglobal or automatic global variable that is available throughout the script.

It returns the filename of the presently executing script; in this case, it will transmit the submitted form data to the page itself, rather than directing to another location.

This security measure in PHP forms ensures that the user receives error messages on the same page as the form.

Furthermore, the  htmlspecialchars() function plays the critical role of converting special characters to HTML entities.

Some characters, such as < and > with &lt; and &gt, express special meaning in HTML. As such, they should be represented by HTML entities to avoid losing their significance.

The htmlspecialchars() function will return a string with all the conversations made, which offers a safeguard from hackers who want to exploit the form code through injecting HTML or other malicious code.

2. Failing to Protect Against SQL Injection

SQL injection is one of the most common types of attacks for destroying databases. It involves placing malicious code in SQL statements to reveal hidden data, override valid commands, or execute other harmful actions on the database.

Here is an example of how an attacker could carry out a simple SQL injection:

$userID = $_POST[ 'user_id' ]; //  The value here is "' OR 1′";

$querySelect = "SELECT * FROM users WHERE user_id = '$userID'";

//Result is SELECT * FROM users WHERE user_id = " OR 1"


The above code shows an insecure PHP code. In the example, the developer placed the $_POST[ ‘user_id’ ] statement right into the query on the website.

Consequently, an attacker altered the value in the hidden form from a number to ‘OR 1’ . In this case, if a database query was made for a single user, it would extract the details of all the users from the table. If the statement is altered to WHERE user_id = ‘’ OR 1 , it will extract all the rows present in the table.

To prevent such types of SQL injection attacks, you should use prepared statements and parameterized queries, such as MySQLi prepared statements or PDO prepared statements.

The prepared statements allow you to detach the data from the SQL command. This way, anything a user inputs is regarded as data and inserted into the table without any alterations.

Here is an example:

$querySelect = "SELECT * FROM users WHERE country=:country and president=:president";

$queryStatement = $database->prepare($querySelect);

$queryStatement->execute(array(":country" => $country, ":president" => $president));


As you can see from the above example, the named parameters, :country and :president , are joined to prepare(). This instructs the database to pre-compile the query and connect the values to the named parameter afterward.

Therefore, if the execute() function is run, the query is executed using the real values of the named parameters, preventing a malicious person from carrying out SQL attacks because the query is compiled beforehand.

Importantly, you should avoid preventing SQL attacks by escaping or eliminating special characters because a hacker can make use of encoding techniques to bypass such safeguards. For example, using mysqli_real_escape_string is not safe and could expose you to SQL attacks.

Wrapping Up

With the current escalation of cyber attacks, the development of a website is only complete when the developer has integrated robust measures for its safety.

Precisely, securely programming with PHP is not an option anymore; it’s essential for the success of a website.

Therefore, as you code in PHP, you should ensure that your website and other applications are safe from the hackers — and the above are two of the common mistakes you can avoid.

Do you know of any other common security mistakes that PHP programmers make? Let us know in the comments below!

Find out how Waratek’s award-winning application security platform can improve the security of your new and legacy applications and platforms with no false positives, code changes or slowing your application.

Topics:
php ,php bad practices ,php developers ,secure coding ,security ,sql injection ,input data ,data validation

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}