Archive for the ‘Php development’ Category

Here’s to my new theme

As many of you will know when thinking about making your own portfolio website – it’s difficult to choose a theme and a concept or even make one that reflects you. I had the same problem, trust me.

One thing that really helped me get over this hurdle and get focused was looking at the problem I wanted it to solve, which for me was – creating a place for me to share my online life with others, and creating a place for me to continue to reference for years to come.

I realised that what I actually wanted it to be is a place for me, not a place for others to come and see me, in doing so I hope it will be mildly more interesting to the onlooker as it should now not only be a reflection of my thoughts / trials / tribulations but also reflects me and my personality.

Ultimately I decided that I needed this redesign to enable me to share various different types of media forms on my own blog. Formats such as tweets, blog posts, spotify embeds, pictures and links have all been taken into consideration.

Although i’m not quite done yet, i’m happy with the initial improvements (particularly the whizzy spinny logo, made purely in CSS3, nifty eh?).

For those interested:

The site is still backed by WordPress & HTML5 boilerplate.

I plan on making some more additions to the site in the near future.

PHP Curl URL which has redirects to obtain the final URL

Been doing some toying around lately with various ways of scraping hidden URL’s from a website that deliberately tries to hide them.

I have been using PHP and the CURL library ascertain the final URL after redirects whilst also picking up on javascript redirects etc.

This is what i’ve come up with so far, and it’s working a dream.

