PHP代码优化:使用Curl判断文件大小避免下载过大文件
PHP代码优化:使用Curl判断文件大小避免下载过大文件
在进行文件下载操作时,我们有时需要避免下载过大的文件。例如,我们只想下载小于8KB的图片。本文介绍如何使用PHP的Curl函数来判断远程文件的大小,从而避免下载过大的文件,提高代码效率和节省带宽。
原代码:
function save_to_local($weburl,$savepath = '') {
$succeed = false;
set_time_limit(0);
if (substr($savepath, -1) != '/') $savepath .= '/';
if (!is_dir($savepath)) @mkdir($savepath, 0777);
/** $imgurl = 'http://images.thumbshots.com/image.aspx?cid=EnF7XhnLiAA%3d&v=1&w=180&url=http://'.$weburl; */
$imgurl = 'https://s0.wp.com/mshots/v1/'.$weburl.'?w=730&h=500';
/** $imgurl = 'http://images.thumbshots.com/image.aspx?cid=cAADZO143yU%3d&v=1&w=180&url=http://'.$weburl; */
$newpath = $savepath.strtr($weburl,'.','_').'.png';
$data = get_url_content($imgurl);
if (strlen($data) != 1984) {
if ($data) {
$fp = @fopen($newpath, 'w');
@fwrite($fp, $data);
@fclose($fp);
$succeed = true;
}
}
if ($succeed) {
return $newpath;
} else {
return $succeed;
}
}
修改后的代码:
function save_to_local($weburl,$savepath = '') {
$succeed = false;
set_time_limit(0);
if (substr($savepath, -1) != '/') $savepath .= '/';
if (!is_dir($savepath)) @mkdir($savepath, 0777);
$imgurl = 'https://s0.wp.com/mshots/v1/'.$weburl.'?w=730&h=500';
$newpath = $savepath.strtr($weburl,'.','_').'.png';
$ch = curl_init($imgurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_exec($ch);
$filesize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
if ($filesize > 0 && $filesize < 8192) {
$data = get_url_content($imgurl);
if ($data) {
$fp = @fopen($newpath, 'w');
@fwrite($fp, $data);
@fclose($fp);
$succeed = true;
}
}
if ($succeed) {
return $newpath;
} else {
return $succeed;
}
}
代码解释:
- 使用
curl_init函数初始化一个Curl句柄。 - 设置
CURLOPT_RETURNTRANSFER为true,表示将结果返回到字符串中,而不是直接输出到浏览器。 - 设置
CURLOPT_HEADER为true,表示将响应头信息也包含在结果中。 - 设置
CURLOPT_NOBODY为true,表示只获取响应头信息,不获取响应主体内容。 - 设置
CURLOPT_FOLLOWLOCATION为true,表示跟随重定向。 - 设置
CURLOPT_MAXREDIRS为10,表示最多跟随10次重定向。 - 执行
curl_exec函数发送请求。 - 使用
curl_getinfo函数获取CURLINFO_CONTENT_LENGTH_DOWNLOAD信息,即文件大小。 - 关闭 Curl 句柄。
- 判断文件大小是否在 0 到 8192 字节之间。如果是,则下载文件。
注意事项:
- 确保服务器已安装 Curl 扩展。
- 使用
get_url_content函数下载文件,该函数需要根据您的环境进行定义。 - 8192 字节等于 8KB。
总结:
通过使用 Curl 函数判断文件大小,可以有效地避免下载过大的文件,提高代码效率和节省带宽。这是一种常用的 PHP 代码优化技巧。
原文地址: https://www.cveoy.top/t/topic/qz1y 著作权归作者所有。请勿转载和采集!