Search code examples
phpurltinyurl

Creating URL Shortner service


This is my first question:

I have created a URL Shortner Service in PHP.It works completely without any problem but there was a problem:

Someone who wants to access his url should type : MyDomain.com/go.php?u=key Here i tried to remove .php extention by configuring apache and worked.Now it is like that: MyDomain.com/go?u=key

but some services such TinyUrl.com works like that: TinyURL.com/key !!!!

How can i get this in php?

thanks a lot.


Solution

  • You basicly use mod_rewrite.

    With mod_rewrite you can say that all requests which are like

    www.example.com/[A-Za-z1-9]
    

    are redirected to:

    www.example.com/shorturl.php?key=$1
    

    While $1 is the extracted variable from the requested URL.

    There is no proper way to do it with pure PHP.

    The rewrite rule could look like this:

    RewriteRule ^([A-Za-z1-9]*)$ shorturl.php?key=$1 [L]
    

    I would exclude files which really exists from the rewriting, use for this RewriteCond.

    This could be done like here:

    # If the request is not for a valid directory
    RewriteCond %{REQUEST_FILENAME} !-d
    # If the request is not for a valid file
    RewriteCond %{REQUEST_FILENAME} !-f
    # If the request is not for a valid link
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^([A-Za-z1-9]*)$ shorturl.php?key=$1 [L]
    

    (Source: anubhava at RewriteCond to skip rule if file or directory exists)