Help with PHP and directories?

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
AnsonM
Forum Commoner
Posts: 72
Joined: Thu Sep 25, 2003 7:21 am

Help with PHP and directories?

Post 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 :)
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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 :)
deltawing
Forum Commoner
Posts: 46
Joined: Tue Jun 14, 2005 2:55 pm

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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
Post Reply