无论如何,我是否可以“阻止”用户使用PHP脚本在我的服务器上下载PDF文件?也就是说,要在请求文件时运行MySQL查询,请对用户进行身份验证(通过cookie和MySQL查询匹配),并且只有在用户通过身份验证的情况下,才能为他提供文件。
谢谢,
乔尔
答案 0 :(得分:3)
一般技术是将您的可下载文件放在文档根目录之外,然后允许通过PHP脚本进行访问,例如:像这样......
if ($authenticated)
{
//name of download - e.g. leaf name of file
//we strip nasties out of it...
$dl=preg_replace('/[^a-z0-9_]/i', '', $_GET['download']);
//build path to files
$file="/path/to/my/fies/$dl.pdf";
if (file_exists($file))
{
//send the file as our response, with headers to make the client
//interpret this as a saveable download...
header('Content-type: application/pdf');
header("Content-Length: ".filesize($file));
header('Content-Disposition: attachment; filename="'.$dl.'.pdf"');
readfile($file);
}
else
{
//do a 404 not found
header("HTTP/1.0 404 Not Found");
echo "Sorry, that file is not available for download";
}
}
答案 1 :(得分:2)
当然可以。只需确保 no 指向PDF文件的直接链接,并在执行身份验证后使用PHP脚本提供文件内容(而不是其位置)。< / p>
要提供示例代码,我需要知道PDF存储的形式(它是磁盘上的文件吗?还有其他什么?)。
假设PDF是磁盘上的文件:
if (!authentication_successful()) {
// output error message, normal PHP here
}
// Otherwise:
// Tell the browser a PDF is coming
header('Content-type: application/pdf');
// Ask it to present a save dialog, with "downloaded.pdf" as the suggested name
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// Send back the PDF contents
readfile('original.pdf');
答案 2 :(得分:2)
有很多方法可以实现这一目标,有些方法比其他方法更好。 这只是一个快速而肮脏的方法,不受我头脑的影响。
<?php
//Connect to your database
mysql_connect('localhost', 'user', 'pass');
mysql_select_db('database');
//Query the database
$results = mysql_query("SELECT * FROM Auth WHERE Cookie='".mysql_escape_string(@$_COOKIES['auth'])."'");
//Ensure that one and only one instance of the cookie exists in the database
if($results && mysql_num_rows($results) == 1) {
header('Content-type: application/pdf');
header('Content-length: '.filesize('my.pdf'));
if(@$_REQUEST['download'] == '1') header('Content-Disposition: attachment; filename=my.pdf'); //This forces the browser to download vs open the file
readfile('my.pdf');
exit();
}
else {
header('HTTP/1.1 403 Forbidden');
}
?>
如果您希望拦截url /my.pdf,则需要使用Web服务器的方法进行URL重写。比如.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond $1 ^/my\.pdf$
RewriteRule . /index.php [L]
</IfModule>