Predicting the Future of PHP Security – Part 3

In some ways security is an infinite game of chess on a board the size of the world. For every move you make, the hackers have a countermove ready. They are highly motivated to take what you have, so the game never ends; it just switches players once in awhile. In this final blog in the series, we are going to review the game board, with a look at the most recent changes to security in PHP 7 and earlier supported versions. Then, we’ll try to look a few moves ahead with predictions for the future of PHP security.

The Problem with Popularity

It is understandable that PHP has attracted a considerable amount of attention from hackers because it is one of the most popular programming languages on Earth, according to the TIOBE index.

In various versions, PHP is currently running underneath the vast majority of sites on the web. Web Technology Surveys reported that PHP is used by about 82 percent of all websites where it is possible to know the server-side language.

PHP 7 Released

The biggest change in the landscape since we left off in Part 2, is that PHP has gone in for a complete makeover. PHP 7 was released in December, the first major update in more than a decade and coming in with an emphasis on faster loads and new functionalities. In case you were wondering what ever happened to PHP 6, it did not happen at all. Unicode failures were too severe, and it had to be scrapped.

This year, some security updates have already been issued, so check on the site to make sure you have the latest update. They are also still supporting the 5.5 and 5.6 release with a number of security patches.

The new release is confirmed to be faster and more stable by plenty of benchmarks and testing sites. The official benchmarks validate PHP 7 running twice the speed of PHP 5.6 in common deployments. The update handles double the number of requests per second, so most users with typical applications like WordPress sites will see a noticeably faster load. For those running data centers, they will essentially double their capacity for running more applications or features.

Security Upgrades in PHP 7

There are still some serious issues with security, however. In their State of Software Security Report 2015, Veracode performed cloud-based scans and code analysis of more than 50,000 applications. They reported that approximately 86 percent of PHP applications showed evidence of cross-site scripting (XSS). Also, more than half (56 percent) appeared to have with at least one SQL injection bug. In part one of this series, we discussed how to handle both of those common flaws in PHP. Below are some of the significant security upgrades in PHP 7.

Whitelist Classes

The new filtered unserialize() feature is a more secure approach to unserializing objects in un-trusted data. You will be able to whitelist classes that can be unserialized to head off the possibility of code injections. This lets you pass complex data structures around as strings.

Cryptographically Secure Random Numbers

There are now two ways to generate both integers and strings. If you are coming from another object-oriented language, you may be thrilled to see these two.

string random_bytes ( int $length )


int random_int ( int $min , int $max )

These are useful any time that you need unbiased results. Also, if you are still running an earlier version of PHP, you can apply these functions with this userland implementation (for PHP versions 5.2 – 5.6).

Override Configurations

If you ever need to completely override session configuration directives in php.ini, you can now handle it with

bool session_start ([ array $options = [] ] )

The PHP manual explains:

“This creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.

The save handlers you use could be ready-built ones that were provided by default, or you could use PHP extensions like SQLite or Memcached. The other option you have is to use a custom handler that you would define in:

bool session_set_save_handler ( callable $open , callable $close , callable $read , callable $write , callable $destroy , callable $gc [, callable $create_sid ] )

Of course, the read callback here can retrieve any existing session data that is stored in a special serialized format. It will be unserialized and used to automatically populate the $_SESSION superglobal. That will be after the read callback returns saved session data back to your PHP session handling.

These are so important because custom save handlers give you more flexibility in what you do with the session data. For example, you can lower the risk of unauthorized use of a session by ending the session after a specified idle time.

Additional PHP Security Patches

In January, the PHP 7.0.2 update was released to address 31 reported errors and six of those were to seal off potential security vulnerabilities. At the same time, the older versions got updates too. PHP 5.6.17 addressed problems with 14 identified bugs, and PHP 5.5.31 was designed to close vulnerability loopholes. The developer announced that PHP 5.5 will be in security support mode from now until July 2016.

In terms of security, it is also critical to note that PHP 5.4 is no longer maintained, so if you are running that version, your site or application will be vulnerable to all kinds of attacks and exploits. Here are some of the potential attacks and remote code execution routines that the latest updates we designed to counter.

