Posts Tagged ‘PHP’

Error reporting with CodeIgniter

February 23rd, 2009 5 comments

While CodeIgniter does come with a reasonable error logging tool its simple nature of just dumping a single line report to a file on a distant server does not seem too pro-active for my tastes.

The following helper replaces the default CI error reporting with a new error reporting interface that also emails any errors that occur to a nominated developer.

* Info:

// Where to send the error report. Leave blank for nowhere
define('ERR_MAIL_TO', '');

 // Literal name of that person
define('ERR_MAIL_TO_NAME', 'Joe Random');
define('ERR_MAIL_FROM', '');
define('ERR_MAIL_FROM_NAME', 'Error Daemon');
define('ERR_MAIL_METHOD', 'SMTP'); // Supported: SMTP
define('ERR_MAIL_HOST', 'localhost');
define('ERR_MAIL_SENDER', '');

 // The subject of the mail. Supported tags: [TYPE], [FILE], [LINE], [STRING], [BASENAME]
define('ERR_MAIL_SUBJECT', 'Error detected: [TYPE] @ [BASENAME]:[LINE]');
 // Other things of interest to include in the email. CSV of supported values: POST, GET, SERVER, GLOBALS, SESSION

// Relative location of PHP mailer to this file
// (Not relative to the working directory because that doesn't specify correctly with fatal errors).
// By default this assumes that the 'phpMailer' folder is located in the same directory as this script.
define('ERR_PATH_PHPMAILER', 'phpMailer/class.phpmailer.php');