function get_final_url( $url, $timeout = 5 ){
    $url = str_replace( "&", "&", urldecode(trim($url)) );
   	$cookie = tempnam ("/tmp", "CURLCOOKIE");
	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
	curl_setopt( $ch, CURLOPT_HEADER, true);
	curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
	curl_setopt( $ch, CURLOPT_ENCODING, "" );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
	curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
	curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
	curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
	$content = curl_exec( $ch );
	$response = curl_getinfo( $ch );
	curl_close ( $ch );
	if ($response['http_code'] == 301 || $response['http_code'] == 302):
	    ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");
	    $headers = get_headers($response['url']);
	    $location = "";
	    foreach( $headers as $value ):
	        if ( substr( strtolower($value), 0, 9 ) == "location:" )
	            return get_final_url( trim( substr( $value, 9, strlen($value) ) ) );
	if (preg_match("/window.location.replace('(.*)')/i", $content, $value) ||
	        preg_match("/window.location="(.*)"/i", $content, $value) ||
	        preg_match("/location.href="(.*)"/i", $content, $value) ):
	    	return get_final_url ( $value[1] );
	    return $response['url'];
// Simply called like so
$my_final_url = get_final_url('',10);

MAMP v2.0+ and Apache Virtual Host Set Up

A colleague of mine was having some trouble setting up virtual host’s with his new installation of MAMP recently. So I decided to sit down and have a little look into it, and here follows a small guide to getting vhosts working locally on your mac using MAMP v2.0 and it’s bundled apache.

I’ve chosen to use “mate” which is the terminal shorthand for textmate, which you can download here Macromates Textmate, but you can swap out my instance’s of this with a more familiar editor like “nano” or “vim”.

Firstly run the following command or open /Applications/MAMP/conf/apache/httpd.conf in your preferred editor.

dave$ mate /Applications/MAMP/conf/apache/httpd.conf

First thing I noticed was that MAMP now quietly includes a bunch of file’s rather than just having it all appended at the bottom of httpd.conf, however all the usual files

Somewhere in amongst all of these files you will find the following:

# Virtual hosts
# Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf

Simply uncomment it like so;

# Virtual hosts
Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf

I used a command from terminal like so:

dave$ mate /Applications/MAMP/conf/apache/httpd.conf

Next we need to set up a record in our /etc/hosts/ file, you will need to call on the power of “sudo” for this. Use the following command:

dave$ sudo mate /private/etc/hosts

You will of course be prompted for your password, which is your system password. Once open you should see something like this:

# Host Database
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##	localhost	broadcasthost
::1             localhost
fe80::1%lo0	localhost

Now add this line to the bottom of this file, replacing “nameserver” with whatever you wish to call yours. testrun

Save and Quit.

Now you need to, create your virtual host in the vhosts file. So remember that line we uncommented in the httpd.conf file? The file that points to is now where we’re heading so.

dave$ mate /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf

Once open you should see something like this:

# Virtual Hosts
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
# Please see the documentation at
# for further details before you try to setup virtual hosts.
# You may use the command line option '-S' to verify your virtual host
# configuration
# Use name-based virtual hosting.
NameVirtualHost *:80
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any  block.
DocumentRoot "/Applications/MAMP/htdocs/playme/http/"
ErrorLog "logs/"
CustomLog "logs/" common
DocumentRoot "/Applications/MAMP/htdocs/playmedeux/http/"
ErrorLog "logs/"
CustomLog "logs/" common

You’ll notice that there are two uncommented dummy servers set up, if you want to reference them at a later date just simply comment them out using the “#” infront of text on every line, or you can simply delete them. If your commenting it should end up like this:

#   ServerAdmin
#   DocumentRoot "/Applications/MAMP/htdocs/playme/http/"
#   ServerName
#   ServerAlias
#   ErrorLog "logs/"
#   CustomLog "logs/" common

Right, now to adding our new one, called testrun, let’s copy the format from above and insert this code into the bottom of our file. Note that at this point you now need to decide where your document route is going to be, in most cases I would just create a folder inside htdocs inside my mamp install something like below:

dave$ mkdir /Applications/MAMP/htdocs/testrun/

Our document root in our VirtualHost setup should now reflect that when you add the following.

<virtualHost *>
ServerName testrun
DocumentRoot /Applications/MAMP/htdocs/testrun/

Notice how i’ve decided to make this available on a specific port but have just opted for any port, normal port numbers for apache are :8888 or :80 so you could specify either one of those if you so wished like so:

VirtualHost *:8888

As opposed to:

VirtualHost *

Onto the final leg, now we just need to reboot apache, so, in terminal you can do:

/Applications/MAMP/bin/apache2/bin/apachectl restart

Or simply if you prefer the mamp interface a stop and start of server’s should suffice.

One last thing, let’s quickly add a index.html file to our Document Root for testing purposes.

mate /Applications/MAMP/htdocs/nameserver/index.html

And enter “Welcome to the testrun vhost – Served by MAMP” to the file. Save and quit.

Finally type http://testrun:8888 into your favourite browser (of course with MAMP started) and you should see your index.html file served up nicely.

Php preg_match simple string examples

Due to ereg being deprecated in php 5.3.0 + I decided since it was at the core of one of the most heavily used functions on a site of mine, to make the move to preg_match this afternoon. More for my own benefit than anyone elses im just blogging it for future reference.

Some simple preg_matchs I wrote this evening to replace some old ereg functionality.

Firstly a simple match whole string of numeric and alphanumeric characters also including: space, (!), (_), (-), (|) and being between length of 1 and 200 characters. Like I said simples icon wink Php preg match simple string examples

if(!preg_match('/^[-A-Za-z0-9_!| ]{1,200}+$/',$data)){
return false;
} else {
return $data;

Heres another: This time only numeric characters are allowed, with a string length of 1-30.

return false;
} else {
return $data;

Also like i said more for my own benefit than anyone elses, but feel free to comment if you’d like more examples.

PHP Weighted Random Choice & Selection Remove / Replacement

For something I have been doing in a php project of late, I needed to weight an array of values and as I go round and select the values remove the value or -1 from the weight depending on how many of the value are left in the weight.

If you have any improvements or suggestions then id very much like to here them icon smile PHP Weighted Random Choice & Selection Remove / Replacement

$starttime = microtime();
$startarray = explode(" ", $starttime);
$starttime = $startarray[1] + $startarray[0];
 * weighted_random()
 * Pick a random item based on weights.
 * @param array $values Array of elements to choose from
 * @param array $weights An array of weights. Weight must be a positive number.
 * @return mixed Selected element.
	function weighted_random($values, $weights){
	    $count = count($values);
	    $i = 0;
	    $n = 0;
	    $num = mt_rand(0, array_sum($weights));
	    while($i < $count){
	        $n += $weights[$i];
	        if($n >= $num){
	    return $i;
	function recalc($val,$values,$weight){
		//two steps to consider here, -1 from the weight and if the weight is <=0 unset both the value and the weight.
			$new_values = array();
			$new_weight = array();
			foreach($values as $k=>$v){
			return array($new_values,$new_weight);
			return array($values,$weight);
	//in the context of what im doing lets get this right.
	$values = array(0=>"164-2",1=>"164-1",2=>"2-2");
	$weights = array(0=>1,1=>2,2=>1);
	//now we wanna select 4 values but edit them as we go round.
	$find = 3;
		$val = weighted_random($values,$weights);
		echo $val.'  |  ';
		echo $values[$val].'<br />';
		list($values,$weights) = recalc($val,$values,$weights);
	echo 'The new weights are ';
	echo '<br />';
	$endtime = microtime();
	$endarray = explode(" ", $endtime);
	$endtime = $endarray[1] + $endarray[0];
	$totaltime = $endtime - $starttime;
	$totaltime = $totaltime;
	echo "This page loaded in $totaltime seconds.";

Do’s and do nots of business websites

Earlier today I decided to have a little think about what makes a business website great and what, well, really doesn’t! The very first thing I thought was it’s, making a wonderful looking website, so wonderful infact that all your clients will immediately be like woah these guys really have talent, I want my site designed by them. Essentially this is a good way of thinking or at least the correct mindset. I’m sure that, I’m not alone in thinking this! However, there’s a little more to a wonderful website than it’s cover. As the sayings go “beauty is only skin deep” & “you cant judge a book by its cover”.

So what really does make a wonderful, purpose serving business website? Good question.

Here are some Do’s and Do Not’s from my own personal experience and view.


  • Do make your new site look really eye catching, but more importantly remember the user experience. Don’t make it so eye catching and out there that the average client or onlooker is immediately put off, and won’t bother to find the information they want. Make sure navigation remains simple, nice menus rather than hidden buttons and links. Remember if you look at alot of the most successful websites used by the biggest base of users out there, most of them won’t have any massively out there or exciting UI. They will all have basic, easy to remember, easy to use UI and thats important to remember! Users are thickle and generally make there mind up about a site in the first minute of being on it.
  • Do make sure you don’t hide important information behind too many pages of link depth, users will not want to siv through to much stuff to get to what they want.
  • Do make sure you don’t forget thats its all very well having a nice new site that utilises jQuery or other javascript language to minimise the amount of pages you have in your website, but remember the consequences of doing so. Less content to be ranked, less pages to be indexed and altogether less chance of search engines picking up your site well (this particuarly applies to small businesses, intending to rely on search engine traffic to drive business).
  • Do make your unique selling points readily available.

Do Not’s

  • Do not Hide important information about who you are behind, to tricky or clever UI.
  • Do not hide information that you want a client to see at all, make sure they are confronted as early as possible with the information.
  • Do not make UI’s to clever, that anyone but the designer will struggle to know what to do.
  • Do not make the entire website based on one page (if you wish to rank well for numerous things in search engines).
  • Do not play any annoying sounds on load of your homepage or any other page, a customer who is confronted with loud sound all of a sudden is likely to first port of call close the browser window, that plus its just plain annoying.
  • Do not bury contact forms and ways to get a quote behind a form asking for an information overload, carefully design it so that you get exactly what you need to a minimum.

Opening Up For Advice

Over the last year I’ve been constantly if not more than constantly trying to ask myself, are we doing things the right way?

There are a million and one different ways to accomplish some of the tasks we undertake on a day to day basis.

Preferences are always going to change and perhaps there is not one best method of practise at all.

Im trying to open myself up here to ask anyone in the context of my company and I, what the next step could be.

We build lots of text based games, driven by simple php and mysql, php = mixture of functions and classes. I generally don’t like the idea of php frameworks for use with game design of this type, as games quickly grow code base hugely and you get the annoyingness of extra overheads in load time. However im very much open to new ideas as to how we could improve code. Maybe a new language, or maybe a different approach.

I wondered really if anyone out there has built a complex game on anything other than there own custom php code and mysql (obviously in the context of text based, browser based games and improving on php).

Also we do alot of client work, nice designs, baskets and checkouts all the usual stuff. Does anyone use a particular framework for similar things and found its really good? We spend far too much time repetitively coding things like checkouts and baskets for each customer.

Ideally its all about taking things up a notch and what could improve what we do.

I’d also like to know if anyone uses any particularly good checkout bundles or companies, to manage all there payments really easily. Ours is very disjointed atm. With payments for different sources ie mobile, card etc all being taken by different companies.

PHP frameworks CodeIgniter, Zend & Symfony

Lately I have been considering PHP frameworks and using them to speed up development of small projects, whilst also considering the MVC (Model, View, Control) approach. Most people looking for a PHP framework seem to stick with CodeIgniter, Zend or Symfony. Each with there own advantages and disadvantages. Which one is best is all down to personal taste and its very difficult to make an educated selection of the framework thats best for you. Its baffled me infact, that I can’t put my finger on the framework that I think works for me the best.

So I plan to try and develop a small project in each of these frameworks and decide after that which one I think is the best for me.

For more complex sites, I will continue to use my own custom framework as it helps to keep down page load speeds and ease of understanding.

Check back here over the next month or so, to see what I get up too. As I will be posting all about my experiences with the frameworks.

My Personal Transition Of Design And Programming Practices

This week I’ve seen a real transition in my own personal way of thinking towards design and development. Particularly with how it relates to the development of our online games. After just over 2 and a half years of programming full time, I’ve noticed some really key and distinctive transitional periods in my developing lifespan.

When I first started out it was a case of get it done no matter how or what and learn along the way. This particularly involved little planning, especially planning programming techniques around the design. I would hit hurdles and obstacles all the time, but being the pragmatic problem solver that I am, I’d find ways to jump them or ways around them (thank god for google). At this stage I took little to no notice of design as my css and general knowledge of design technique was so poor that I was stuck well within the table age.

Things quickly moved on and before I knew it all the problem solving had left a lasting imprint of php, html, css and ajax in my head. Enough to be competent (at least so I thought) but not enough by far to be the master. Not knowing that at this stage is possibly the biggest downfall I had. A bit like a guy fresh out of college with his honors degree and first job, I set off to change the world and make amazing looking websites. Uh oh, I might hear you say! Uh oh, indeed. Not long after I began to see my designs not really working out as I wanted or not functioning as well as needed and browser compatibility wasn’t great (I partly blame this on the comfortability and lovability of my new mac, making me not want to look at the far more popular windows based browsers. Damn you internet explorer!).

However I buckled up, hung in for the ride and got things working, with less than sexy solutions at times. After this I began to realise the importance of planning and careful structuring of code, so much so that I even started to do it myself icon smile My Personal Transition Of Design And Programming Practices This became especially important with the development of my companies online games. Massive code bases with hundreds of thousands of lines of code and files. Making use of functions, class’s and sub version made a massive difference to how we developed and maintained our code base.

Yet recently something more radical has changed than just the methods that we used to serve up a page to a player or user. I don’t now think about going in all guns blazing to make the ‘best’ looking website in the quickest time possible, as most of the time this isn’t possible. Im more interested in simple but effective design with clever and efficient coding beneath it. Especially so with our online text based mmorpgs, users are more thickle than you think and care less about the fact that it looks good, and more about that it works good. Simple designs tend to be more backwards compatible and also more compatible with the gathering pace market of mobile and netbook gaming. So generally I now tend to think a bit like google I guess, make it work good, make it look okay, but most importantly make sure the whole experience ‘works’ for the user.

So its interesting to see how I’ve gone from struggling to stay afloat, to swimming too hard and finally to staying calmly and nicely afloat.

I wonder if anyone else will have had some interesting personal development stories….