Search Engine Friendly URLs With PHP

Posted under PHP on November 14, 2008.

In this tutorial I will show you how to make nice looking, search engine friendly URLs in PHP without Mod_Rewrite.

Objective

Make a URL that looks like this:

http://www.yourdomain.com/index.php?page=about&user=Evan&index=2

Look like this:

http://www.yourdomain.com/index.php/about/Evan/2

The Code

Put the following code into a file called index.php and upload it to your server.

<?php

// Get the URL relative to the script
$url = $_SERVER['PATH_INFO'];

// If for some reason $_SERVER["PATH_INFO"] does not work then
// you could use $_SERVER["REQUEST_URI"] or $_SERVER["PHP_SELF"]

// Remove the /index.php/ at the beginning
$url = preg_replace('/^(/)/','',$url);

// Split URL into array
$url = explode('/',$url);

// Display array
print_r($url);

?>

If you visited the URL index.php/about/Evan/2 the above should output something like this:

Array
(
    [0] => about,
    [1] => Evan,
    [2] => 2
)

If you visited the URL index.php/21/five/uno/wow the output would look like this:

Array
(
    [0] => 21,
    [1] => five,
    [2] => uno,
    [3] => wow
)

As you can see this method allows a virtually unlimited amount of "directories" in your URL. The CodeIgniter Framework uses a very similar method for its URLs.

Comment

See what others have to say on this topic, or add your own two cents.