php下载文件代码详解,php将远超文件下载到本地的示例代码详解
注:這個(gè)demo適用的是yii框架,如果您使用的不是yii框架,這個(gè)方法也適用您,簡(jiǎn)單的了解一下思路/**
* 保存文件到本地
* @param 文件路徑 $url
* @param 保存本地路徑 $savePath
* @return string
*/
public static function downloadFile($url) {
$www_root = Yii::getPathOfAlias('webroot');
$root_dir = 'uploads/audio';
$build_dir = date('Y') . '/' . date('m');
$origin_dir = $root_dir . '/' . $build_dir;
$savePath = $www_root . DIRECTORY_SEPARATOR . $origin_dir . DIRECTORY_SEPARATOR;// 本地存放的路徑(我是按照年月日來劃分)
$fileName = Common::getUrlFileExt($url); // 獲取文件擴(kuò)展名
if (!file_exists($savePath)) {
Common::mkdirs($savePath); //目錄不存在創(chuàng)建目錄
}
$fileName = time() . '.' . $fileName;
//$file = file_get_contents($url);
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch); //使用curl $ch 為返回的文件流
if (!empty($file_contents)) {
file_put_contents($savePath . '/' . $fileName, $file_contents); //保存到本地的地址
return '/' . $origin_dir . '/' . $fileName; //返回本地地址
}
}
/**
* 獲取文件擴(kuò)展名
* @param 網(wǎng)頁URL $url
* @return string
*/
public static function getUrlFileExt($url) {
$ary = parse_url($url);
$file = basename($ary['path']);
$ext = explode('.', $file);
return $ext[1];
}/**
* 創(chuàng)建多級(jí)目錄
*/
public static function mkdirs($dir) {
if (!is_dir($dir)) {
if (!Common::mkdirs(dirname($dir))) {
return false;
}
if (!mkdir($dir, 0777)) {
return false;
}
}
return true;
}downloadFile(http://www.php.cn/); // 調(diào)用
總結(jié)
以上是生活随笔為你收集整理的php下载文件代码详解,php将远超文件下载到本地的示例代码详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php系统构建,增加知识: 如何使用PH
- 下一篇: 如何统计php数组值的和,php数组键值