PHP: URL shortening


.htaccess:

Options +FollowSymlinks
RewriteEngine On
RewriteRule ^([A-Za-z0-9]{4})$ /_go_url_.php?code=$1 [L]


PHP (one file):


include_once "config.php";


@mysql_connect(DB_SERVER,DB_USER,DB_PASS) or die("Unable to connect to database " . DB_NAME);
@mysql_select_db(DB_NAME) or die("Unable to select database " . DB_NAME);
$warning = 0;
$codetogo = 0;
if ($_POST['gourl']){
  $theurl = trim($_POST['URL']);
  if (!preg_match("/^http:\/\/.+|https:\/\/.+|ftp:\/\/.+/",$theurl)){
    $warning = "not a valid URL!";
  }// end if preg_match
  
  if (! $warning){
    //good to go
    $theurl = preg_replace("/\n/","",$theurl);
    // generate 4 digits + letters
    
    for($i=1; $i<=100000; $i++){
      $rs = getrand(4);
      $query = "SELECT code FROM data WHERE code='$rs'";
      $result = mysql_query($query);
      $howmany = mysql_num_rows($result);
      if ($howmany > 0){
        continue;
      } else {
        $thenewid = genid(time().mt_rand(1,999999));
        $query = "INSERT INTO data VALUES('$thenewid','$theurl','$rs')";
        $result = mysql_query($query);
        $codetogo = $rs;
        break;
      }
    }
    
  }
  
  
  
}



click here to add a comment