Chapter 21. Distributing Your Code

Once you have your ideal scripts written, very often you will want to give them to other people. Perhaps you have written code to generate graphs or predict the weather, or perhaps you have just written Yet Another Forum (YAF)—it does not matter what you write, because there are few feelings quite as nice as watching people take your code and use it.

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 ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.