Skip to content

Instantly share code, notes, and snippets.

@Xophmeister
Created July 24, 2012 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xophmeister/3172878 to your computer and use it in GitHub Desktop.
Save Xophmeister/3172878 to your computer and use it in GitHub Desktop.
Simple, session-persistent error handling
<?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();
}
?>
<?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();
?>
@Xophmeister
Copy link
Author

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, call complain(), which will redirect you to an error page (defaults to showErrors.php, but can be changed at construction) if there are any problems. The error page can then use show() 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!?

@Xophmeister
Copy link
Author

Forked into php-stack

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment