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:
[code lang=”php”]
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’);
}
}
[/code]
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:
[code lang=”php”]
function stripSlashesDeep($value) {
$value = is_array($value) ? array_map(‘stripSlashesDeep’, $value) : stripslashes($value);
return $value;
}
[/code]
This function is used in the next one:
[code lang=”php”]
function removeMagicQuotes() {
if ( get_magic_quotes_gpc() ) {
$_GET = stripSlashesDeep($_GET );
$_POST = stripSlashesDeep($_POST );
$_COOKIE = stripSlashesDeep($_COOKIE);
}
}
[/code]
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:
[code lang=”php”]
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]);
}
}
}
}
}
[/code]
And your app is secure again.
I hope that this little functions will help you in your PHP life.
Nice post!
Personally for error_reporting I prefer -1 instead of E_ALL so that it includes strict warnings.
Now, that you mentioned it, I see it is even better to use -1. Thanks for the tip.
No problem. Glad I could share a tip!!
Should be error_reporting(-1) because of php 5.3
Comments are closed.