2

Im trying to make automatic download page url shortener for my file upload script.

Example of part that inserts data to database:

function RandomString($length) {
    $key = "";
    $keys = array_merge(range(0,9), range('a', 'z'), range('A', 'Z'));

    for($i=0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }
    return $key;
}

try {
    $db = new PDO('mysql:host='. DB_HOST .';dbname=' . DB_DATABASE .';charset=utf8', DB_USER, DB_PASSWORD);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

    $download_code = RandomString(5);
    $query = "INSERT INTO user_uploads(User_Id, Name, File, DownloadCode) VALUES('".$USER_ID."','".$upload_name."','".$upload_file."','".$download_code."'")";
    $link = $db->prepare($query);
    if($link->execute()){
        header("location: upload-success");
        exit();
    }
    $db = null;
}catch(PDOException $e) {
    die($e->getMessage());
}

So, lets say that download code is "KD9UI"

How can I make download page that works like this? http://domain.com/KD9UI

And when visitor goes to that url, page gets data from database by this download code and prints file details to visitor.

Home help would be nice :)

plexcell
  • 1,647
  • 2
  • 15
  • 29
  • You have to use .htaccess to redirect internally a GET request – HamZa Mar 31 '13 at 11:48
  • `$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);`, what in hell made you do that? `PDO::ERRMODE_EXCEPTION` is better. – Madara's Ghost Mar 31 '13 at 11:54
  • Do what @HamZaDzCyberDeV suggested - but you also need to make sure your 'shortened' URLs are unique. Check before you return / assign it. Also check to see if a given page has already been assigned a URL and return it if found. – ethrbunny Mar 31 '13 at 12:25
  • For generating unique short urls, you can use uniqid function of PHP. http://php.net/manual/en/function.uniqid.php It also generates unique id with prefix. And with more_entropy parameter, you can increase the likelihood that the result will be unique. – smitrp Mar 31 '13 at 14:38

1 Answers1

1

Pass id to upload-success page.

Like this:

header('Location: upload-success?download_code='.$download_code);

and redirect domain.com/id to domain.com/download.php?download_code=id

Like this:

RewriteRule ^upload-success$ upload_success.php [L,NC]
/*
other rewrite rules..
this rule must be at last rule
becuse another rules may be exists too and it's domain.com/(...)
*/
RewriteRule ^(.+?)$ download.php?download_code=$1 [L,NC]
Oğuzhan Eroğlu
  • 152
  • 1
  • 10