php文件下载
2026-04-30 21:53:37
166
分类:php
简单的文本文件下载
/**
* 下载文本文件
* @param string $file_url 下载路径
* @param string $save_to 保存路径
*/
public function downloadFile($file_url, $save_to)
{
$content = file_get_contents($file_url);
file_put_contents($save_to, $content);
}php远程文件下载
/**
* 采集远程文件(需要开启php_curl扩展)
* @access public
* @param string $remote 远程文件名
* @param string $local 本地保存文件名
* @return mixed
*/
public function curlDownload($remote, $local)
{
$cp = curl_init($remote);
$fp = fopen($local, "w");
curl_setopt($cp, CURLOPT_FILE, $fp);
curl_setopt($cp, CURLOPT_HEADER, 0);
curl_setopt($cp, CURLOPT_SSL_VERIFYPEER, false); //禁止curl验证对等证书
curl_exec($cp);
curl_close($cp);
fclose($fp);
}php文件下载,基于ThinkPHP类库-Org类库-Http类
/**
* 文件下载(需要开启php_fileinfo扩展)
* 可以指定下载显示的文件名,并自动发送相应的Header信息
* 如果指定了content参数,则下载该参数的内容
* @static
* @access public
* @param string $filename 下载文件名
* @param string $showname 下载显示的文件名
* @param string $content 下载的内容
* @param integer $expire 下载内容浏览器缓存时间
* @return void
*/
public function download($filename, $showname = '', $content = '', $expire = 180)
{
if (is_file($filename)) {
$length = filesize($filename);
}
elseif (is_file(UPLOAD_PATH . $filename)) {
$filename = UPLOAD_PATH . $filename;
$length = filesize($filename);
}
elseif ($content != '') {
$length = strlen($content);
}
else {
E($filename . L('下载文件不存在!'));
}
if (empty($showname)) {
$showname = $filename;
}
$showname = basename($showname);
if (!empty($filename)) {
$finfo = new \finfo(FILEINFO_MIME);
$type = $finfo->file($filename);
}
else {
$type = "application/octet-stream";
}
//发送Http Header信息 开始下载
header("Pragma: public");
header("Cache-control: max-age=" . $expire);
//header('Cache-Control: no-store, no-cache, must-revalidate');
header("Expires: " . gmdate("D, d M Y H:i:s", time() + $expire) . "GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . "GMT");
header("Content-Disposition: attachment; filename=" . $showname);
header("Content-Length: " . $length);
header("Content-type: " . $type);
header('Content-Encoding: none');
header("Content-Transfer-Encoding: binary");
if ($content == '') {
readfile($filename);
}
else {
echo($content);
}
exit();
}