Invalid command ‘RewriteEngine’, perhaps misspelled or defined by a module not included in the server configuration

I’ve just installed WAMP (Windows Apache MySql PHP) on my computer and with the installation came a bit of trouble when I was configuring my .htaccess file and adding some url rewriting. I received the following error message:

	[Thu Aug 09 11:18:17 2012] [alert] [client 127.0.0.1] C:/wamp/www/XXX/.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

This was because I hadn’t configured apache to allow mod_rewrite. This is done by uncommenting the following line in httpd.conf:

	LoadModule rewrite_module modules/mod_rewrite.so

To fake a PHP enum

Today I was sort of in a need of an enum in PHP. This, of course, doesn’t exist so I had to make the best of what I had. I wanted to both use an enum as a way to organize digits, but also to use the literal form of it.
One way to do it is to define string constants, like this:

<?php 
	define("MY_CONSTANT", 0);
?>

But I didn’t want that, because that can clutter your code up pretty badly. So while googling this issue I saw some interesting solutions which I mixed together. This example isn’t excellent in that it uses swedish letters in the code (oh the horror), but it does actually work and in this particular situation it was just what I needed:

<?php 
	/**
	 *	A class representing various swedish types of jewelry
	 */
	class Items
	{
		const Halsband = 0;
		const Armband = 1;
		const Örhänge = 2;
		const Barnsmycke = 3;
		const Övrigt = 4;
 
		/**
		 *	A function that returns the name of an Items constant 
		 *
		 *	@param 		int 	$const	A constant in the Items class 
		 *	@returns	string			The name of the constant
		 */
		public static function getName($const)
		{
			$itemClass = new ReflectionClass("Items");
			$constants = $itemClass->getConstants();
 
			foreach($constants as $name => $value)
			{
				if($value == $const)
					return $name;
			}
 
			//Nothing was found
			return -1;
		}
	}
?>

This can be used like this:

<?php 
$item = Items::getName(Items::Halsband); //$item will now hold the string 'Halsband'
?>

Intercepting all errors in PHP

Sometimes you get annoying errors in PHP that refer to the server error log. If you do not have access to the log, because your pretentious web hosting company does not allow you to access them, you need to catch any errors before they end up in the error log. Therefore, there is the amazing feature, set_error_handler , that allows you to intercept errors halfway to hell and manage them yourself.

Here is an example of a simple error handling:

<?php 
	function simpleErrorHandler($errno, $errstr, $errfile, $errline)
	{
		if (!(error_reporting() & $errno)) 
		{
			// This error code is not included in error_reporting
			return;
		}
 
		switch ($errno) 
		{
			case E_USER_ERROR:
				echo "<b>User error:</b> [$errno] '$errstr' - Error line $errline in file $errfile\n";
				exit(1);
				break;
 
			case E_USER_WARNING:
				echo "<b>User warning:</b> [$errno] '$errstr'\n";
				break;
 
			case E_USER_NOTICE:
				echo "<b>User notice:</b> [$errno] $errstr\n";
				break;
 
			default:
				echo "<b>Unknown error:</b> [$errno] $errstr\n";
				break;
		}
 
		/* Don't execute PHP internal error handler */
		return true;
	}
 
	$errorHandler = set_error_handler("simpleErrorHandler");
?>

Obtaining the current file name

For some reason I just needed to get the name of the file I was currently in. So, here is a small function I cooked up which returns the name of the file you are in:

<?php 
	/**
	 *	Returns the name of the file of execution
	 *
	 *	@param	bool	$baseFile 	If false, this function will return the name of the file this function resides in, if true, the current file of execution
	 */
	function getCurrentFileName($baseFile = false)
	{
		if($baseFile)
		{
			return basename(__FILE__);
		}
		else
		{
			return basename($_SERVER['SCRIPT_NAME']);
		}
	}
?>

This function takes in a parameter (optional) which, if false, will take in to account whether or not the function will account for imports or not. Sometimes the function being called is not located in the file that’s being executed.

PHP: Weird functions

After having found more than one really odd function in PHP I’ve decided to put some of them up here on maffelu.net which I will probably update every once in a while when I found something strange.
The list will start with a function I found recently which useful, if unnecessary, called nl2br:

 

nl2br