Buffer Overflows

PHP fixed a heap buffer overflow to prevent a hacker from passing a string longer than 1 billion characters to


The end goal is to overwrite the return pointer of the function. The hacker might then be able to change the flow of the code execution.

Memory Leaks

Another update addressed the memory read error in the GD graphics library. In the past, hackers could use this vulnerability to gain access to substantial and contiguous chunks of your memory. It works by passing a large number that exceeds the color palette array to ImageRotate.

Another potential memory leak that was plugged up was an error in FPM, the FastCGI Process Manager. In the older versions, whenever a long token like an HTTP request with an extra-long query string came at the end of the access.format option of FPM, the code would try to write outside the compiled buffer. PHP listed the severity as low because several other conditions would have to exist in addition before hackers could exploit this vulnerability.

Remote Code Executions

A potentially more serious threat was addressed by closing up the user-after-free vulnerability in WDDX, the Web Distributed Data eXchange interface. Hackers would have been able to remotely execute malicious code if this were still in place. Even when values are freed from memory during packet deserialization, malicious recordsets could gain use of the free memory.

Type Confusion

One update was targeted at eliminating type confusion vulnerabilities in WDDX. These left applications open to remote code execution attacks. Hackers would have been able to deserialize a string type and create their own hash table to insert.

Updates also addressed a second type confusion vulnerability in XMLRPC-EPI, which is the XML-RPC protocol for PHP. This would have left a door open for hackers to do a lookup on arbitrary memory addresses. That could lead to memory leaks or a complete crash of your PHP code.

What’s Coming Next for PHP

Adam Englander at LaunchKey made a significant prediction about where PHP might be headed in the very near future. Englander, speaking to other PHP developers at Reddit, said:

“You will start to see some movement into real hardware level Internet of Things (IoT) development in PHP. With a true asynchronous programming framework to take advantage of asynchronous I/O, you will now be able to write PHP applications to easily receive input from GPIO based hardware on Raspberry Pi, Intel Edison, and other IoT devices running Linux operating systems.”

It makes perfect sense that PHP will be looking for ways to expand its interoperability with other frameworks this year, and IoT is a field where a great of development is happening right now. As you may have noticed at CES this year, a host of consumer and professional markets are filling up with IoT devices and applications.

The problem is that security will need to get much tighter for PHP applications in IoT applications that interface with cars, automated door locks, location services, private identifying information and a host of other things that hackers will be extremely interested in accessing.

Getting the security piece right is incredibly important, and even more so, it is an enormous opportunity for any developers hoping to stay one move ahead of the hackers.

Just in case you missed anything, here’s a TL;DR for the entire blog:

  • PHP is super popular, running under around 82 percent of websites. That is why so many hackers want to break it.
  • PHP 7 just came out, the first major update in more than ten years.
  • You can now whitelist classes by unserializing untrusted data.
  • You can generate cryptographically secure random numbers
  • You can reset and override session configuration.
  • Patches addressed buffer overflows, memory leaks, remote code executions and type confusion vulnerabilities.
  • In the very near future, expect to see PHP working its way into the Internet of Things (IoT). That will issue in a new era of security concerns and advances.

Introduction to PHP Security – Part 1

It is a question that has daunted software engineers for decades: how secure is my software application? Modern web application development has evolved to a point where one can build and launch an entire product or company revolved around a full-fledged software-as-a-service. The only interface to your product is the UI provided via a browser, mobile application, or the data exposed by your web service API. Unfortunately, as these modern software media continue to evolve into more sophisticated platforms, so do the areas in which your product and your data become exposed to potential security risks, criminal intrusions, and data theft.

We’ll explore in this blog frequent channels of attacking and exploiting a PHP application. This blog is by no means an official guide to the security of your application, and you should always consult with your team of security experts on the best practice for your application environment.

Common Attacks

For starters, we’ll cover some of the most common attacks that you should be aware of. Almost all modern frameworks, libraries, and extensions have built-in mechanisms to patch these popular methods of attacks, but we’ll cover them nonetheless. These attacks are extremely simple to do and very easy to thwart, but they are very damaging if left exposed to the public.

