共计 2104 个字符,预计需要花费 6 分钟才能阅读完成。
前言
这是一篇一站式服务的 php 下载文件解决方案。集合了下载远程文件和本地服务器中文件的方法。
之所以写这篇文章的原因是,之前在项目中有个需求是要求直接下载文件而不是从浏览器中打开。从网上找了很多方法,但是大多是直接下载本地的服务器中的文件。
于是我就稍加改造了一下网上找到的代码,话不多说直接上代码
<?php | |
/** | |
* | |
* | |
* sys_download_file('web 服务器中的文件地址', 'test.jpg'); | |
* sys_download_file('远程文件地址', 'test.jpg', true); | |
* | |
* | |
* | |
* @param $path 件地址:针对当前服务器环境的相对或绝对地址 | |
* @param null $name 下载后的文件名(包含扩展名)* @param bool $isRemote 是否是远程文件(通过 url 无法获取文件扩展名的必传参数 name)* @param bool $isSSL 是否是 HTTPS 协议 | |
* @param string $proxy | |
* @return bool true|false | |
*/ | |
function sys_download_file($path, $name = null, $isRemote = false, $isSSL = false, $proxy = '') { | |
$fileRelativePath = $path; | |
$savedFileName = $name; | |
if (!$savedFileName) {$file = pathinfo($path); | |
if (!empty($file['extension'])) {$savedFileName = $file['basename']; | |
} else { | |
echo 'Extension get failed, parameter \'name\'is required!'; | |
return false; | |
} | |
} | |
// 如果是远程文件,先下载到本地 | |
if ($isRemote) {$file = empty('') ? pathinfo($path,PATHINFO_BASENAME) :''; | |
$dir = pathinfo($file,PATHINFO_DIRNAME); | |
!is_dir($dir) && @mkdir($dir,0755,true); | |
$url = str_replace("","%20",$path); | |
if(function_exists('curl_init')) {$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_TIMEOUT, 60); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查 | |
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查 SSL 加密算法是否存在 | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); | |
$temp = curl_exec($ch); | |
if (@file_put_contents($file, $temp) && !curl_error($ch)) {$fileRelativePath = './'.$file;} else {return false;} | |
} | |
} | |
// 执行下载 | |
if (is_file($fileRelativePath)) {// header('Content-Description: File Transfer'); | |
header('Content-type: application/octet-stream'); | |
header('Content-Length:' . filesize($fileRelativePath)); | |
if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { // for IE | |
header('Content-Disposition: attachment; filename="' . rawurlencode($savedFileName) . '"'); | |
} else {header('Content-Disposition: attachment; filename="' . $savedFileName . '"'); | |
} | |
readfile($fileRelativePath); | |
if ($isRemote) {unlink($fileRelativePath); // 删除下载远程文件时对应的临时文件 | |
} | |
return true; | |
} else { | |
echo 'Invalid file:' . $fileRelativePath; | |
return false; | |
} | |
} | |
// 下载远程文件 | |
sys_download_file('https://xxx.xxx.xxx/download/M0/xxxx.pdf','xxxx.pdf',true,true); | |
// 下载本地文件 | |
sys_download_file('F:\Visual-AMP-x64\www\Demo1\ico_checkon.svg','ico_checkon.svg',false,false); |
正文完