By Jazerix

2013-05-05 20:43:04 8 Comments

I have a URL that looks like:

How would I go about converting that URL to:


I think WordPress does the same.

How do I go about making friendly URLs in PHP?


@Niels Keurentjes 2013-05-05 20:53:24

You can essentially do this 2 ways:

The .htaccess route with mod_rewrite

Add a file called .htaccess in your root folder, and add something like this:

RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=$1

This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want, without the end user seeing it. Easy, but inflexible, so if you need more power:

The PHP route

Put the following in your .htaccess instead: (note the leading slash)

FallbackResource /index.php

This will tell it to run your index.php for all files it cannot normally find in your site. In there you can then for example:

$path = ltrim($_SERVER['REQUEST_URI'], '/');    // Trim leading slash(es)
$elements = explode('/', $path);                // Split path on slashes
if(empty($elements[0])) {                       // No path elements means home
} else switch(array_shift($elements))             // Pop off first item and switch
    case 'Some-text-goes-here':
        ShowPicture($elements); // passes rest of parameters to internal function
    case 'more':
        header('HTTP/1.1 404 Not Found');

This is how big sites and CMS-systems do it, because it allows far more flexibility in parsing URLs, config and database dependent URLs etc. For sporadic usage the hardcoded rewrite rules in .htaccess will do fine though.

@Mike 2013-05-05 21:09:27

Instead of hard-coding it, you could just use regex to ignore the string completely. In other words, the only thing that counts is the ID part. Going to picture.php/invalid-text/51 would also redirect to the same location. You could also add a check to see if the string is correct and if not, redirect again to the correct location. That's how I did it on one of my sites using htaccess.

@Niels Keurentjes 2013-05-05 21:12:18

Convenient for smaller sites, but not really practical if you have to parse /blog/25 as well as /picture/51 and /download/684. Also, it's considered very bad practice (and gets you Google PR penalized!) if not all randomly generated URLs properly return 404.

@Jack James 2014-01-31 14:46:23

on my system at least, that was FallbackResource /index.php (note the leading slash)

@Niels Keurentjes 2014-06-15 10:56:53

@olli: the bad practice comment specifically refers to "not returning 404's for non-existent URLs", which is solved by the solution in the answer itself. As for the first question - FallbackResource only kicks in for files that do not actually exists on the filesystem, hence the fallback. So if you have a file /static/styles.css and refer to it as http://mydomain.tld/static/styles.css the code is never executed, making it work as expected and intended transparently.

@Koen. 2015-01-13 22:54:03

I did not know about FallbackResource, but then again, I moved from Apache to Nginx years ago.

@Ajoy 2015-07-14 04:27:38

@fireinspace 2016-02-08 22:00:26

you should use if($elements[0] === NULL) instead, as $elements will still return a count of one, even if it's empty.

@jasinth premkumar 2018-02-08 17:54:56

what is the + sign and $denotes in here /([0-9]+)$ if i have to do this in index page should i replace page name with index?

@Abhishek Gurjar 2017-04-27 06:44:23

Although already answered, and author's intent is to create a front controller type app but I am posting literal rule for problem asked. if someone having the problem for same.

RewriteEngine On
RewriteRule ^([^/]+)/([^/]+)/([\d]+)$ $1?id=$3 [L]

Above should work for url picture.php/Some-text-goes-here/51. without using a index.php as a redirect app.

@Danijel 2013-05-06 14:25:46

If you only want to change the route for picture.php then adding rewrite rule in .htaccess will serve your needs, but, if you want the URL rewriting as in Wordpress then PHP is the way. Here is simple example to begin with.

Folder structure

There are two files that are needed in the root folder, .htaccess and index.php, and it would be good to place the rest of the .php files in separate folder, like inc/.



RewriteEngine On
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

This file has four directives:

  1. RewriteEngine - enable the rewriting engine
  2. RewriteRule - deny access to all files in inc/ folder, redirect any call to that folder to index.php
  3. RewriteCond - allow direct access to all other files ( like images, css or scripts )
  4. RewriteRule - redirect anything else to index.php


Because everything is now redirected to index.php, there will be determined if the url is correct, all parameters are present, and if the type of parameters are correct.

To test the url we need to have a set of rules, and the best tool for that is a regular expression. By using regular expressions we will kill two flies with one blow. Url, to pass this test must have all the required parameters that are tested on allowed characters. Here are some examples of rules.

$rules = array( 
    'picture'   => "/picture/(?'text'[^/]+)/(?'id'\d+)",    // '/picture/some-text/51'
    'album'     => "/album/(?'album'[\w\-]+)",              // '/album/album-slug'
    'category'  => "/category/(?'category'[\w\-]+)",        // '/category/category-slug'
    'page'      => "/page/(?'page'about|contact)",          // '/page/about', '/page/contact'
    'post'      => "/(?'post'[\w\-]+)",                     // '/post-slug'
    'home'      => "/"                                      // '/'

Next is to prepare the request uri.

$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );

