How to use Friendly Urls to create download link

Asked

Viewed 211 times

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 one with its key, for example, the name file Arq3 is in ./arquivos/7fa4b/Arq3.

I would like to make a URL friendly on that when entering the link site.com/download/chave would download directly, for example, when entering the link site.com/download/56Q4u automatically it would download the Arq2.

So far my .htaccess is just the basics to get . php out of the end.

.htaccess:

RewriteEngine On

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

RewriteRule ^(.*)$ index.php?url=$1

1 answer

1

Something very simple, to have a minimum sense of what you really need to 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';
}

To the 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 recommendable, there are procedures that you must still implement and several modifications to be made, for it to be implemented successfully. It shall also consult the documentation of the apache.

References

Browser other questions tagged

You are not signed in. Login or sign up in order to post.