Cross-platform code 1: Loading extensions

The dl() function lets you load PHP extensions at run-time, which is a simple way of making sure a particular extension is available to your script. Of course, it is best to have the extension loaded in the php.ini file because it's a lot faster.

The problem with dl() is that it requires the filename and extension of the extension you want to include, and extensions differ across platforms. PHP extensions on Windows start with php_ and end with .dll, whereas PHP extensions on Unix just end with .so. For example, the IMAP extension we looked at back in the Networks chapter is called php_imap.dll on Windows, and just imap.so on Unix - remember that dl() needs that full filename, so we need to add some special code to check which to load.

Luckily, PHP makes available a special constant value, PHP_SHLIB_SUFFIX, which contains the file extension of PHP extensions on that platform. As such, the code below works around the problems of dl(), by choosing how to load the extension based upon the platform.

<?php
    if (!extension_loaded('imap')) {
        if (PHP_SHLIB_SUFFIX == 'dll') {
            dl('php_imap.dll');
        } else {
            dl('imap.' PHP_SHLIB_SUFFIX);
        }
    }
?>

Note that the non-Windows code uses PHP_SHLIB_SUFFIX - this allows for platforms that do not use .so as their extension, such as NetWare, which uses .nlm.

In all modern versions of PHP, dl() is available only in the CLI SAPI. It used to be available in Apache too, but that just proved too much of a nightmare for the developers, and was pretty darn poor for performance too!

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Cross-platform code 2: Using extensions >>

Previous chapter: PHP Encoders

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.