Page 1 of 1

Help with PHP and directories?

Posted: Tue Oct 25, 2005 5:31 am
by AnsonM
Hi all,

Brief explaination of what tinyurl is..
Welcome to TinyURL!™
Are you sick of posting URLs in emails only to have it break when sent causing the recipient to have to cut and paste it back together? Then you've come to the right place. By entering in a URL in the text field below, we will create a tiny URL that will not break in email postings and never expires.


I get the whole shortening process but what I don't get is how you can make PHP do http://tinyurl.com/XXXXXXXX

I know the XXXXXXX is randomly generated and checked to ensure there is no duplicate entries, but how does PHP handle it to make sure the user gets redirected to the correct place? Does it create a directory per site? (Doesnt seem quite as knowledgeable as you would have millions of directories..)

Can someone explain how this is handled without having those millions of directories? lol

Thank you :)

Posted: Tue Oct 25, 2005 5:57 am
by Jenk
It uses a database table, with two fields:

Shorturl - actual url

and has a script similar to:

Code: Select all

<?php
$tinyurl = substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/'));

$result = mysql_query("SELECT redirect_url FROM url_table WHERE tiny_url = '" .mysql_real_escape_string($tinyurl)."'");

$row = mysql_fetch_assoc($result);

header("Location: {$row['redirect_url']}");
Obviously it will be much more secure and have several methods to filter etc. but I'm of the opinion that a small example speaks many more words than a few paragraphs of text, so there you go :)

Posted: Tue Oct 25, 2005 11:56 am
by deltawing
I did something like this with an IIS server, where I wanted to have people browse to directories which didn't exist. I then made the 404 error page do the REQUEST_URI thing (or whatever the ASP equivelant is, I forget), and use that to put up the relevant information. Of course, if there is no entry in the database for XXXXX, you'll have to make sure you return a real error 404.

But anyway, my suggestion would be to use something similar to the code Jenk gave as a 404 page, but make sure the users never know that they're getting a 404 error.

Posted: Tue Oct 25, 2005 3:03 pm
by John Cartwright
or you can use mod rewrite and htaccess to grab it

Code: Select all

RewriteEngine On
RewriteBase /
RewriteRule ^([A-Za-z0-9]+)$ /?pageid=$1 [L]
something along those lines