This a completely brilliant and totally pointless function which lets you convert your line breaks (\n) to html breaks (<br />). In the latest version you can also chose between HTML and XHTML breaks.
Brilliant, and worthless when it’s just about one line of code to convert it using the str_replace method, but, there you are:

function replaceLineBreaks($text)
{
	return str_replace("\n", "<br />", $text);
}
 
$text = "My text\n with linebreaks!";
//Either
$text = replaceLineBreaks($text);
//or
$text = nl2br($text);

parse_url

This is a function I’ve often wanted, and as it turns out, I’ve always had. I didn’t know about it though and I like it. The function, and this might come as a surprise, parses url’s. It’s perfect, all you do is toss in a url and get an associative array with all the key value pairs in it:

<?php 
 
	$url = "http://www.maffelu.net?id=5";
	$url_data = parse_url($url);
 
	echo "< pre>";
	print_r($url_data);
	echo "< /pre>";
?>
Array
(
    [scheme] => http
    [host] => www.maffelu.net
    [query] => id=5
)

checkdnsrr

Every now and then you want to check peoples e-mail in a form. This is good when someone can create an account on your site or if you have a comment area. In any case you’ll use a regex and all to test it with. PHP has a method which, aside from the regex control, also lets you check if the DNS used in the e-mail is correct which means that people who just enter a fake e-mail such as asdfwe@asdfwe.com isn’t allowed even if the structure is correct:

<?php
	$fakeMail = "asdfwe@asdfaswewefasdf.com";
 
	$splittedMail = explode("@", $fakeMail);
	$dns = $splittedMail[1];
 
	if(checkdnsrr($dns))
		echo "$fakeMail has a valid DNS!";
	else
		echo "$fakeMail does not have a valid DNS...";
 
//asdfwe@asdfaswewefasdf.com does not have a valid DNS...
?>

natsort

natsort is a very useful sorting function that sorts numbers the way humans sort them (2 is less than 10 and not the other way around). It’s very useful if you have alphanumeric strings to sort:

$alphaNumericNumbers = array("Test 10", "Test 1", "Test 5", "Test 23", "Test 2");

sort($alphaNumericNumbers);

echo "<p>Standard sorting:</p>";
echo "<pre>";
print_r($alphaNumericNumbers);
echo "</pre>";

echo "<p>Natural sorting:</p>";
natsort($alphaNumericNumbers);
echo "<pre>";
print_r($alphaNumericNumbers);
echo "</pre>";

This will show the following result:


Standard sorting:

Array
(
[0] => Test 1
[1] => Test 10
[2] => Test 2
[3] => Test 23
[4] => Test 5
)
Natural sorting:

Array
(
[0] => Test 1
[2] => Test 2
[4] => Test 5
[1] => Test 10
[3] => Test 23
)

Posted in PHP

PHP: Managable exception output

Having exceptions thrown in PHP can be quite irritating. You want to catch them but sometimes you just throw them for debugging purposes to find the source of errors and sadly every once in a while you see pages that output this kind of horrid crap:

 

Fatal error: Uncaught exception ‘Exception’ with message ‘User id is incorrect!’ in test.php:9 Stack trace: #0 test.php(4): formatUser(12) #1 test.php(12): GetUser(12) #2 {main} thrown in test.php on line 9

 

The error above is hard to read, horrible for visitors and often with an enormous stack trace. This doesn’t really make them ideal when it comes to using them.
There is hope though! There is a wonderful function called set_exception_handler which allows you to catch any error that bubbles all the way up to the top without getting caught. It takes a callback as a parameter which lets you define a way in which to handle the error. Here’s a very simple example of how to use this function to at least output the error in a readable way:

 

	set_exception_handler(function($exception)
		{
			?>
<h2>An exception has been thrown!</h2>
<p><b>Line:</b> <?php echo $exception->getLine(); ?></p>
<p><b>File:</b> <?php echo $exception->getFile(); ?></p>
<p><b>Message:</b> <?php echo $exception->getMessage(); ?></p>
<p><b>Stack trace:</b></p>
< pre>
<?php echo $exception->getTraceAsString(); ?>
< /pre>
			<?php
		});

Då kommer det se ut (ungefär) så här:

An exception has been thrown!
Line: 23
File: test.php
Message: User id is incorrect!
Stack trace:
#0 test.php(18): formatUser(12)
#1 test.php(26): GetUser(12)
#2 {main}

Posted in PHP