Development

Simple pretty URL’s with PHP and the htaccess file

An easy method of doing simplified or pretty URLs with PHP and a htaccess file. Using prettified URL’s looks good, clean, helps readability and is a positive for SEO.

Two examples of prettified URL’s vs conventional:

https://domain.com/users/index.php?id=hunter123

vs

https://domain.com/users/hunter123

Or an even more extreme case:

https://domain.com/products/index.php?category=clothing&type=shorts

vs

https://domain.com/products/clothing/shorts

 

Instructions

Doing pretty or simple URL’s isnt hard, all thats required is a .htaccess file or editing your existing one.

.htaccess in the root folder of the domain:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)$ index.php?id=$1 [QSA]

This means anything after the slash “/” in the URL will be a string for $_GET['id'].

index.php file:

<?php
$url_data = explode("/", $_GET['id']);
echo json_encode($url_data);

This will put the string into an array based on the “/” position.

https://domain.com/alpha/bravo/charlie

Will output

["alpha","bravo","charlie"]

Now you can work with the virtual directory depth (/) and have pretty URL’s without having the actual folder structure.

This example being for

https://domain.com/users/hunter123

This URL has the base directory of users and then a pointer to get specific data, in this case it is for the user “hunter123”

if (count($url_data) == 1) {
    $base_dir = $url_data[0];//users
    if ($base_dir == 'users') {
        //Show users homepage
    } else {
        //.....
    }
} else {
    $base_dir = $url_data[0];//users
    $pointer = $url_data[1];//hunter123
    if ($base_dir == 'users') {
        //Get and show hunter123 data
        //.....
    } else {
        //.....
    }
}

As this is only a simple guide there are no checks for if the data exists else redirect back and make sure to be using prepared MySQL statements.

If you want to show the homepage run a conditional check such as:

if (empty($url_data[0])) {
    //Show homepage
} else {

}

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago