Tag Archives: php

Calculating memory used by PHP to generate that page

Do you know how much memory those loops are using ?
Why is this page taking so long to load ?
Well with this simple PHP code you can daily benchmark different versions of your script to use the least possible amount of Memory.

< ?php echo "Memory Usage: ". (function_exists('memory_get_usage') ? round(memory_get_usage()/1024/1024, 2) : 'Unknown') .'MB'."\n"; ?>

An example of this can be seen by visiting the Precision Badges New Zealand site, and viewing the page source, right down the bottom.

PHP Dump/Debug script.

Ever use PHP’s var_dump() or print_r() to debug what is going wrong with that $data you have ?

Well, this simple script acts as the above functions, yours first parameter is your data, and the second optional parameter is stoping the script or continuing on.

The ‘debug_backtrace()’ function will return which file call’s the dump function so you can easily track where your errors are coming from.


	function dump($data = array(), $finish = TRUE) {

		list($referrer) = debug_backtrace();
		$total = count($data);
		echo '
'; echo ''.$referrer['file'].' @ line: '.$referrer['line'].''; echo '
';
		$l = 0;
		if($data) {
			foreach($data as $line => $value) {
		        echo '
Debug #'.(++$l).' of '.$total.', Line: #'. $line .':
'; print_r($value); } } echo "

";
echo "

";
if($finish == TRUE) die;

}

Use PHP to find your mobile browser

I needed a quick way to include different files based on the if the visitor to a site is on a mobile device or a regular browser/computer.

Every browser has a user agent depending on the operating system, browser and system.

below are some common use agents, they can be found by echoing the server variable HTTP_USER_AGENT

< ?php echo $_SERVER['HTTP_USER_AGENT']; ?>

FireFox

Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7

Safari Mac

Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-en) AppleWebKit/523.10.3 (KHTML, like Gecko) Version/3.0.4 Safari/523.10 

Safari Windows

Mozilla/5.0 (Windows; U; Windows NT 6.0; en) AppleWebKit/522.13.1 (KHTML, like Gecko) Version/3.0.2 Safari/522.13.1 

Nexus One

Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD56C) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17

Apple iPhone

Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3

Apple iPod Touch

Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3A100a Safari/419.3 

Internet Explorer

Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)

PHP mobileAgent() Function

Here is my function, is it simple PHP function, is expects one paramerter, and array or expected user agents, but by leaving it blank, the function will use the default user agents.

Update: I have added more mobile user agents for older Android models, Blackberrry’s and the iPhone simulator. .

< ?php
	function mobileAgent($custom_agents = array()) {

		$agents = array_merge($custom_agents, array(
			'iphone',           // Apple iPhone
			'ipod',             // Apple iPod touch
			'aspen',            // iPhone simulator
			'nexus',            // Nexus One Android
			'dream',            // Pre 1.5 Android
			'android',          // 1.5+ Android
			'cupcake',          // 1.5+ Android
			'blackberry9500',   // Storm
			'blackberry9530',   // Storm
			'opera mini',       // Opera mobile
			'webos',            //  Nokia Browser
			'incognito',        // Other iPhone browser
			'webmate'           // Other iPhone browser
		));
		$user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
		foreach($agents as $agent) if(strpos($user_agent, $agent)) return TRUE;
		return FALSE;

	}
?>

Usage

	< ?php if(mobileAgent()): ?>
	
	
	< ?php else: ?>
	
	< ?php endif; ?>

Use PHP and the GD Library to make CSS Sprites

I came across some neat free Icons a couple of day’s ago. I found 178 free icons by WooThemes.

They suited my needs for some navigation icons I was after, so after a quick download, I have them all. Great.

Now, when I code, I’m all about speed of page loads with our reducing quality of course. So more and more and with that I have been using CSS sprites for images, the Less requests, the faster a page loads. there are hundreds of articles explaining this sort of thing, like only use 1 CSS file, putting your Javascript at the bottom, I use them, I even have written a Mootools extensions for embedding Google Analytic in to my sites, that secretly embed the GA code after the page has loaded so its doesn’t slow down the rest of your site from loading, tracking external links and form submits, but any how that is for another post.

178 PNG icons

After extracting the ZIP, I found 178 separate icon files, and I wanted a gray-scale version of each for a hover state, that would mean up to 356 requests plus all of the rest of the images on that page.
Now of course I’m not going to use every Icon, but you never know !

Using PHP & the GD Library to make my Sprite

I must Credit Sandy for his awesomeness and contribution to this script.

< ?php
		function spriter($dir = '*.png', $dest = 'sprite.png', $spacing = 0) {

			// define icons sizes
			$icon_width = 32;
			$icon_height = 32;

			// start height of my sprite canvas
			$height = 0;

			// select all the icons and read theri height to build our canvas size.
			foreach (glob($dir) as $file) {
				list($w, $h) = getimagesize($file);
				// make sure out icon is a 32px sq icon
				if ($h == $icon_height)
					$height += ($h + $spacing);
			}

			// double our canvas height to allow for a gray-scale versions.
			$height = ($height * 2);

			// create our canvas
			$img = imagecreatetruecolor($icon_width, $height);
			$background = imagecolorallocatealpha($img, 255, 255, 255, 127);
			imagefill($img, 0, 0, $background);
			imagealphablending($img, false);
			imagesavealpha($img, true);

			// start placing our icons from the top down.
			$pos = 0;
			foreach (glob($dir) as $file) {
				$tmp = imagecreatefrompng($file);
				if (imagesy($tmp) == $icon_height) {
					imagecopy($img, $tmp, 0, $pos, 0, 0, $icon_width, $icon_height);
					$pos += ($icon_height + $spacing);
				}
				imagedestroy($tmp);
			}

			// place all of our icons on again, but this time convert them to gray-scale
			foreach (glob($dir) as $file) {
				$tmp = imagecreatefrompng($file);
				if (imagesy($tmp) == $icon_height) {
					imagefilter($tmp, IMG_FILTER_GRAYSCALE);
					imagecopy($img, $tmp, 0, $pos, 0, 0, $icon_width, $icon_height);
					$pos +=  ($icon_height + $spacing);
				}
				imagedestroy($tmp);
			}

			// create our final output image.
			imagepng($img, $dest);
		}

