on Tips

4 awesome PHP functions you must use every time

5 comments
php
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

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.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon



  • Nice post!

  • Wayne May

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

    • Zvonko

      Now, that you mentioned it, I see it is even better to use -1. Thanks for the tip.

      • Wayne May

        No problem. Glad I could share a tip!!

  • Should be error_reporting(-1) because of php 5.3