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.

 

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

Previous chapter: PHP Encoders

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar