<?php
// $previous_entry would be pulled from a database or something in a real-life situation.
$previous_entry = "afs";
// Generates the next string in alphabetical order (in this case, "aft" as "t" follows "s").
$new_entry = $previous_entry++;
// Prints the new string to the browser ("aft").
echo $new_entry;
?>
It could be done as simple as that. You could use integers or strings (letters or numbers). To test the behaviour of this as more entries are created, run this script…
<?php
$previous_entry = "afs";
// Prints the 10000 strings which would follow "afs".
while ($count < 10000) {
echo $previous_entry."<br />";
$previous_entry++;
$count++;
}
?>
You should now get an idea of the simplicity. Tinyurl would be one of the easiest applications to program. Just retrieve the most recent entry to the url database and plus it by 1 and then store that with the new URL. Rinse and repeat.
<?php
function encode36($x){
return base_convert($x, 10, 36);
}
function decode36($x){
return base_convert($x, 36, 10);
}
if(isset($_GET)){
list($shortcode, $junk) = each($_GET);
$id=decode36($shortcode);
if(is_numeric($id)){
$sql="select url from short where id=$id";
$rs=mysql_query($sql);
if(mysql_num_rows($rs)>0){
$r=mysql_fetch_assoc($rs);
header("Location: ".((substr($r['url'],0,7)=="http://" or substr($r['url'],0,8)=="https://")?"":"http://").$r['url']);
exit;
}
}
}
header("Location: http://www.base-website.com");
exit;
?>
short.php makes the links
<?php
function encode36($x){
return base_convert($x, 10, 36);
}
echo "
<form action='short.php' method='post'>
Your URL to Shorten: <input type=text name='url' value='http://' size=40> <input type=submit value='Submit'>
</form><br>";
if(isset($_POST['url']) and strlen($_POST['url'])>0 and (!stripos($_POST['url'],"url.php") or stripos($_POST['url'],"url.php")===false)){
$url=mysql_escape_string($_POST['url']);
$sql="select id from short where url='$url'";
$rs=mysql_query($sql);
if(mysql_num_rows($rs)>0){
$r=mysql_fetch_assoc($rs);
echo "Here's your short url: <b>http://www.base-website.com/url.php?".encode36($r['id'])."</b><br><small>(Shortened from: ".$url.")</small>";
}else{
$sql="insert into short (url) values ('$url')";
mysql_query($sql);
echo "Here's your short url: <b>http://www.base-website.com/url.php?".encode36(mysql_insert_id())."</b><br><small>(Shortened from: ".$url.")</small>";
}
}elseif(stripos($_POST['url'],"url.php") or stripos($_POST['url'],"url.php")>=0){
echo "You can't use a url that contains \\"url.php\\"";
}
?>
the table in the database:
CREATE TABLE short ( id int(11) NOT NULL auto_increment, url text NOT NULL,
PRIMARY KEY (id)
);