Sample Usage

< ?php
// IMPORTANT:  REMEMBER TO MAKE SURE THE WEBSERVER HAS WRITE ACCESS TO YOUR DESTINATION DIRECTORY.

spriter('icons/*.png', 'icons/sprite.png', 10);

Show our Sprite

icons/sprite.png

Basic REGEX for cleaning and prepping data

Over the last year or so, I have used a PHP Framework Code Igniter, Amongst many of its good features is its built in Form Validation Library.

Every now and then I either write a a small site out of Code Ignite, or help others to write or develop sections of their site, I constantly get MSN/IM messages asking for help which I am happy to help.

More recently I have started compiling a list of the little help functions I have written to generate my own ‘Form Validation’ Class, I hope to post it here soon.

Today though I have been doing a lot of Code Igniter validation, with some extra ‘callbacks’ using regex/preg_match & preg_replace combos,

Note: This is not are Regex tutorial, just some basic common examples.

Basic Examples

Strip non-numeric characters from a string.

< ?php

$string = 'sheldon is not james bond 007';
$numbers = preg_replace('/[^0-9]+/', '', $string);
// returns '007';
?>

Strip all none numeric and alpha characters from a string

$string = 'sheldon, Is james bond (007)';
$numbers = preg_replace('/^([a-z0-9])+$/i' '', $string); // the i means case insensitive.
// returns 'sheldon Is james bond 007';
?>

Create a safe URL string.

want to make url safe permalinks or strings?
lets strip out anything that’ll break our address.

// assume $_POST['name'] = "sheldon's wonderful *product* costs $19.95";
$name = str_replace(' ', '-', trim($_POST['name']));
$url = preg_replace('/^([a-z0-9-_])+$/i', '', $name);

header("Location: http://sheldon.lendrum.co.nz/". $url);
//  http://sheldon.lendrum.co.nz/sheldons-wonderful-product-costs-19.95
?>

preg_replace() & preg_match()

I have used preg_replace() to strip out the unwanted tags, but if you just want to validation against with out altering the users data, you can use preg_match().

Here is an example to make sure a user has only submitted a trough z and 0 trough 9 characters and spaces.

< ?php
// assume $_POST['name'] = "sheldon's wonderful *product* costs $19.95";
if(preg_match('/^([a-z0-9\ ])+$/i',  $_POST['name'])) {
	// valid data ( spaces are allowed. )
	// case insative
	echo('Validation Passed');
} else {
	// this was invalid data
	echo('Please enter a valid string.');
}
?>

In this example, our string would fail.

We allowed spaces in our test, to run the same match with out allowing spaces, re can remove the ‘\ ‘ form the Regex.

Here is an example to make sure a user has only submitted a trough z and 0 trough 0 characters .

< ?php
// assume $_POST['name'] = "sheldon";
if(preg_match('/^([a-z0-9])+$/i',  $_POST['name'])) {
	// valid data ( spaces are  NOT allowed. )
	// case insative
	echo('Validation Passed');
} else {
	// this was invalid data
	echo('Please enter a valid string.');
}
?>

In this example, our post data would pass the validation.

Using Mootools Request.HTML response Javascript using $exec

Javascript frameworks are great, no matter which one you use their all built to do more, quickly.

I use Mootools for most of my JS needs, and something is I often use is the AJAX request functionality.

Today I needed to send not only HTML back, but Javascript.

Here are the steps I needed to follow to not only return my Javascript, but to attach it to my response with the Mootools function ‘$exec’

My HTML

Update

My Mootoold Javascript

	

Our Request Handler PHP script





< ?php

	/* QUERY OUR RECORDS FROM OUR GET DATA */

	$response = mysql_get_data_function($_GET);

	echo($response);

?>

Final Response

After running this ‘update’ script, we will have displayed information based on our GET data in the div ‘container’, removed our update link, shown a success message, and styled everything with out response javascript, all thanks to our nifty Mootools $exec function.

Use PHP to subStr to cut length in whole words

In work, we often output a section of content and don’t always either want the whole content, or want a quick summary;

Below is a quick piece of code that will create a quick clean summary of a full HTML page from our ( or any ) content Management System.
This doesnt actually use PHP’s substr function, but has the same effect.

function summary($content, $length = 20, $finish = '…') {
	// Clean and explode our content, Strip all HTML tags, and special charactors.
	$words = explode(' ', strip_tags(preg_replace('/[^(\x20-\x7F)]*/','', $content)));
	// Get a count of all words, and check we have less/more than our required amount of words.
	$count = count($words);
	$limit = ($count > $length)?$length:$count;
	// if we have more words than we want to show, add our ...
	$end   = ($count > $length)?$finish:'';
	// create output
	for($w = 0;$w< =$limit;$w++) {
		$output .= $words[$w];
		if($w < $limit) $output .= ' ';
	}
	// return end result.
	return $output.$end;
}

Sample Usage:

// our page cntent from our SQL database... example.
$page_content = '

Page title

lorem... ...ipsum home page'; echo summary($page_content, 5);

This will output…

‘Page title lorem lemon…’

This will output full words rather than cutting at a certain amount of letter, and some times ending half way trough a word.