Now that we have the request uri, the final step is to test uri on regular expression rules.

foreach ( $rules as $action => $rule ) {
    if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
        /* now you know the action and parameters so you can 
         * include appropriate template file ( or proceed in some other way )

Successful match will, since we use named subpatterns in regex, fill the $params array almost the same as PHP fills the $_GET array. However, when using a dynamic url, $_GET array is populated without any checks of the parameters.


        [0] => /picture/some text/51
        [text] => some text
        [1] => some text
        [id] => 51
        [2] => 51


        [text] => some text
        [id] => 51

These few lines of code and a basic knowing of regular expressions is enough to start building a solid routing system.

Complete source

define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/inc/' );

$rules = array( 
    'picture'   => "/picture/(?'text'[^/]+)/(?'id'\d+)",    // '/picture/some-text/51'
    'album'     => "/album/(?'album'[\w\-]+)",              // '/album/album-slug'
    'category'  => "/category/(?'category'[\w\-]+)",        // '/category/category-slug'
    'page'      => "/page/(?'page'about|contact)",          // '/page/about', '/page/contact'
    'post'      => "/(?'post'[\w\-]+)",                     // '/post-slug'
    'home'      => "/"                                      // '/'

$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );

foreach ( $rules as $action => $rule ) {
    if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
        /* now you know the action and parameters so you can 
         * include appropriate template file ( or proceed in some other way )
        include( INCLUDE_DIR . $action . '.php' );

        // exit to avoid the 404 message 

// nothing is found so handle the 404 error
include( INCLUDE_DIR . '404.php' );

@andrebruton 2014-06-20 06:52:42

How do you read the parameters? It does not work with $post_id = htmlentities($_GET['post']);

@4 Leave Cover 2017-08-28 17:21:06

@Danijel Can I have a complete source code? I tried the code above but only text was output, CSS no effect. Thank you.

@Luca Rocchi 2013-05-05 21:01:45

this is an .htaccess file that forward almost all to index.php

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !-l
RewriteCond %{REQUEST_FILENAME} !\.(ico|css|png|jpg|gif|js)$ [NC]
# otherwise forward it to index.php
RewriteRule . index.php

then is up to you parse $_SERVER["REQUEST_URI"] and route to picture.php or whatever

@Niels Keurentjes 2013-05-05 21:03:58

Apache introduced the FallbackResource directive a few major versions ago, which is now the preferred way to implement this behaviour at a lower performance cost since it doesn't need to launch the entire rewriting engine. Documentation here. Your rules are also flawed because you do not reference directories (!-d) and all the extension filters are obsolete - the -f should already catch them.

@rauchmelder 2013-05-05 20:47:09

PHP is not what you are looking for, check out mod_rewrite

@Jazerix 2013-05-05 20:50:35

will it affect all urls?

@nietonfir 2013-05-05 20:51:33

@Jazerix This depends on the rules you define.

Related Questions

Sponsored Content

20 Answered Questions

[SOLVED] Get the current URL with JavaScript?

  • 2009-06-23 19:26:45
  • dougoftheabaci
  • 2603427 View
  • 2752 Score
  • 20 Answer
  • Tags:   javascript url

15 Answered Questions

[SOLVED] How to change the URI (URL) for a remote Git repository?

  • 2010-03-12 12:48:47
  • e-satis
  • 1274263 View
  • 3227 Score
  • 15 Answer
  • Tags:   git url git-remote

7 Answered Questions

[SOLVED] How does PHP 'foreach' actually work?

18 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

30 Answered Questions

[SOLVED] Convert HTML + CSS to PDF with PHP?

14 Answered Questions

[SOLVED] Encode URL in JavaScript?

16 Answered Questions

[SOLVED] What is the maximum length of a URL in different browsers?

  • 2009-01-06 16:14:30
  • Sander Versluys
  • 1124945 View
  • 4492 Score
  • 16 Answer
  • Tags:   http url browser

28 Answered Questions

[SOLVED] Get the full URL in PHP

  • 2011-07-20 21:29:51
  • DiegoP.
  • 2555631 View
  • 978 Score
  • 28 Answer
  • Tags:   php url

18 Answered Questions

[SOLVED] How do I modify the URL without reloading the page?

31 Answered Questions

[SOLVED] What is the difference between a URI, a URL and a URN?

  • 2008-10-06 21:26:58
  • Sean McMains
  • 1069862 View
  • 4104 Score
  • 31 Answer
  • Tags:   http url uri urn rfc3986

Sponsored Content