<?php
require("mysql.php"); // to establish a connection to the db
/* configurations options */
$lengthOfTheHash = 5; // the length determine the numbers of chars in the hash created 5 => 12345 for example
$timeToExpire = 1; // in days
$urlOfYourSite = "http://www.djpate.com/portfolio/shortURL";
function createHash($length=5){ // very simple hash function to generate a random string
$valid = 0;
while(!$valid){
for($i=0;$i<$length;$i++){
$possibleValues = "123456789"; // if you want to add letters you will have to change the id to varchar instead of int
// pick a random character from the possible ones
$hash .= substr($possibleValues, mt_rand(0, strlen($possibleValues)-1), 1);
}
$check = mysql_query("select id from urls where id = $hash") or die(mysql_error()); // checks if the hash allready exists in the db , not very likely to happen
if(mysql_num_rows($check)==0){
$valid = 1;
}
}
return $hash;
}
if(isset($_POST['url'])){ // post was posted
//here we want to validate that the url is valid with a regexp
if(ereg("^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$",$_POST['url'])){
$hash = createHash();
mysql_query("insert into urls (id,url,expire) values ($hash,'".addslashes($_POST['url'])."',date_add(now(),interval $timeToExpire day))") or die(mysql_error());
echo "Congrats ! here is your link : <a href=\"$urlOfYourSite/v/$hash\">$urlOfYourSite/v/$hash</a>";
} else {
echo "Invalid url !";
}
} else {
// no post data so we display the form
?>
<form method="post">
URL : <input type=text name=url>
<input type=submit value=go>
</form>
<?php
}
?>