Cross-Site Scripting (XSS)

All the data that you present to your users are not entirely hosted by you, contrary to popular belief. Modern web applications are extremely dynamic and pull data from various sources. In some instances, your site could provide the ability for a user to leave comments via a form. From inside that form, a hacker could paste a <script> tag pointing to a malicious script on another remote server.

This comment is then saved in the database, retrieved again for another user, and displayed in that user’s web browser. Because the attack is HTML, the hack does not display when rendered in the browser. However, if you use the view-source command on the page, you’ll easily see the embedded Javascript that was inserted and executed in your browser and every browser of the users of the site. Potentially, millions of your customers could be compromised by running unknown Javascript that is served by your application but points to another remote file controlled by hackers!

Further, the hacker can place more than just a <script> tag. XSS involves <iframe>, <body>, and even <img> exploits. How do you avoid this? You sanitize all the data that you receive from users!

Common sanitation techniques include strip_tags(), htmlspecialchars(), and other data filtering techniques.  

SQL Injection

This exploit is creative and, frankly, deadly to your database. Imagine, for instance, that you are passing information from one page to another via hidden fields in a form.

In this case, you are accessing $_POST[‘user’], and the value is 23 and $_POST[‘password’]. Then, you move on to the database to perform a SELECT from your user table where user = 23. This particular attack overrides the SQL and inserts an additional statement so that your query returns true. For example, where you normally perform this:

SELECT user_id FROM user WHERE user_id = ‘23′ and password = ‘bla’

this hacker could override that by making you execute this:

SELECT user_id FROM user WHERE user_id = ‘23′ and password = ‘bla’ OR ‘true’ = ‘true’

The query above can run successfully and return true, even though the password is incorrect, causing your hacker to gain access by only knowing the user_id and not knowing the password at all!

To learn how to avoid database hacks, you can scroll down to the Database section (below).

Security Best Practice

OK, we’ve covered a couple of the most common attacks look like. Let’s dive into software development best practices and how they can help protect you from being vulnerable to attacks.

Security is a moving target. There is no perfect method of protecting yourself from the infinite exploits that could potentially exist. What does one do in this case in order to avoid being compromised? There are some basic best practices that should be implemented in your PHP environment.

Keep your PHP Upgraded

Always keep your PHP version up-to-date. I cannot stress this enough. You would probably be shocked at the amount of PHP users today who are running vulnerable versions of PHP, going as far back as PHP 4! Even within the PHP 5 series, always keep up-to-date with the latest version, and keep in mind that the PHP group does drop support and will end-of-life a version, regardless of who is running it. This means your PHP version could be outdated and vulnerable.

Keep SSL on at all times

There used to be a time when SSL was only used for when dealing with financial or health records. In other words, SSL was used when federal regulatory bodies required it. However, best practice is beginning to dictate that SSL always be turned on at all times throughout the lifetime of a customer session. The threat to security has unfortunately become so prevalent that even the most basic of requests can come under threat. For this reason and others, turning on SSL at all times has become a common practice in most web applications.

Validate everything that you collect and that is sent to you

All information that is passed to your application is suspect. There is no exception to this rule. Even if you receive this information from a third-party web service API, there is no guarantee that their data is not contaminated. You cannot vouch for the security of another company, so it is probably best to practice good data validation against information received from the outside world.

This information can be in the form of input from your users, partner access to your web service API, or perhaps even local files you are opening with PHP to parse through. Before any data is processed, saved to a database, or returned to your customers, you should always run the data through basic sanity checks.

Also, keep in mind that the session data that you set can be jeopardized. For example, when you set a cookie value on the client side, that value can be manipulated; so, the next time you access it, you should validate that data. You probably shouldn’t see sensitive information in your cookies, but just in case, verify the data, too.

