4 awesome PHP functions you must use every time

Sep 08, 2010 5 Comments by

As you already know, when you build applications for many clients, you have unpredictable environments, server settings and configurations. To avoid this, I am using 4 simple but effective PHP functions and am sharing them today.

I like to have error reporting on the highest possible level during development. But, we must not show those error messages on the production server. So, I wrote a simple function which checks my DEVELOPMENT_ENVIRONMENT constant and acts accordingly:


function setReporting() {
    if (DEVELOPMENT_ENVIRONMENT == true) {
        error_reporting(E_ALL);
        ini_set('display_errors','On');
    } else {
        error_reporting(E_ALL);
        ini_set('display_errors','Off');
        ini_set('log_errors', 'On');
        ini_set('error_log', ROOT.DS.'lm/tmp'.DS.'logs'.DS.'error.log');
    }
}

You can easily change the path to your error log on the last line.

Second function is a helper for striping slashes which I am using in my third function. So here it is:


function stripSlashesDeep($value) {
    $value = is_array($value) ? array_map('stripSlashesDeep', $value) : stripslashes($value);
    return $value;
}

This function is used in the next one:


function removeMagicQuotes() {
    if ( get_magic_quotes_gpc() ) {
        $_GET     = stripSlashesDeep($_GET   );
        $_POST   = stripSlashesDeep($_POST  );
        $_COOKIE = stripSlashesDeep($_COOKIE);
    }
}

If the environment is using Magic Quotes, the above function will take care of it.

And last, but not least, function that is checking for devil’s Registered globals settings and dealing with it succesfully:


function unregisterGlobals() {
    if (ini_get('register_globals')) {
        $array = array('_SESSION', '_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');
        foreach ($array as $value) {
            foreach ($GLOBALS[$value] as $key => $var) {
                if ($var === $GLOBALS[$key]) {
                    unset($GLOBALS[$key]);
                }
            }
        }
    }
}

And your app is secure again.

I hope that this little functions will help you in your PHP life.

Tips

About the author

I am a passionate web developer with more then 10 years experience in PHP and other web related technology. My main interest is backend side of the web, but was doing both sides.

5 Responses to “4 awesome PHP functions you must use every time”

  1. Wayne May says:

    Personally for error_reporting I prefer -1 instead of E_ALL so that it includes strict warnings.

  2. DmitrySh says:

    Should be error_reporting(-1) because of php 5.3

Leave a Reply