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.

1.   <?php
2.   
3.   function custom_die($args=false,$h1=false,$show_header=true,$show_footer=true) {
4.   	//note: if $args comes in as a string, it is actually $args['error']
5.   	//this lets you access the function in shorthand
6.   	if (!is_array($args)) { $args = array('error'=>$args); }
7.   
8.   	//get all the options set
9.   	if (!array_key_exists('h1',$args)) { $args['h1'] = $h1; }
10.  	if (!array_key_exists('show_header',$args)) { $args['show_header'] = $show_header; }
11.  	if (!array_key_exists('show_footer',$args)) { $args['show_footer'] = $show_footer; }
12.  	if (!array_key_exists('error',$args)) { $args['error'] = false; }
13.  	if (!array_key_exists('class',$args)) { $args['class'] = false; }
14.  	if (!array_key_exists('message',$args)) {
15.  		if ($args['error']) { $args['message'] = 'Error! '.$args['error']; }
16.  		else { $args['message'] = false; }
17.  	}
18.  	if (!$GLOBALS['ip']['error_class']) { $GLOBALS['ip']['error_class'] = 'alert'; }
19.  
20.  	//display the page header, if there is one. note: you'll want to include a line within page_header() preventing it from running twice
21.  	if (($args['show_header']) && function_exists('page_header')) { echo page_header(); }
22.  	if (($args['h1']) && is_string($args['h1'])) { echo '<h1>'.$args['h1'].'</h1>'; }
23.  
24.  	//display the error (or message) itself
25.  	if ($args['message']) {
26.  		if ($args['class']) { $class = ' class="'.$args['class'].'"'; }
27.  		elseif ($args['error']) { $class = ' class="'.$GLOBALS['ip']['error_class'].'"'; }
28.  		else { $class = ' class="status"'; }
29.  		echo '<p'.$class.'>'.$args['message'].'</p>';
30.  	}
31.  
32.  	//display the page footer, if there is one.
33.  	if (($args['show_footer']) && function_exists('page_footer')) { echo page_footer(); }
34.  	die();
35.  }
36.  
37.  //custom header and footer functions are needed for this
38.  //these are obviously pretty basic, just to show the idea
39.  function page_header() {
40.  	if (array_key_exists('header_displayed',$GLOBALS) && ($GLOBALS['header_displayed'])) { return ''; } //if already displayed, don't display again
41.  	$GLOBALS['header_displayed'] = true;
42.  	return '<html><body>';
43.  }
44.  
45.  function page_footer() {
46.  	if (array_key_exists('footer_displayed',$GLOBALS) && ($GLOBALS['footer_displayed'])) { return ''; } //if already displayed, don't display again
47.  	$GLOBALS['footer_displayed'] = true;
48.  	return '</body></footer>';
49.  }
50.  
51.  ?>

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.