我正在使用php脚本,在必要的javascript计时器后提供从我的网站下载,此php脚本导致下载。但是无论我尝试什么,下载的文件都是损坏的。有人可以帮我指出我错在哪里吗。
这是我的代码
<?php
include "db.php";
$id = htmlspecialchars($_GET['id']);
$error = false;
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!($conn)) echo "Failed To Connect To The Database!";
else{
if(mysql_select_db(DB_NAME,$conn)){
$qry = "SELECT Link FROM downloads WHERE ID=$id";
try{
$result = mysql_query($qry);
if(mysql_num_rows($result)==1){
while($rows = mysql_fetch_array($result)){
$f=$rows['Link'];
}
//pathinfo returns an array of information
$path = pathinfo($f);
//basename say the filename+extension
$n = $path['basename'];
//NOW comes the action, this statement would say that WHATEVER output given by the script is given in form of an octet-stream, or else to make it easy an application or downloadable
header('Content-type: application/octet-stream');
header('Content-Length: ' . filesize($f));
//This would be the one to rename the file
header('Content-Disposition: attachment; filename='.$n.'');
//Finally it reads the file and prepare the output
readfile($f);
exit();
}else $error = true;
}catch(Exception $e){
$error = true;
}
if($error)
{
header("Status: 404 Not Found");
}
}
}
?>
mysql_*
函数,因为它们正在弃用过程中。改用MySQLi或PDO,成为一个更好的PHP开发者(http://jason.pureconcepts.net/2012/08/better-php-developer/)。 - Jason McCreary<?php
的开头前面有5个空格吗?你开启了错误报告吗? - Lawrence Cheroneob_start
开始脚本,并在readfile
之前执行ob_clean
。 - air4x