我有一个托管在code.google.com上的可执行文件(比如,http://code.google.com/fold/file1.exe)。当用户浏览到http://mysite.com/download.exe,我希望他们自动获取文件的内容http://code.google.com/fold/file1.exe而没有任何重定向。用户应该认为他/她正在从http://mysite.com/download.exe不http://code.google.com/fold/file1.exe.
使用PHP,我该如何做到这一点?这个过程有什么特别的术语吗?
您可以使用URL重写将文件名作为参数传递给脚本。您的脚本(本例中为downloadexecutable.php)将响应$_GET参数"q",该参数将包含"download":
<?php
if (isset($_GET['q']) && $_GET['q'] == "download") {
//you will want to:
//1) set Content-type to be the correct type...I just set it to octet-stream because I'm not sure what it should be
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename('http://code.google.com/fold/file1.exe').'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize('http://code.google.com/fold/file1.exe')); // provide file size
echo file_get_contents('http://code.google.com/fold/file1.exe'); // push it out
exit()
}
?>
然后,您可以在根目录中的.htaccess文件中启用Apache上的URL重写,如下所示:
RewriteEngine On
RewriteRule ^(.+)'.exe$ /downloadexecutable.php?q=$1 [NC,L]
当用户请求任何以.exe结尾的文件时,downloadexecutable.php应按如下方式执行:
请求:http://yoursite.com/download.exe
PHP实际处理的内容:http://yoursite.com/downloadexecutable.php?q=download
请求:http://yoursite.com/this/could/be/a/bug.exe
已处理:http://yoursite.com/downloadexecutable.php?q=this/could/be/a/bug
很明显,这需要一些工作,我还没有测试过上面的任何一项,但如果你在这里闲逛一段时间,并愿意使用谷歌,你应该能够让它发挥作用。
URL重写教程:http://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/
php内容的来源:http://snipplr.com/view/22546/
您可能想尝试这种方法:
<?
function get_file($url) {
$ficheiro = "file.exe";
$fp = fopen (dirname(__FILE__) . "/$ficheiro", 'w+'); //make sure you've write permissions on this dir
//curl magic
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);
}
//sets the original file url
$url = "http://code.google.com/fold/file1.exe";
//downloads original file to local dir
get_file($url);
//redirect user to the download file hosted on your site
header("Location: $ficheiro");
?>
并将其添加到你的.htaccess:中
RewriteEngine On
RewriteRule ^download.exe this_script.php