有沒有辦法阻止用戶使用PHP腳本在我的服務器上下載PDF文件?也就是說,要在請求文件時運行MySQL查詢,請驗證用戶(通過cookie和MySQL查詢匹配),並且僅在用戶通過身份驗證時才爲他提供文件。只有在驗證令牌後才能提供PDF
感謝,
喬爾
有沒有辦法阻止用戶使用PHP腳本在我的服務器上下載PDF文件?也就是說,要在請求文件時運行MySQL查詢,請驗證用戶(通過cookie和MySQL查詢匹配),並且僅在用戶通過身份驗證時才爲他提供文件。只有在驗證令牌後才能提供PDF
感謝,
喬爾
通用技術是將可下載文件放在文檔根目錄之外,然後允許通過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";
}
}
當然可以。只要確保有沒有直接鏈接到PDF文件,並且在執行認證後使用PHP腳本來爲文件內容(而不是它的位置)提供服務。
爲了提供示例代碼,我需要知道您的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');
有很多方法可以做到這一點,一些更好然後其他人。 這只是一個快速而骯髒的問題,而不是我頭頂的方法。
<?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>
爲什麼你不能簡單地將他的位置*文件*後*您的身份驗證檢查已滿足? – 2010-11-28 12:51:20