PHP error handler

Nothing is more disturbing in an web application than beeing interupted by an error message. So what should i do?

Make you own error handler for your php application and include it at the top of every script.

Here is the code:

 'ERROR',
		E_WARNING => 'WARNING',
		E_PARSE => 'PARSING ERROR',
		E_NOTICE => 'NOTICE',
		E_CORE_ERROR => 'CORE ERROR',
		E_CORE_WARNING => 'CORE WARNING',
		E_COMPILE_ERROR => 'COMPILE ERROR',
		E_COMPILE_WARNING => 'COMPILE WARNING',
		E_USER_ERROR => 'USER ERROR',
		E_USER_WARNING => 'USER WARNING',
		E_USER_NOTICE => 'USER NOTICE',
		E_STRICT => 'STRICT NOTICE',
		E_RECOVERABLE_ERROR => 'RECOVERABLE ERROR'
		);
 
	// create error message
	if (array_key_exists($errno, $errorType)) {
		$err = $errorType[$errno];
	} else {
		$err = 'CAUGHT EXCEPTION';
	}
 
	$mail = "Error Report\n--------------\n\n";
	$mail .= 'called Script: ' . $_SERVER['PHP_SELF'] . "\n";
	if (isset($_SERVER['HTTP_REFERER'])) {
		$mail .= 'from Script: ';
		$mail .= $_SERVER['HTTP_REFERER'];
	}
 
	$mail .= "\n";
	$mail .= '$_REQUEST:' . "\n";
	$mail .= print_r($_REQUEST, true);
	$mail .= '_FILES:' . "\n";
	$mail .= print_r($_FILES, true);
	$mail .= "\n" . 'Error Type: ' . $err;
        $mail .= " \n----------\n[$errno] $errstr\n\nFatal error in line $errline of file $errfile" . "\n";
 
	$mail .= backtrace();
 
	if (DEBUG) {
		// output the error on the site
		echo nl2br($mail);
	} else {
		// sent the output to the syslog
		// syslog(LOG_INFO, $mail);
 
		// or via mail
		mail(ERROR_EMAIL, 'Error ' . $_SERVER['PHP_SELF'] . '-' . $errline . '', $mail);
	}
 
	switch ($errno) {
		case E_ERROR:
		case E_USER_ERROR:
		case E_COMPILE_ERROR:
		case E_CORE_ERROR:
		case E_RECOVERABLE_ERROR:
			// exit the script or display a message when the error is critical
			exit();
	}
}
 
// set the error handler to our new handler
set_error_handler('myErrorHandler');
 
?>

With this little script you can choose what to do if an error occurs. Perhaps send an Mail to Bugtracker or to your work email. Or if you just in the development display it on the site.

If you have questions feel free to ask in the comments.

Example of using PHP PDO

Welcome to the first Tutorial about PHP and the PDO database interface.

Here is some code using PDO for simple data fetching:

exec("INSERT INTO table_name (colum1,colum2)
                 values ('content for colum 1','content for colum 2')");
#the query for the result display
$sql = 'SELECT colum1,colum2 FROM table_name ORDER BY colum1';
# go trough each row of the query
foreach ($database->query($sql) as $row) {
        # display the content of the rows
        print $row['colum1'] . ' | ';
        print $row['colum2'] . PHP_EOL;
}
?>

This should get you started on using PDO. If you have any questions please use the comments.