PHP Fatal error: Out of memory – Prevention better than Cure

While running a PHP script you may encounter the dreaded “Fatal error: Out of memory” message. It is usually be accompanied with a few long numbers which represent the number of bytes the script tried to allocate.

The obvious fix would be to increase the memory limit in the php.ini, apache config, .htaccess or at the top of the script itself:

ini_set('memory_limit', '64M');

Increasing the amount of memory will possibly make the error disappear, but for how long? Really all you are doing is suppressing the problem, which will more than likely rear it’s ugly head again in the future.

The best course of action is to get to the real root cause of the problem. Why is the script using so much memory? Can the code be refactored to make it more efficient?

In order to diagnose why, you need to identify where. Some strategically placed debug code is required. Using memory_get_usage(), a built in PHP function, will return the number of bytes the script is using at that point.

echo memory_get_usage();

// Make it more human-readable. Convert Bytes to MB.
echo intval((memory_get_usage() / 1024) / 1024) . "MB\n";

It can be a little tedious, but working line by line or in areas you think could be symptomatic will quickly highlight where you should concentrate your optimisation efforts.

A common cause is a very large result set from a MySQL query. The returned data is read into memory and stored until such time PHP decides it’s no longer required. Do you really need to select all fields, or all rows?

SELECT * FROM `tablename`

SELECT `id`,`surname`,`age` FROM `tablename`

If you only require 5 of the 10 fields in a table, you consume approximately 50% less memory. On small result sets it’s not significant, but when you have 10K plus rows it can really start to add up. Also consider using LIMIT to only retrieve the rows you need.

There is also a minimal saving to be made by returning the results as an array, rather than an object as can be the case with some Active Record libraries.

The Takeaway

Prevention is better than cure. A quick fix will always come back to byte you!
Continue reading

Posted in MySQL, Performance, PHP | Comments Off

Dynamic object property names in Javascript

Have ever needed to create a Javascript object with dynamic property names? You may have found that your dynamic variable name was actually used literally. eval() is your friend…

// Initialise an object.
var myObj = new Object();

var testValue = 'Jim Lam'; 

// Assign your dynamic property name. e.g. via PHP.
var dynamicPropertyName = 'changeable'; 

// WRONG. Creates a property called 'dynamicPropertyName'.
myObj.dynamicPropertyName = testValue;

// RIGHT. Creates a property called 'changeable'.
eval("myObj." + dynamicPropertyName + " = '" + testValue + "' ");

// Check.
alert(myObj.changeable); // Jim Lam

Continue reading

Posted in Javascript | Comments Off

Format price with 2 decimal places in PHP

sprintf("%01.2f", $price );

Example usage:

sprintf("%01.2f", 10 ); // 10.00
sprintf("%01.2f", 10.5 ); // 10.50

Continue reading

Posted in PHP | Comments Off

Steve Jobs 1955-2011 

Steve Jobs

Posted in Apple Mac | Comments Off

Become the fastest programmer in the world

This post was influenced by the film Limitless.

“An action-thriller about a writer who takes an experimental drug that allows him to use 100 percent of his mind. As one man evolves into the perfect version of himself, forces more corrupt than he can imagine mark him for assassination. Out-of-work writer Eddie Morra’s (Bradley Cooper) rejection by girlfriend Lindy (Abbie Cornish) confirms his belief that he has zero future. That all vanishes the day an old friend introduces Eddie to NZT, a designer pharmaceutical that makes him laser focused and more confident than any man alive.” –  IMDb

I found the film quite inspirational, and immediately began researching methods to improve my productivity.

Focus is the key.

Anything which has the potential to break your concentration must be removed from your environment. Close Facebook, Twitter, Skype and your Email. If you have your own office close the door. Position your desk in a direction which minimises passing distractions. Clear your physical and virtual desktop.

Performance enhancing drugs.

Caffeine can help stimulate your mind and body. In my case, only a small amount is required otherwise it has the opposite effect, and actually reduces my concentration level.

Fuel the fire.

Keep bottles of water and various snacks at arms length. Being well hydrated will keep you alert, whilst the sugar will satisfy the slightest hunger, without having to resort to getting up for something more substancial. Your doctor won’t be too happy about this, but hey.

Stay in the zone.

Listening to music works for me. Tracks without words ideally. The higher the BPM, the better. Drum & Bass is a great choice. This one is very much about personal preference. There are cases both for and against playing music which is familiar, versus new.

Time of day can play a role. If you are a freelancer or work from home, do so when you feel you are the most proactive. For many developers, it is often the night time. Unless you live above a bar, it should be quieter during the small hours. Clients and colleagues are likely to be in bed, so you won’t be disturbed by emails and phone calls.

Don’t touch the mouse.

Learn all the keyboard shortcuts for the IDE you use.

Engage Auto Pilot.

