Don't use dl()

This advice applies only to older versions of PHP. Newer versions of PHP don't allow you to use dl() in a web environment, which is for the best!

The dl() function allows you to dynamically load a particular PHP extension for use in a single script then unload it when that script is done. While this is certainly very useful, consider what happens if you have that script being executed once every couple of seconds - PHP would need to continuously load the extension, execute the code, then unload it again, only to repeat the process a few seconds later.

In comparison, extensions that are enabled in the php.ini file are loaded once, when your web server is started, and unloaded only when the web server is stopped. This means that any scripts that take advantage of these modules execute a lot (lot) faster.

To give you an idea of the difference using dl() can make, I wrote a simple test script - in one, I used dl() to dynamically load the MySQL extension, connect to a database, then disconnect again. In the other, the MySQL extension was enabled in the php.ini file, there was resident in memory all the time, and it was also used to connect to a database then disconnect again.

Here is the two scripts:

<?php
    dl('php_mysql.dll');

    $db = mysqli_connect("localhost", "phpuser", "alm65z", "phpdb");
    mysqli_close($db);
?>
<?php
    $db = mysqli_connect("localhost", "phpuser", "alm65z", "phpdb");
    mysqli_close($db);
?>

Simple enough, right? Well, I ran each script through the Apache benchmarking tool, which called each of them 10,000 times individually and returned the amount of time each took to execute - the former took 26.88 seconds to complete, and the latter took 4.98 seconds. From this test, dl() slowed the script down by a factor of five, which should make it crystal clear that you should enable your extensions in your php.ini file, and not by using dl() unless you really cannot help it.

 

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: Debug your code >>

Previous chapter: Don't use CGI

Jump to:

 

Home: Table of Contents

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