Tools to Check PHP 8 Compatibility & Performance Tips

With the new PHP 8.2 set to roll out on November 24, 2022, what are your thoughts on the upgrades and the newest features? Have you done a compatibility check yet? if not, here are the right tools for you!

PHP stands for the recursive acronym Hypertext Processor, created by the Danish-Canadian programmer Rasmus Lerdorf in 1993 until Suraski and Gutmens started to take up the basic code and rewrite the core PHP, resulting in the Zend engine.

Zend engine is the standard PHP interpreter that behaves as a compiler and runtime environment and executes the PHP code.

As of October 2022, "PHP is used by 74.4% of all the websites whose server-side programming language we know" reports W3Techs.

Table Of Contents

The lack of International Components for Unicode (ICU)  and UTF-16 made PHP a fallback option for web developers back until 2014. That was when PHP 7 was released.

PHP 7

Although there was never a 6th version of the code language, the company decided to go with the no.7 since most of the users and developers mistook versions 5.4 and 5.6 as PHP 6. The PHP 7 branch was originally dubbed as PHP next generation for its WordPress-based benchmarks showed a 100% improvement in performance than the earlier versions.

Following the surge in market popularity of PHP 7, the company launched a new version of PHP 8 on November 26, 2020. This went on to become one of the best versions of the language ever released. Some of the updated functions and new features include:

  1. Just in time compilation
  2. Introduction of match expression
  3. Union types
  4. Attributes
  5. Nullsafe operator

Note: (Check out the blog on Too Many Good Features In PHP 8 for a detailed explanation of each of these features)

Further PHP 8.1 was released with additional ‘enums’ feature, read-only properties and array unpacking with string keys.

Now since PHP 7.4 is slated to be gone by November 2022, it is high time tech-geeks and enthusiasts gear up to check their browser's compatibility with the new PHP 8 versions.

PHP 8 Compatibility Checker Tools

If you are developing your website in 2022 then it is a given that you should have a PHP 7+ or more version so as to offer minimum resistance while running a programme. Let's take a look at some of the PHP compatibility check tools if you've already installed PHP 8!

  1. Phan
  2. PHP compatibility checker
  3. PHPstan
  4. PHP Parallel Lint
  5. PHPStorm

#1 Phan

Phan is a static analyzer for PHP that prefers to minimize false positives. It attempts to prove the incorrectness of the code. Phan has a good understanding of flow control and can track values in case of a few use cases like arrays, integers and strings.

Composer 2 is required or you can install it from here if you do not have it.

Phan can be installed using the below command:

composer require phan/phan

After installing phan you will have to create a .phan/config.php file in your project for Phan to analyse your source code.

Update the Phan config file with your source code directory name in the directory_list field. I have given /home/vagrant/code/Laravel-8-CRUD-Operation as the directory name. Also make sure to update the "target_php_version" to the 8.

<?php

/**
 * This configuration will be read and overlaid on top of the
 * default configuration. Command line arguments will be applied
 * after this file is read.
 */
return [

    // Supported values: `'5.6'`, `'7.0'`, `'7.1'`, `'7.2'`, `'7.3'`, `'7.4'`,
    // `'8.0'`, `'8.1'`, `null`.
    // If this is set to `null`,
    // then Phan assumes the PHP version which is closest to the minor version
    // of the php executable used to execute Phan.
    "target_php_version" => 8.0,

    // A list of directories that should be parsed for class and
    // method information. After excluding the directories
    // defined in exclude_analysis_directory_list, the remaining
    // files will be statically analyzed for errors.
    //
    // Thus, both first-party and third-party code being used by
    // your application should be included in this list.
    'directory_list' => [
        '/home/vagrant/code/Laravel-8-CRUD-Operation',
        'vendor/symfony/console',
    ],

    // A directory list that defines files that will be excluded
    // from static analysis, but whose class and method
    // information should be included.
    //
    // Generally, you'll want to include the directories for
    // third-party code (such as "vendor/") in this list.
    //
    // n.b.: If you'd like to parse but not analyze 3rd
    //       party code, directories containing that code
    //       should be added to the `directory_list` as
    //       to `exclude_analysis_directory_list`.
    "exclude_analysis_directory_list" => [
        'vendor/'
    ],

    // A list of plugin files to execute.
    // Plugins which are bundled with Phan can be added here by providing their name
    // (e.g. 'AlwaysReturnPlugin')
    //
    // Documentation about available bundled plugins can be found
    // at https://github.com/phan/phan/tree/v5/.phan/plugins
    //
    // Alternately, you can pass in the full path to a PHP file
    // with the plugin's implementation.
    // (e.g. 'vendor/phan/phan/.phan/plugins/AlwaysReturnPlugin.php')
    'plugins' => [
        // checks if a function, closure or method unconditionally returns.
        // can also be written as 'vendor/phan/phan/.phan/plugins/AlwaysReturnPlugin.php'
        'AlwaysReturnPlugin',
        'DollarDollarPlugin',
        'DuplicateArrayKeyPlugin',
        'DuplicateExpressionPlugin',
        'PregRegexCheckerPlugin',
        'PrintfCheckerPlugin',
        'SleepCheckerPlugin',
        // Checks for syntactically unreachable statements in
        // the global scope or function bodies.
        'UnreachableCodePlugin',
        'UseReturnValuePlugin',
        'EmptyStatementListPlugin',
        'LoopVariableReusePlugin',
    ],
];

