Archive for October, 2008

Gracefully handling errors in php using advanced techniques

Saturday, October 11th, 2008

There are a few ways in which you can handle errors in PHP. You can do the not so smart thing and just turn them off altogether using


However this is not a good idea, and should never happen. If you want to hide all of your errors, you can set it so that you have them hidden, but log them to a file instead


That will then log all of your errors to your server error log by default. If you wish to set the log to a different file you can do so by using


and that will log all of your errors to error.log in the /path/to/your/ directory.

Another option is to use a custom function to handle all errors. This can be useful should you wish to log all of your errors to a database so that you can use queries to view errors instead. The way that we tell PHP that we want to handle the errors ourselves is to use the set_error_handler() function and pass the name of the function we want to handle the errors.


Then we make a function to handle the errors. For example if you wanted to add the error to your database table it would look something like this

function custom_error_func($errno, $errmsg, $filename, $line, $context)
    // Create query - NOTE: This is using the mressf() function that I created available at
    $query = mressf("INSERT INTO `errors` VALUES(NULL,'%s','%s','%s','%s','%s')",
    //run query

If you wish to have any of the above ini_set() functionalities set permanently on your server, you may be able to if you have access to either the php.ini file or your .htaccess allows you to make php changes you can do so quite simply. For the php.ini file, simply search the file for display_errors for example and modify the value in there. If you are using .htaccess, you may be able to use the php_flag or php_value settings to modify the data. For more information on setting values this way, see here

sprintf and mysql_real_escape_string all in one function

Wednesday, October 8th, 2008

Well as many php developers will know, there is the arduous task of having to sanitize all of your data before actually being able to add it to your queries for running in MySQL. So I decided to make a small function that would basically be a clone of the sprintf function, with the added bonus of running the mysql_real_escape_string on all of the arguments passed to it

function mressf()
    $args = func_get_args();
    if (count($args) < 2)
        return false;
    $query = array_shift($args);
    $args = array_map('mysql_real_escape_string', $args);
    array_unshift($args, $query);
    $query = call_user_func_array('sprintf', $args);
    return $query;

You would then call it as you would with your regular sprintf function such as

echo mressf("SELECT * FROM `table` WHERE `name` = '%s' AND `password` = '%s'", 'username', 'pass');

which would return

SELECT * FROM `table` WHERE `name` = 'username' AND `password` = 'pass'