How to use Friendly URLs to create download link

0

Hello, I have the following database:

ID | Chave | Nome | Tamanho
===========================
1  | q3T49 | Arq1 | 20 MB
2  | 56Q4u | Arq2 | 35 MB
3  | 7fa4b | Arq3 | 89 MB
4  | 13dqa | Arq4 | 49 MB

And the files are stored in ./arquivos , but each with its key, for example, the file Arq3 is in ./arquivos/7fa4b/Arq3 .

I would like to make a friendly url where by entering the site.com/download/chave link would directly download, for example, when you enter the site.com/download/56Q4u link it would automatically download Arq2 .

For now my .htaccess is just the basics to get the .php out of the end.

.htaccess :

RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1
    
asked by anonymous 13.03.2017 / 00:17

1 answer

1

Something very simple, to have a minimal notion of what you really should do, is this:

<?php
// index.php

// apresentar os respectivos links
print "<a href=\"download/{$item['chave']}\" target=\"_blank\">{$item['nome']}</a>";
print "<a href=\"download/{$item['chave']}\" target=\"_blank\">{$item['nome']}</a>";

// verificar se o link foi clicado
$a = isset($_GET['a']) ? $_GET['a'] : null; // a=download
$f = isset($_GET['f']) ? $_GET['f'] : null; // f=chave_no_banco

if(isset($a) && isset($f)){ 
    /* algo melhor elaborado aqui, 
    para verificar os detalhes da chave e retornar 
    dados correspondentes do banco antes de iniciar a transferencia,
    ou algo semelhante
    */
    print "A transferir: <br/>";
    print "<strong>ficheiro: </strong>{$f}<br>";
    sleep(1);
    include_once 'download.php';
}

For htaccess you could add this:

RewriteRule ^download/([A-Za-z0-9]+)$ index.php?a=download&f=$1

To download the file in question:

<?php
$name= $_GET['f'];
$randNumber = date('d-m-Y');

    header('Content-Description: File Transfer');
    header('Content-Type: application/force-download');
    header("Content-Disposition: attachment; filename=\"" . basename($randNumber.$name) . "\";");
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($name));
    ob_clean();
    flush();
    readfile("_directorio_do_arquivo_no_servidor/".$name);
    exit;
?>

NOTE: Although without something functional, I do not say for now that it is recommended, there are procedures that you must still implement and several modifications to make, so that it is implemented successfully. See also apache documentation.

References

17.03.2017 / 02:24