Home > Backend Development > PHP Tutorial > php文件下载解决办法

php文件下载解决办法

WBOY
Release: 2016-06-13 12:16:19
Original
911 people have browsed it

php文件下载
下面是我在网上的找的代码,自己改了下:

down_file.php:

<?php<br /><br />if(!empty($_GET)){<br /><br />    header("Content-type: application/octet-stream ; charset=utf-8"); //输出类型 <br />	header("Content-Disposition:filename=".$name);<br />	header("Accept-Ranges: bytes"); //文件单位<br />	header("Accept-Length:".$filesize); //文件大小<br />	header("Content-Disposition: attachment; filename=".$name);//下载时显示的名字<br />$name=$_GET['name'];<br />	$url=$_GET['url'];<br /><br />	$f=fopen($url.$name, "r");<br />	$buffer=1024;<br />	$filesize=filesize($name);<br />	$downsize=0;<br />	$str="";<br />	while(!feof($f) && ($filesize-$downsize)>0){<br />		$downsize+=$buffer;<br />		echo fread($f,$buffer);<br /><br />	}<br />	//echo $str;<br />	fclose($f);<br /><br />}<br /><br />?>
Copy after login


html页面:
<!DOCTYPE html><br /><html><br />	<head><br />		<meta charset="utf-8"><br />		<title>Document</title><br />	</head><br />	<body><br />		<br />	<a href="down_file.php?name=a.jpg&url=./img/">下载a.jpg</a><br /><br />	</body><br /></html>
Copy after login


目的是下载a.jpg,
问题是点击后弹出窗口下载的是down_file.php而不是a.jpg。。如下图



求指点一下,能给个能用的代码更好了
------解决思路----------------------
$name=$_GET['name'];
$url=$_GET['url'];
$filesize=filesize($url.$name);

这三句要放在上面,否则 header("Content-Disposition:filename=".$name); 会拿不到$name导致出notice.

改成这样
<br />if(!empty($_GET)){<br />    $name=$_GET['name'];<br />    $url=$_GET['url'];<br />    $filesize=filesize($url.$name);<br /><br />    header("Content-type: application/octet-stream ; charset=utf-8"); //输出类型 <br />    header("Content-Disposition:filename=".$name);<br />    header("Accept-Ranges: bytes"); //文件单位<br />    header("Accept-Length:".$filesize); //文件大小<br />    header("Content-Disposition: attachment; filename=".$name);//下载时显示的名字<br /><br /> <br />    $f=fopen($url.$name, "r");<br />    $buffer=1024;<br />    $downsize=0;<br />    $str="";<br />    while(!feof($f) && ($filesize-$downsize)>0){<br />        $downsize+=$buffer;<br />        echo fread($f,$buffer);<br /> <br />    }<br />    //echo $str;<br />    fclose($f);<br /> <br />}<br />
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template