function err($errno, $errstr, $errfile, $errline, $errcontext) {
	$errtable = array(
		1 => 'Fatal',
		2 => 'Warning',
		4 => 'Parse Error',
		8 => 'Notice',
		16 => 'Core Error',
		32 => 'Core Warning',
		64 => 'Compile Error',
		128 => 'Compile Warning',
		256 => 'User Error',
		512 => 'User Warning',
		1024 => 'User Notice',
		2048 => 'Strict Notice',
		4096 => 'Recoverable Error',
		8192 => 'Deprecated',
		16384 => 'User Deprecated',
	$message = "";
	$message .= "
"; $message .= ""; $message .= ""; $message .= ""; $message .= ""; $message .= ""; $message .= ""; $message .= "
"; $traces = debug_backtrace(); array_shift($traces); if ( (count($traces) > 1) && ($traces[0]['function'] != 'err_shutdown') ) { // Ignore fatal shutdown traces $message .= ""; foreach ($traces as $offset => $trace) { // Calculate line number if ($offset == 0) { // First in trace $message .= ""; } $message .= "
$errline"; } else // Nth in trace $message .= "
" . (isset($trace['line']) ? $trace['line'] : ' ') . ""; // Calculate arg stack $trace['argstack'] = ''; if (isset($trace['args']) && $trace['args']) { foreach ($trace['args'] as $arg) $trace['argstack'] .= _err_human($arg) . ' , '; if ($trace['argstack']) $trace['argstack'] = substr($trace['argstack'], 0, -3); } // Output context if (isset($trace['object'])) { // Object error $message .= "{$trace['class']}->{$trace['function']}({$trace['argstack']})"; } else // Function error $message .= "{$trace['function']}({$trace['argstack']})"; $message .= "
"; } $message .= "
"; if (ERR_MAIL_TO) { if (!file_exists($p = dirname(__FILE__) . '/' . ERR_PATH_PHPMAILER)) { echo "Cannot find PHP mailer at the relative path '" . ERR_PATH_PHPMAILER ."'. Make sure it is located there to send mails"; } else { require_once($p); $mailobj = new PhpMailer(); if (ERR_MAIL_METHOD == 'SMTP') $mailobj->IsSMTP(); $mailobj->IsHTML(TRUE); $mailobj->CharSet = 'utf-8'; $mailobj->Host = ERR_MAIL_HOST; $mailobj->Sender = ERR_MAIL_SENDER; $mailobj->From = ERR_MAIL_FROM; $mailobj->FromName = ERR_MAIL_FROM_NAME; $mailobj->AddAddress(ERR_MAIL_TO, ERR_MAIL_TO_NAME); $mailobj->Subject = strtr(ERR_MAIL_SUBJECT, array( '[TYPE]' => $errtable[$errno], '[FILE]' => $errfile, '[BASENAME]' => basename($errfile), '[LINE]' => $errline, '[STRING]' => $errstr, )); $extras = preg_split('/\s*,\s*/', ERR_MAIL_FOOTERS); if (in_array('GET', $extras)) $message .= _err_dump_array($_GET, 'Get'); if (in_array('POST', $extras)) $message .= _err_dump_array($_POST, 'Post'); if (in_array('SESSION', $extras)) $message .= _err_dump_array(isset($_SESSION) ? $_SESSION : array(), 'Session'); if (in_array('SERVER', $extras)) $message .= _err_dump_array($_SERVER, 'Server'); if (in_array('GLOBALS', $extras)) $message .= _err_dump_array($_GLOBALS, 'Globals'); $mailobj->Body = $message; $status = $mailobj->Send(); } } echo $message; return TRUE; } // Catch fatal errors function err_shutdown() { $err = error_get_last(); if (in_array($err['type'], array(E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR))) err($err['type'], $err['message'], $err['file'], $err['line'], 'Fatal error'); } function _err_human($what) { if (is_object($what)) { return get_class($what); } elseif (is_array($what)) { return "Array[" . count($what) . "]"; } else return $what; } function _err_dump_array($array, $title) { if ($array) { $out = ''; $out .= ""; foreach (array_keys($array) as $key) $out .= ""; $out .= '
Dump of $title array
$key" . _err_human($array[$key]) . "
'; } else { $out = "
$title is empty
"; } return $out; } set_error_handler('err', E_ALL); register_shutdown_function('err_shutdown'); ?>

Installation of the component is similar to any CI helper: drop the file into the application/system/helpers directory and create the associated entry in the application/system/config/autoload.php file like so:

$autoload['helper'] = array('err');

Then open the above and change the constants at the top of the file to specify where the error messages are sent.

In order to send mail the above component needs the truly excellent PHPMailer package which can be stashed in the same helpers directory. If you do decide to move it somewhere else change the corresponding constant that specifies the location of the library. A small note of warning though – the path to the PHP mailer libraries must be relative to the current file NOT the current working directory. This is due to how PHP handles fatal errors which for some reason sets the working directory to ‘/’.

Should there be any interest I may extend the above with other useful features such as RSS, SMS (text messaging) or other non-SMTP methods of emailing.

Categories: PHP Tags: , ,

Pretty URLS in CodeIgniter

January 12th, 2009 No comments

CodeIgniter has to be my favorite framework for PHP. The way it keeps out of your way while working to an MVC standard is something deserving of the highest praise.

For reasons passing understanding though the programmers of this excellent system have desided not to provide pretty URL’s out of the box. Getting infomation on this is a little tricky so here is my take on the situation.

Simply dump the following into a file called ‘.htaccess’ (Note the starting Dot) in the root path (thats the one at the very start of your path tree that should contain the ‘system’ folder).

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*)$		- [L]

RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

As with most mod_rewrite hacks you will need that enabled on an apache server. Its very rare to find a hosting company that doesn’t use this setup so you should be fine.

You will also need to change the following variable to a blank value in the system/application/config/config.php file:

$config['index_page'] = '';

And you’re done. From now on your Urls are addressed in the form: http://SITE/CONTROLLER/METHOD/VALUE1/VALUE2 (e.g.

Categories: HowTo's, PHP Tags: , , ,

Missing PHP Functions: getopts()

December 23rd, 2008 11 comments

This function is intended as a complete replacement for the horribly crippled getopt() native PHP function and provide extended functionality.

The use of this library means lots of great command-line-fu becomes readily available without any unnecessary validation tediousness messing up the first half of your script.

To use simply add the (ahem) hash-bang to the top of your PHP script and make the script executable.

An example of a correct setup would be:

#!/usr/bin/php -qC
 array('switch' => 'a','type' => GETOPT_SWITCH),
	'b' => array('switch' => array('b','letterb'),'type' => GETOPT_SWITCH),
	'c' => array('switch' => 'c', 'type' => GETOPT_VAL, 'default' => 'defaultval'),
	'd' => array('switch' => 'd', 'type' => GETOPT_KEYVAL),
	'e' => array('switch' => 'e', 'type' => GETOPT_ACCUMULATE),
	'f' => array('switch' => 'f'),

In the above the script can now be run as:

./getopts_example.php -a -b

With the incoming options (in this case the switches ‘a’ and ‘b’) being set in the $opts variable.

Full documentation as well as extensive examples are included in the source which can be found below.

#!/usr/bin/php -qC
 array('switch' => 'a','type' => GETOPT_SWITCH),
	'b' => array('switch' => array('b','letterb'),'type' => GETOPT_SWITCH),
	'c' => array('switch' => 'c', 'type' => GETOPT_VAL, 'default' => 'defaultval'),
	'd' => array('switch' => 'd', 'type' => GETOPT_KEYVAL),
	'e' => array('switch' => 'e', 'type' => GETOPT_ACCUMULATE),
	'f' => array('switch' => 'f'),

When used with the commandline:
>./PROGRAM.php -ab -c 15 -d key=val -e 1 --letterb -d key2=val2 -eeeeeee 2 3

Gives the $opt variable the following structure:
$opt = Array (
	[cmdline] => Array (
		[0] => 1
		[1] => 2
		[2] => 3
	[a] => 1
	[b] => 1
	[c] => 15
	[d] => Array (
		[key] => val
		[key2] => val2
	[e] => 8
	[f] => 0

Of course the above is a complex example showing off most of getopts functions all in one.

Types and there meanings

	This is either 0 or 1. No matter how many times it is specified on the command line.
	>PROGRAM -c -c -c -cccc
	$opt['c'] = 1;
	$opt['c'] = 0

	Each time this switch is used its value increases.
	>PROGRAM -vvvv
	$opt['v'] = 4

	This expects a value after its specification.
	>PROGRAM -c 32
	$opt['c'] = 32
	Multiple times override each precursive invokation so:
	>PROGRAM -c 32 -c 10 -c 67
	$opt['c'] = 67

	The same format as GETOPT_VAL only this allows multiple values. All incomming variables are automatically formatted in an array no matter how few items are present.
	>PROGRAM -c 1 -c 2 -c 3
	$opt['c'] = array(1,2,3)
	>PROGRAM -c 1
	$opt['c'] = array(1)
	$opt['c'] = array()

	Allows for key=value specifications.
	>PROGRAM -c key=val -c key2=val2 -c key3=val3 -c key3=val4
	$opt['c'] = array('key1' => 'val2','key2' => 'val2','key3' => array('val3','val4');


define('GETOPT_NOTSWITCH',0); // Internal use only

* @param array $options The getOpts specification. See the documentation for more details
* @param string|array $fromarr Either a command line of switches or the array structure to take options from. If omitted $_SERVER['argv'] is used
* @return array Processed array of return values
function getopts($options,$fromarr = null) {
	if ($fromarr === null)
		$fromarr = $_SERVER['argv'];
	elseif (!is_array($fromarr))
		$fromarr = explode(' ',$fromarr); // Split it into an array if someone passes anything other than an array
	$opts = array('cmdline' => array()); // Output options
	$optionslookup = array(); // Reverse lookup table mapping each possible option to its real $options key
	foreach ($options as $optitem => $props) { // Default all options
		if (!isset($props['type'])) { // User didnt specify type...
				$options[$optitem]['type'] = GETOPT_SWITCH; // Default to switch
				$props['type'] = GETOPT_SWITCH; // And again because we're not using pointers here
		switch ($props['type']) {
				case GETOPT_VAL:
					if (isset($props['default'])) {
						$opts[$optitem] = $props['default'];
					} // else fallthough...
					$opts[$optitem] = 0;
					$opts[$optitem] = array();
		if (is_array($props['switch'])) { // Create the $optionslookup var from an array of aliases
				foreach ($props['switch'] as $switchalias)
					$optionslookup[$switchalias] = $optitem;
		} else { // Create the $optionslookup ref as a simple pointer to the hash
			$optionslookup[$props['switch']] = $optitem;
	$inswitch = GETOPT_NOTSWITCH;
	for ($i = 1; $i < count($fromarr); $i++) {
		switch ($inswitch) {
			case GETOPT_VAL:
				if (substr($fromarr[$i],0,1) == '-') // Throw error if the user tries to simply set another switch while the last one is still 'open'
					die("The option '{$fromarr[$i]}' needs a value.\n");
				$inswitch = GETOPT_NOTSWITCH; // Reset the reader to carry on reading normal stuff
			case GETOPT_KEYVAL: // Yes, the awkward one.
				if (substr($fromarr[$i],0,1) == '-') // Throw error if the user tries to simply set another switch while the last one is still 'open'
					die("The option '{$fromarr[$i]}' needs a value.\n");
				$fromarr[$i] = strtr($fromarr[$i],':','='); // Replace all ':' with '=' (keeping things simple and fast.
				if (strpos($fromarr[$i],'=') === false)
					die("The option '$inswitch_userkey' needs a key-value pair. E.g. '-$inswitch_userkey option=value'");
				$inswitch = GETOPT_NOTSWITCH; // Reset the reader to carry on reading normal stuff
			case GETOPT_NOTSWITCH: // General invokation of no previously complex cmdline options (i.e. i have no idea what to expect next)
				if (substr($fromarr[$i],0,1) == '-') {
					// Probably the start of a switch
					if ((strlen($fromarr[$i]) == 2) || (substr($fromarr[$i],0,2) == '--')) { // Single switch OR long opt (might be a weird thing like VAL, MULTIVAL etc.)
							$userkey = ltrim($fromarr[$i],'-');
							if (!isset($optionslookup[$userkey]))
									die("Unknown option '-$userkey'\n");
								$hashkey = $optionslookup[$userkey]; // Replace with the REAL key
							if (($options[$hashkey]['type'] == GETOPT_SWITCH) || ($options[$hashkey]['type'] == GETOPT_ACCUMULATE)) {
								GETOPT_setval($opts,$options,$hashkey,1); // Simple enough - Single option specified in switch that needs no params.
							} else { // OK the option needs a value. This is where the fun begins
								$inswitch = $options[$hashkey]['type']; // Set so the next process cycle will pick it up
								$inswitch_key = $hashkey;
								$inswitch_userkey = $userkey;
					} else {
						// Multiple letters. Probably a bundling
						for ($o = 1; $o < strlen($fromarr[$i]); $o++) {
							$hashkey = substr($fromarr[$i],$o,1);
							if (!isset($optionslookup[$hashkey]))
									die("Unknown option '-$hashkey'\n");
							if (($options[$optionslookup[$hashkey]]['type'] != GETOPT_SWITCH) && ($options[$optionslookup[$hashkey]]['type'] != GETOPT_ACCUMULATE))
								die("Option '-$hashkey' requires a value.\n");
				} else {
					$opts['cmdline'][] = $fromarr[$i]; // Just detritus on the cmdline
	return $opts;	

function GETOPT_setval(&$opts,&$options,$key,$value) {
	switch ($options[$key]['type']) {
		case GETOPT_VAL:
			$opts[$key] = $value;
			$opts[$key][] = $value;
			$opts[$key][$value[0]] = $value[1];

If you do use this script, please take a moment to add any comments or suggestions below.

Categories: PHP Tags: ,

Missing PHP Functions: array_totree()

December 13th, 2008 1 comment
array_totree( $array, $seperator = "/" )

Splits a given array into a tree formed hash array.

This is useful when a large array of strings needs splitting into a hierarchical array structure.

For example in incoming array structure

$a = array(

Is returned as:

	"a" => array(
		"a" => array(
			"a" => array()
	"b" => array(
		"b" => array(),
		"c" => array()
	"c" => array(
		"c" => array()
	"c" => array(
		"a" => array(
			"a" => array()

The function:

function array_totree($in, $splitchar = '/') {
        $out = array();
        foreach ($in as $item) {
                $bits = explode($splitchar,$item);
                $outref =& $out;
                foreach ($bits as $bit) {
                        if (!isset($outref[$bit]))
                                $outref[$bit] = array();
                        $outref =& $outref[$bit];
        return $out;
Categories: PHP Tags:

Templating in PHP in 10 seconds flat

December 6th, 2008 No comments

One of the rather messy practices that the PHP documentation actually encourages is the practice of using include or require to correctly layout a web page.

The PHP manual suggests that two pages be created: header and footer, and that these are included at the beginning and end of each document.

Thus for a ‘contact us’ page the contact.php file would look something like:

... The contact pages HTML ...

While this does work, there are easier ways to accomplish the same thing and still maintain compatibility with editors such as Dreamweaver which seems to choke on even a small amount of PHP.

The under-documented auto_prepend_value and auto_append_values get a brief mention in the ini directives documentation but I thought it would be nice to show an example of how these can be used in the wild,

Adding the following to either an existing ‘.htaccess’ (note the starting dot) or downloading the below file will do pretty much the same as the above contact.php file example did only without needing to specify the files in the beginning and ends of each separate file.

php_value auto_prepend_file "header.php"
php_value auto_append_file "footer.php"

And as with all .htaccess directives you can override these on a directory basis. So if you need a different header and footer when inside the ‘invoices’ directory dump another copy of the above into that directory changing it as needed.

And yes this method can be merged with the previous post to work with the URL prettifier.

Categories: HowTo's, PHP Tags: , ,