After configuration, you can run it with the following command:

./vendor/bin/phan
Phan Analyzer

Features

  1. All methods, functions, classes, traits, interfaces, constants, properties, variables, and constant arguments are defined and accessible by PHP Phan.
  2. Ensures binary operations are type-safe.
  3. Check for features unsupported by earlier PHP 7.x minor releases (objects, voids, iterables, ?T, [$x] = ...;, negative string offsets, multiple exception catches, etc.)
  4. Backward compatibility checks are performed by PHP Phan for PHP8/PHP7/PHP5.
  5. Supports generic types, namespaces, union types, traits and variadics.

Refer the documentation for more features and supports offered by PHP Phan.

#2 PHP compatibility checker

The PHP Compatibility coding standard for code sniffer allows you to verify cross-version compatibility. This tool scans your code and looks for any potential compatibility issues. It then provides you with a report detailing any issues it found, along with suggested fixes. You can then go through and fix any issues, and rest assured that your code will be compatible with different versions of PHP.

To install PHP compatibility checker add the below line of code into your composer.json file:

"require-dev": {
    "phpcompatibility/php-compatibility": "*"
}
"prefer-stable" : true

Then add the following lines in the composer.json files under "scripts" to inform PHP CodeSniffer about the location of the PHP compatibility standard.

"scripts": {
    "post-install-cmd": "\"vendor/bin/phpcs\" --config-set installed_paths vendor/phpcompatibility/php-compatibility",
    "post-update-cmd" : "\"vendor/bin/phpcs\" --config-set installed_paths vendor/phpcompatibility/php-compatibility"
}

You can test the PHP code by running the following command:

./vendor/bin/phpcs -p . --standard=PHPCompatibility
PHP Compatibility Check

#3 PHPstan

This static analysis tool allows you to find the error in your code even before running it. Phpstan gives you a step-by-step overview of installing the tool and using it on your code.

With the below installation command you can easily install PHPstan:

composer require --dev phpstan/phpstan

It is important that you have the correct version of composer before installing PHPstan. Ensure that you have the latest version of composer (version 2).

First of all, you require a composer which will install PHPstan’s executable in its vendor/bin. Then use the analyse command and point to the right directories.

vendor/bin/phpstan analyse tests
PHPstan Analyzer

#4 PHP Parallel Lint

This application checks PHP files in parallel. It produces output in plain text, coloured text, JSON and check syntax formats. Nette Framework Tests inspire it. This application can be used with PHP 5.3 to 8.1.

Install with composer as a development dependency:

composer require --dev php-parallel-lint/php-parallel-lint

If you want coloured output, install PHP Parallel Lint with console highlighter using the below command:

composer require --dev php-parallel-lint/php-console-highlighter

Run PHP parallel lint with the follwoing command:

vendor/bin/parallel-lint --exclude app --exclude vendor .
PHP Parallel Lint

#5 PHPStorm

PHPStorm is an IDE developed by jet brains. It is a combination of webstorm + PHP + DB/SQL. It provides on-the-fly error prevention, code refactoring and the best autocompletion with zero configuration debugging and an extended HTML, CSS, Javascript editor.

