Created
July 24, 2012 21:45
-
-
Save Xophmeister/3172878 to your computer and use it in GitHub Desktop.
Simple, session-persistent error handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ErrorStack { | |
private $errorPage; | |
private $stack; | |
function __construct($errorPage = 'showErrors.php') { | |
$this->errorPage = $errorPage; | |
} | |
public function add($desc) { | |
global $currentFile; | |
if ($currentFile != $this->errorPage) { | |
$this->stack[] = array('timestamp' => time(), | |
'description' => $desc); | |
} | |
} | |
public function show() { | |
if (is_array($this->stack)) { | |
return array_reverse($this->stack); | |
} else { | |
return false; | |
} | |
} | |
public function complain() { | |
global $currentFile; | |
if (count($this->stack) > 0 && $currentFile != $this->errorPage) { | |
$pickled = serialize($this); | |
$_SESSION['err'] = $pickled; | |
@header('Location: '.$this->errorPage); | |
exit; | |
} | |
} | |
} | |
// Initialise | |
// (n.b., Needs to be within a session) | |
if (isset($_SESSION['err'])) { | |
$err = unserialize($_SESSION['err']); | |
} else { | |
$err = new ErrorStack(); | |
} | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
session_destroy(); | |
session_start(); | |
$currentFile = end(explode('/', $_SERVER['PHP_SELF'])); | |
include "error.php"; | |
// I don't work after 5pm | |
if (date("G") >= 17) { | |
$err->add('Go away! Sleeping!'); | |
} | |
$err->complain(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a very simple error handling class: You add errors to the stack, as-and-when they occur, using the
add('Error text')
method; after everything that could have gone wrong, callcomplain()
, which will redirect you to an error page (defaults toshowErrors.php
, but can be changed at construction) if there are any problems. The error page can then useshow()
to output the stack, which also includes UNIX timestamps.To persist the error data across pages, you can simply serialise the class into a session variable (which, of course, requires you to do the session handling first). Also note that the global
$currentFile
indicates the filename of the currently running script. I know global state isn't cool, but fuck: it's PHP! What do you want!?