Php 如何生成动态URL以防止直接下载?
我想为我的网站生成一个下载url,当前类似,但可以直接访问。我不希望人们复制粘贴链接,然后直接开始下载,我通过电子邮件发送下载链接。1:不要给用户直接链接到文件的链接。将这些文件放在受.htaccess保护的单独文件夹中。例如:将所有文件放在名为“User\u files”的目录下,并在该目录下生成此.htaccess文件:Php 如何生成动态URL以防止直接下载?,php,Php,我想为我的网站生成一个下载url,当前类似,但可以直接访问。我不希望人们复制粘贴链接,然后直接开始下载,我通过电子邮件发送下载链接。1:不要给用户直接链接到文件的链接。将这些文件放在受.htaccess保护的单独文件夹中。例如:将所有文件放在名为“User\u files”的目录下,并在该目录下生成此.htaccess文件: deny from all 因此用户无法直接访问此文件 2:创建一个php脚本,将文件读取给用户。您可以在读取文件之前进行会话或登录检查,如下所示: if (isset(
deny from all
因此用户无法直接访问此文件
2:创建一个php脚本,将文件读取给用户。您可以在读取文件之前进行会话或登录检查,如下所示:
if (isset($_SESSION['logged_in']) AND $_SESSION['logged_in'] == 1){ //change it to suit your needs to verify whatever you want before reading file to user
$file = "Files/something.rar";
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
}
因此,当用户访问时,PHP将向用户读取文件。您可以创建一个脚本,告诉PHP为该文件提供服务。这是一个很好的函数,我在某个地方得到了它: 下载.php
function send_download($file){
$basename = basename($file);
$length = sprintf("%u", filesize($file));
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $basename . '"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header("Accept-Ranges: bytes");
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $length);
set_time_limit(0);
ob_get_clean();
readfile($file);
ob_end_flush();
}
$file="file/download/path";
send_download($file);
因此,您的下载链接如下所示:
something.com/download.php?id=some_hash_or_id
您也可以通过启动会话来执行此操作。如果会话不存在,请不要将头设置为下载文件位置。否则,将头设置为下载文件。甚至您也可以设置允许ip/用户下载该文件的时间:)我没有登录模块,希望使用电子邮件提供该文件的链接
<?php
//start session
session_start();
function randomkey( $length ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return substr(str_shuffle($chars),0,$length);
}
//if the session exist
if(isset($_SESSION['sessionid'])){
//check session id
if($_SESSION['sessionid'] == $_GET['sessionid']){
echo 'Download script here! for file :' . $_GET['fileid'];
session_destroy(); //to avoid reapply for download
}else{ //if user has provided false sessions.
echo 'Redirect user to the page again!';
session_destroy(); //to avoid reapply for download
}
}else{
//if session not exist
//create a temporary session
$sessionid = randomkey(20);
$_SESSION['sessionid'] = $sessionid;
?>
<form action="" method="get">
<input type="hidden" name="sessionid" value="<?php echo $sessionid ?>">
<input type="hidden" name="fileid" value="File you want the user to download">
<input type="submit" value="download">
</form>
<?php
}
?>