The AL2 Blog

April 7, 2010

Creating SEO-friendly URLs using PHP

If you’ve used WordPress or done much PHP developing you’ll probably be familiar with the concept of SEO-friendly URLs. That is, an informative link such as http://www.al2webdevelopment.com/blog/2010/04/07/creating-seo-friendly-urls-using-php/ which tell you nicely what the link is about, rather than something like blog.com?post=42.

There are plenty of functions out there that will create a friendly URL for you. This post shows you how to utilise one of these functions in a user friendly way.

This tutorial utilises the JQuery library, and uses its AJAX functionality, so you’ll want to make sure you are familiar with these before continuing.

Demo

Try a demo. This scenario assumes you are entering an news article title, but of course you can use it for anything you like. Try putting some punctuation in, and capital letters and you’ll see that these are nicely removed for you.

View demo

How it works

This feature uses a custom PHP function on a blog by asvin to create the URL. Let’s have a look at this function.

function friendlyURL($string){
    	$string = str_ireplace("'", "", $string);
			$string = preg_replace("`\[.*\]`U","",$string);
			$string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i','-',$string);
			$string = htmlentities($string, ENT_COMPAT, 'utf-8');
			$string = preg_replace( "`&([a-z]) (acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo); `i" "\\1", $string );
			$string = preg_replace( array("`[^a-z0-9]`i","`[-]+`") , "-", $string);

			return strtolower(trim($string, '-'));
		}

This is all well and good, but how do we make it user friendly?

The Clever Bit

I decided to display the SEO-friendly URL on the fly, so the user can see it as it is being created. I also used it in a text field as we can assume it is being sent to a database, and it also gives the user the opportunity to edit the URL if required.

It does this by sending an AJAX request on the ‘keyup’ event on the top input box. As each character is entered, an AJAX request is sent, sending the article headline. The friendly URL is returned and entered into the URL text input field.

The Code

The HTML for the form..

The JQuery to make the magic happen…

$('#title').keyup(function(){
		//Create SEO friendly URL on the fly
		$.ajax({
			type: "GET",
			cache: false,
			url: "[php file location]?title=" + $(this).val(),
			success: function (msg){
			$('#seoTitle').val(msg);
			}
		});
	});

The PHP page that the AJAX calls…

	if($_GET['title']){
		$seoURL = friendlyURL($_GET['title']);
		echo $seoURL;
	}

There you go…

Utilising this code, you can now have an on-the-fly SEO-friendly URL generator!

Filed under: Development,Programming,SEO — Tags: , , , — Andy Long @ 8:18 pm

April 5, 2010

Convert MySQL DATE to PHP format

It’s often annoying to some PHP developers that the format of a DATE field in MySQL does not really correspond to anything immediately useful in PHP. Firstly it’s backwards, or at least different to a ‘typical’ date format of ‘DD/MM/YY’ or ‘MM/DD/YY’ (depending on which side of the Atlantic you are on!).

Not only that, but it’s often returned as a string, and has those dashes (‘-’) in . This is not really useful.

I remember spending a lot of time as a student PHP developer trying to work out how to convert from one to the other.

So here’s how you do it…

You have a string with dashes, and the date format is YYYY-MM-DD. All you need to do is use the in-built PHP split function to create an array with the fields we will need.

Let’s assume we are working with the date of September 13th, 2010. MySQL’s DATE datatype will store this as ’2010-09-13′. Let’s get PHP to handle this and make it useable.

    $date = '2010-09-13';
    $dates = split('-', $date);

So now we have an array ($dates) which contains the individual date fields as array items. The split function splits the string using the first parameter as a separator and the second parameter as the string to split. So this divides the $date string into 3 array items – the year, month and day values. For ease of use we can assign them to more verbose variable names.

  $year = $dates[0];
  $month = $dates[1];
  $day = $dates[2];

Now we are getting somewhere, and have the values that we need. Here, you can transform this into a Unix timestamp (which is what I use for most of my date and time handling. I’d recommend steering clear of DATE, DATETIME and TIMESTAMP datatypes unless you have a specific reason to use them – and that doesn’t happen very often). You can do with it what you will, but for the purpose of this demo will will make a Unix timestamp.

    $timeStamp = mktime(0,0,0, $month, $day, $year);

PHP’s mktime function creates the Unix timestamp on the parameters you give it. The first three parameters are for hour, minute, and seconds. So this creates a timestamp for midnight (the beginning of the day) on 13th September 2010. You can change these parameters statically or dynamically to suit your needs.

This will allow you much more freedom in performing date calculations in PHP now that you have converted it from the MySQL format.

It would also be recommended to wrap all of this up into a function. Here is the full code below in a function, taking the MySQL date as a single parameter and returning a Unix timestamp.

function mysqlDateConvert($mysqlDate){
  //Split the incoming date
  $dates = split('-', $mysqlDate);

  //Assign to variables from array
  $year = $dates[0];
  $month = $dates[1];
  $day = $dates[2];

  //Create the timestamp
  $timeStamp = mktime(0,0,0, $month, $day, $year);

  //Return the timestamp
  return $timeStamp;
}

You can now use this function to easily convert your MySQL dates into an easily useable PHP format!

Filed under: Development,Freelancing,Programming — Tags: , , — Andy Long @ 9:33 pm

April 2, 2010

Use PHP long tags

When updating legacy sites, I have sometimes discovered the use of short PHP tags (<?), which has on occasions caused sites to fail when server or php.ini setting have been upgraded for security.

A server will never ignore the full long tag (<?php), so make sure you use these for your web apps to retain their longevity.

Filed under: Development,Freelancing,Programming — Tags: — Andy Long @ 9:13 am

March 11, 2010

Doink! Website Launched

AL2 are pleased to announce the launch of a new e-commerce website, for up and coming boardwear brand Doink!

This is a full e-commerce solution, allowing Doink! to open up their product range to the global surfing and skating community. The site is built upon the open-source Magento framework, giving them an enterprise quality store site at a fraction of the cost.

The store is fully managed by by Doink! using the site’s adminstrative section. They have full control over all their product range and endless options, including;

  • Price Management
  • Promotions
  • Customer Newsletters
  • Payment Options
  • Product and Category Management
  • Retail / Wholesale Options
  • Order / Shipping / Invoice Control
  • Delivery Options

Al2 worked closely with us throughout the whole webstore building process. The good communication and level of service received took a lot of pressure off us. As a new business, we were able to concentrate on the stock, marketing and admin whilst letting Andy and his team work on the website. I would be happy to recommend AL2 to anyone considering starting an online business.

P.J Lawlor, Sales Director, Doink! Boardsport Apparel.

Filed under: Development,E-Commerce,Freelancing — Tags: — Andy Long @ 8:39 am

March 2, 2010

MySQL – CURRENT_TIMESTAMP on update

It’s not always immediately clear how to get a MySQL table to automatically populate a field with the timestamp of when the field was created or updated.

It’s actually really simple.

Just create a field of type DATETIME and make sure it is NOT NULL. This field will then automatically timestamp for you.

CREATE TABLE example (
id int(255) NOT NULL,
updated DATETIME NOT NULL);
Filed under: Development,Freelancing,Programming — Tags: , — Andy Long @ 9:29 pm
« Newer PostsOlder Posts »

Powered by WordPress