21.1. Cross-Platform Code 1: Loading Extensions
The dl( ) function lets you load PHP extensions at runtime, 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; however, that is not always possible.
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 is called php_imap.dll on Windows, and just imap.so on Unix. The dl( ) function needs that full filename, so we need to add some special code to check which to load.
Luckily, PHP has 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:
function useext($extension) {
if (!extension_loaded('$extension')) {
if (PHP_SHLIB_SUFFIX = = 'dll') {
dl('php_$extension.dll');
} else {
dl('$extension.' . PHP_SHLIB_SUFFIX);
}
}
}
useext("imap");
The non-Windows code uses PHP_SHLIB_SUFFIX for platforms that do not use .so as their extension, such as NetWare, which uses .nlm.
|