Create Short Url

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Create Short Url

    Let's start off by making a .htaccess file in your project folder on your server (for me, it will be: C:\wamp\www\cleanURLs\.htaccess). In that file, we will put the follow code:

    Code:
    RewriteEngine On
    RewriteRule (.*) index.php
    RewriteBase /cleanurls/
    RewriteEngine On turns on the rewrite engine for Apache. This will allow us to modify the URL requests once they come in.
    RewriteRule ^([a-zA-Z0-9_\-/]*?)$ index.php tells Apache to pass every request that has alphanumberic characters, underscores, dashes, and slashes through index.php.
    RewriteBase /cleanurls/ tells Apache where to start the rewriting. If you are not using this .htaccess file in a subdirectory, you can remove this line.

    Now, on to the PHP!

    After we have create our index.php file, place the following code in it:
    Code:
    <?php
    $request = $_SERVER['REQUEST_URI']; //This grabs the page requested. It should look something like this: /cleanURLs/user/tim
    $filename = $_SERVER['SCRIPT_NAME']; //This gets the script name. It should look something like this: /cleanurls/index.php
    $request = substr($request, strrpos($filename, '/') + 1); //This removes the string /CleanURLs/ off the beginning of the request. It is not needed.
    while(substr($request, -1) == '/')
      $request = substr($request, 0, -1); //This removes all the trailing slashes off the request. It helps clean up the request.
    $request = explode('/', $request); //We then explode the request by the slash. You can then calculate which page the user is requesting
    foreach($request as $key => $value)
      if($value == '')
        array_splice($request, $key, 1); //Removes any empty items. This is caused by double slashes in the URL
    
    print_r($request); //This will show us all the parameters passed in the URL
    if there are a prob
    Code:
    Delete or comment out the print_r($request); line.
Working...
X