Take a look at the filter_var() and filer_input() functions and see how you can fit it into your sanitation workflow. Configure your php.ini for optimal security. Your php.ini file may contain serious security flaws if you do not configure your environment correctly. I wrote another blog piece on this topic that you can read. In that blog post, I have a section that covers a basic introduction to security, but also covers other basic declaratives that you should be aware of.

Follow proper Error Reporting practices

The general rule when it comes to error reporting is: report everything in development, display nothing in production.

This means that, while you are in development mode, you want to be aware of all potential issues with your PHP application – including Notices, Warnings, and, of course, Errors. However, in production, you never want error information to be displayed to your visitors. Not only will you avoid upsetting your customers, but you’ll also avoid displaying secure information that could be used against you if it fell into the wrong hands.

Configuration Files – Keep them safe and hidden

All modern frameworks and web applications require configuration files. These are the files that contain access information, connection info, passwords, database connectivity, and environment-specific variables. Obviously, this file is extremely sensitive and should never be compromised. You do not want these files in your public web directories. Configuration files should always be at least one directory above your public web folders and accessed from within the application itself by a front controller or the framework.

Front Controller Method – Keep PHP files private

This approach is possible with almost all modern PHP frameworks. The only file that should be exposed in your public web root folder is your front controller or index.php. Your front controller then instantiates your framework object, dispatches all requests to the internal router, and includes the necessary framework files by going one level down. This way, you never have any of your application files exposed to the Internet and only have a single point of entry that you can lock down to make more secure.

Database Abstraction Libraries are your friend

If you are using a framework, you are probably using a database abstraction layer. Alternatively, at the least, you could be using MySQLi or PDO. Regardless of what method you use to interface with your database backend, all data should be sanitized before being inserted into your database. Specifically, by using prepared statements, you ensure that your database libraries perform all the tedious work of extracting and removing potentially malicious data hidden inside your inputs. Remove unnecessary PHP extensions. You do not want to have more extensions than you need. Perform a quick phpinfo() on your PHP runtime to find out how many extensions you have loaded and remove all the extensions that you do not need. By including extensions that you do not need, you are introducing potential performance overhead and security risks. The more variables you can remove from the equation, the less you have to worry about. It is just good practice, in general, not to load more extensions than necessary.


This list barely scratches the surface in regards to PHP security. There are more advanced topics, including proper password hashing and encryption techniques, proper session and cookie management, file and permissions techniques, web server and firewall configurations, and more. I hope this post, at least, provides a basic introduction to PHP security topics as a starting point in securing your application and your customer data.


Interested in gaining end-to-end visibility of your PHP application? Check out a FREE trial today!  

Staying current matters: Why to upgrade PHP?

PHP 5.2 was released in 2006. If you are still running PHP 5.2, it is time to join 2013 and upgrade to at least PHP 5.4 if not to the currently stable PHP 5.5.6. There are many reasons to upgrade your PHP stack to the latest and greatest — not only does every release include new features and stability improvements, but more importantly, they also have security fixes. Security is essential for the trust of your users. If you are continuing to run PHP 5.2 you are throwing your users’ trust away. There were over 100 vulnerabilities in the first four releases in PHP 5.2.x. It is outdated, expired, past due and no longer suitable for production applications. Strong words, eh? Just take a look at the list of known vulnerabilities since PHP 5.2:


Do the right thing and make some progress on your technical debt. Your users will thank you.

Find out how to upgrade on your distribution

At AppDynamics we support PHP from version 5.3 to 5.5 (and PHP 5.2 coming soon due to popular demand). If you aren’t running PHP 5.4 or newer you really should take the time to update. Not only are there critical security fixes, but you will see better performance immediately!

Take it a step further and harden PHP and check your project for known vulnerabilities

“PHP, like any other large system, is under constant scrutiny and improvement. Each new version will often include both major and minor changes to enhance security and repair any flaws, configuration mishaps, and other issues that will affect the overall security and stability of your system. Like other system-level scripting languages and programs, the best approach is to update often, and maintain awareness of the latest versions and their changes.”

Take five minutes to get complete visibility into the performance of your production applications with AppDynamics Pro today.

As always, please feel free to comment if you think I have missed something or if you have a request for content in an upcoming post.