Try using auto code completion and self closing braces. Keep snippets of often used code handy.

Once you go black…

I switched over to having a black background in my text editor, after years on white. Some editors will allow you to simply invert the syntax colouring. I’ve found that I can look at a darker screen for longer without causing my eyes to fatigue, plus it looks more geeky and matrix-like.

Get a head start.

Consider using a framework. For Javascript, jQuery is obviously the go-to library of choice. For PHP, there are an array to choose from: Zend, Cake, Symphony, Fuel and my personal favourite CodeIgniter. Frameworks provide a great foundation on which to build your application with features like MVC  build in for free.

Summary

It’s all about finding out what works for you. Getting in the zone, and then staying there.
Continue reading

Posted in Performance, PHP, Project Management | 2 Comments

How to get Parent of Parent Post in WordPress

$parent = get_post($post->post_parent);
$grandparent = $parent->post_parent;

Continue reading

Posted in PHP, Wordpress | Comments Off

Timing is everything

The average internet user has a very short attention span and doesn’t like waiting, who does?

A slow loading website will fustrate potential customers. It gives a poor first impression when compared with your rivals.

A misconception may be formed about your business that you are unresponsive and don’t care for user experience.

Imagine if your website loaded twice as fast as your competition. That would certainly help engage users, resulting in higher conversions.

Just like tuning an F1 racing car, there are many aspects which can be analysed and optimised to give greater performance.

Don’t let your competitors steal a lead on you.

Webwings are experts in tuning the performance of websites.
Continue reading

Posted in Performance | Comments Off

Facebook Like – small button, BIG marketing potential

When purchasing a product or deciding on a supplier for a service there is an inherent risk, especially online.

This risk is reduced significantly if it is in the form of a personal recommendation.

No where is the personal recommendation more prevalent than with Facebook’s Like button.

A ‘safety in numbers’ theory can be applied, whereby a large number of like’s is translated into a perceived acceptance or superiority. In many cases this is justified.

Facebook is built around relationships. The power/weight of a ‘like’ is far greater the closer a friend is in your social circle.

The average number of friends a Facebook user has is 150. Use this order of magnitude to your advantage.

If you can get just 1 user to ‘like’ your product or service, a recommendation will be posted to their news feed. Potentially, you have increased your audience by 150!

You Like?
Continue reading

Posted in Online Marketing | Comments Off

Generate array with x years before/after the current year

Wrote this PHP date function which can easily be used to populate a drop down in a form.
e.g. credit card expiry, or date of birth.

function getDateYears( $start = NULL, $before = NULL, $after = NULL, $sort = NULL ) {
	if ( empty( $start ) || ( empty( $before ) && empty( $after ) ) ) {
		return false;
	}
	$years = array( $start );
	if ( $before ) {
		for( $i = 1; $i <= $before; $i++ ) {
			$years[] = $start - $i;
		}
	}
	if ( $after ) {
		for( $i = 1; $i <= $after; $i++ ) {
			$years[] = $start + $i;
		}
	}
	asort( $years );
	if ( $sort ) {
		rsort( $years );
	}
	return $years;
}

Example usage:

// The next 10 years, starting with the current year.
getDateYears( date('Y'), 0, 10 );

// 10 years either side of 1982, and sort in reverse.
getDateYears( 1982, 10, 10, TRUE );

What about months? It would be more efficient to have this as a static array, but where’s the fun in that. You get month number (with leading zeros) as the key, and the value is the full month (December). Perfect for insertion into a date field in MySQL.

function getDateMonths() {
	$months = array();
	for( $i = 1; $i <= 12; $i++  ) {
		$months[str_pad( $i, 2, '0', STR_PAD_LEFT )] = date( 'F', mktime( 0, 0, 0, $i, 1 ) );
	}
	return $months;
}

Continue reading

Posted in PHP | Comments Off

Why use a version control system like Subversion?

Version control, revision control or source control are all umbrella terms for systems that allow you to manage your code and assets.

The two popular systems in the web dev community are CVS (Concurrent Versioning System) and SVN (Subversion).

In the last 6 years I’ve had a great deal of exposure to Subversion. It has become the backbone to the larger projects I manage/develop.

A prime example of this is MailBigFile.com. The site has paying subscribers in over 100 countries around the world, and is deployed across multiple datacenters. It receives over a quarter of a million visits per month, with notable clients such as BBC, Carlsberg, Pepsi, Nikon and AEG Live. It’s a pretty big deal.

With mulitple developers working on the project at any one time, managing the code is vital to a smooth development process.

Subversion has the concept of a trunk and branches… like a tree! The live version of the site is defined as the trunk. You can create branches which are essentially a copy of the trunk.

It is best practise to carry out your development on a dev branch, although you can call them anything.

More to come…

Posted in Project Management | Leave a comment