You can install the program through any distributor. For eg., follow this command below

flatpak install flathub com.jetbrains.PhpStorm

And then run the code

flatpak run com.jetbrains.PhpStorm

Also you can download PHPStorm from here. Start the application by following the steps below:

cd path/to/phpstorm/bin

Run the IDE using the command:

./phpstorm.sh

You will be prompted to PHPStorm and, if you already have a JETBRAINS account, you can login otherwise you can create a new account and upload your PHP project.

PHPStorm

PHP 8 Performance Tips

Getting the most out of your web application is a daunting task. However, here are some tips you can use for a better performance of your codes.

#1 Enable OpCache on the PHP server

OpCache caches the pre-compiled code and doesn’t compile on later requests. Now this will save your loading time every time you input a new request. Conducting a PHP performance check after integrating OpCache will make the performance 3X faster and the load time concurrently lesser.

Start by enabling OpCache on the system before running PHP with the following command:

Add the following line to your php.ini:

zend_extension=/full
zend_extension=c:\path\to\php_opcache.d11 (win)

Note that you use the zend_extension directive instead of the normal once because it affects the actual Zend engine.

#2 Enable realpath_cache

For servers running on high traffic, we can produce additional throughput by setting PHP realpath_cache_size correctly. For best performance, also tune realpath_cache_ttl. Initially, it is better to set the size large (for example 4M for PHP 7) and then tune it down in case you have low server memory.

realpath_cache_size = 4M
realpath_cache_ttl = 130

#3 Configure Memcache for Database

Websites having large dynamic databases deploy Memcache to store their database objects in dynamic memory. Memcaching allows the retrieval of data in an easier way whenever an external source requests a read. It stores the values and keys and retrieves them the same way without parsing the database queries.

You can install Memcache by running the following command:

sudo apt-get install memcached

And then echo phpinfo() function to check if it's running.

#4 Customize output_buffering

PHP output_buffering is used to keep some data in memory rather than sending it to the web browser.

  • Log into your Linux server as root user or using sudo privileges,
  • Run the command php--ini
  • Now change the output buffering = on in the file.
  • Save this file and exit.
  • Restart the browser.
  • Create a phpinfo() page to see if the output_buffering is enabled.

You can set a custom value for output_buffering. For example, 4096 for off.

#5 Always update your PHP version

While performing compatibility checks and using OpCache might sound like an easy way to improve performance, it is always best to update your PHP versions since the developers are introducing changes that minimise all these risks and ultimately give you a better output.

Several CMS platforms have cited that an improvement from PHP 5.3 to 7 has allowed them to receive outputs much faster as the engagement in CPU instructions required has largely been reduced in the newer versions from about 100M to 25M.

Conclusion

With 80% of all the web development platforms still using PHP as their scripting language, it is certainly the one to stay. This is especially true since its developers are now adding functions that make building platforms easier for web developers.

Those still using the 5.3+ versions may be on the verge of having no choice since the upgrades in 7 and 8 are supremely high to all the ones before. Having said that, PHP 8’s significance comes in its security measures and faster loading rates at a time when the end-users are definitely not the ones to wait!

Using PHP 8 isn't just a matter of upgrading to the latest and greatest version, but involves making several configuration changes, compiling PHP, and testing out your code. As each tool has its own advantages, it has its own best features.

Check the compatibility of your PHP code with the right and best tool according to your preferences. Since Phan offers a lot of good features and is regularly updated by the committee, I personally recommend using it.

Then what are you waiting for?  Check your platform's compatibility with PHP 8 and review its performance today!


Atatus: PHP Performance Monitoring and Log Management

Atatus is an Application Performance Management (APM) solution that collects all requests to your PHP applications without requiring you to change your source code. However, the tool does more than just keep track of your application's performance. It monitors logs from all of your PHP applications and systems into a centralized and easy-to-navigate user interface, allowing you to troubleshoot faster.

We give a cost-effective, scalable method to centralized PHP logging, so you can obtain total insight across your complex architecture. To cut through the noise and focus on the key events that matter, you can search the logs by hostname, service, source, messages, and more. When you can correlate log events with APM slow traces and errors, troubleshooting becomes easy.

Try your 14-day free trial of Atatus.