$ip='';
$password='';
$path='/';
$id_min_length=2;
/*
Place this at $httproot/s/index.php
Make $httproot/s/.data/ writable
Optional: $httproot/.htaccess: 
  Rewriteengine on
  Rewriterule ^([a-zA-Z0-9]{1,3}-?)$ /s/?id=$1 [L]
Or: $httproot/s/.htaccess:
  Rewriteengine on
  Rewriterule ^([a-zA-Z0-9]{1,3}-?)$ ?id=$1 [L]
$httproot/s/.data/.htaccess:
  Deny from all
Remove old: find $httproot/s/??? -mtime +30 -delete
GET input:
  id
Return:
  redirect to long url
add a - to the end for preview
GET input:
  url
  id_min_length
Return:
  short url
 
*/
$chars=array_merge(range('a', 'z'), range('A', 'Z'), range(0,9)); // characters
if(isset($_GET['id']) && preg_match('/^[a-zA-Z0-9-]+$/', $_GET['id']) ){ // redirect
  
  if($_GET['id'][strlen($_GET['id'])-1]=='-'){ // preview
    $f='.data/'.substr($_GET['id'], 0, -1);
    if(is_readable($f)){ $get=file_get_contents($f); echo "
"; }
  }else{
    $f='.data/'.$_GET['id'];
    if(is_readable($f)){ $get=file_get_contents($f); header("Location: $get"); echo ""; }
  }
  
}elseif(isset($_GET['url']) && ( !$ip || $_SERVER['REMOTE_ADDR']==$ip ) && $_GET['password']==$password){
  
  if(isset($_GET['id_min_length'])) $id_min_length=$_GET['id_min_length'];
  $str='';
  for($i=0; $i<$id_min_length; $i++){ $str.=$chars[array_rand($chars)]; } // minimum length
  $p=strlen($str)-1;
  for($i=0; $i<50 && file_exists(".data/$str"); $i++){ // append a random character
    $str.=$chars[array_rand($chars)];
    $p++;
    for($j=0; $j<100 && file_exists(".data/$str"); $j++){ // try a new random character
      $str[$p]=$chars[array_rand($chars)];
    }
  }
  
  if(is_writable('.data')){ file_put_contents(".data/$str", $_GET['url']); chmod(".data/$str", 0600); } // save
  else{ die($_GET['url']." url-arza: no write access"); }
  
  echo "http://${_SERVER['HTTP_HOST']}$path$str"; // shortened url
  
}else{
  echo ':P';
}
?>