Custom Error Handling Function

This PHP function prints a nicely formatted error message out to the screen and ends the script. I use it frequently in my other code, so I figured I should post it here.

<?php

function custom_die($args=false,$h1=false,$show_header=true,$show_footer=true) {
	//note: if $args comes in as a string, it is actually $args['error']
	//this lets you access the function in shorthand
	if (!is_array($args)) { $args = array('error'=>$args); }

	//get all the options set
	if (!array_key_exists('h1',$args)) { $args['h1'] = $h1; }
	if (!array_key_exists('show_header',$args)) { $args['show_header'] = $show_header; }
	if (!array_key_exists('show_footer',$args)) { $args['show_footer'] = $show_footer; }
	if (!array_key_exists('error',$args)) { $args['error'] = false; }
	if (!array_key_exists('class',$args)) { $args['class'] = false; }
	if (!array_key_exists('message',$args)) {
		if ($args['error']) { $args['message'] = 'Error! '.$args['error']; }
		else { $args['message'] = false; }
	}
	if (!$GLOBALS['ip']['error_class']) { $GLOBALS['ip']['error_class'] = 'alert'; }

	//display the page header, if there is one. note: you'll want to include a line within page_header() preventing it from running twice
	if (($args['show_header']) && function_exists('page_header')) { echo page_header(); }
	if (($args['h1']) && is_string($args['h1'])) { echo '<h1>'.$args['h1'].'</h1>'; }

	//display the error (or message) itself
	if ($args['message']) {
		if ($args['class']) { $class = ' class="'.$args['class'].'"'; }
		elseif ($args['error']) { $class = ' class="'.$GLOBALS['ip']['error_class'].'"'; }
		else { $class = ' class="status"'; }
		echo '<p'.$class.'>'.$args['message'].'</p>';
	}

	//display the page footer, if there is one.
	if (($args['show_footer']) && function_exists('page_footer')) { echo page_footer(); }
	die();
}

//custom header and footer functions are needed for this
//these are obviously pretty basic, just to show the idea
function page_header() {
	if (array_key_exists('header_displayed',$GLOBALS) && ($GLOBALS['header_displayed'])) { return ''; } //if already displayed, don't display again
	$GLOBALS['header_displayed'] = true;
	return '<html><body>';
}

function page_footer() {
	if (array_key_exists('footer_displayed',$GLOBALS) && ($GLOBALS['footer_displayed'])) { return ''; } //if already displayed, don't display again
	$GLOBALS['footer_displayed'] = true;
	return '</body></footer>';
}

?>

Comments

Loading…

This post was first published on August 7th, 2014 and last updated on April 20th, 2015 by Robert James Reese in PHP. Before using any of the code or other content in this post, you must read and agree to our terms of use.