PHP 获取远程文件大小的3种解决方法
程序员文章站
2023-11-30 16:24:46
1、使用file_get_contents()复制代码 代码如下:
1、使用file_get_contents()
<?php
$file = file_get_contents($url);
echo strlen($file);
?>
2. 使用get_headers()
<?php
$header_array = get_headers($url, true);
$size = $header_array['content-length'];
echo $size;
?>
ps:
需要打开allow_url_fopen!
如未打开会显示
warning: get_headers() [function.get-headers]: url file-access is disabled in the server configuration
3.使用fsockopen()
<?php
function get_file_size($url) {
$url = parse_url($url);
if (empty($url['host'])) {
return false;
}
$url['port'] = empty($url['post']) ? 80 : $url['post'];
$url['path'] = empty($url['path']) ? '/' : $url['path'];
$fp = fsockopen($url['host'], $url['port'], $error);
if($fp) {
fputs($fp, "get " . $url['path'] . " http/1.1\r\n");
fputs($fp, "host:" . $url['host']. "\r\n\r\n");
while (!feof($fp)) {
$str = fgets($fp);
if (trim($str) == '') {
break;
}elseif(preg_match('/content-length:(.*)/si', $str, $arr)) {
return trim($arr[1]);
}
}
fclose ( $fp);
return false;
}else {
return false;
}
}
?>
复制代码 代码如下:
<?php
$file = file_get_contents($url);
echo strlen($file);
?>
2. 使用get_headers()
复制代码 代码如下:
<?php
$header_array = get_headers($url, true);
$size = $header_array['content-length'];
echo $size;
?>
ps:
需要打开allow_url_fopen!
如未打开会显示
warning: get_headers() [function.get-headers]: url file-access is disabled in the server configuration
3.使用fsockopen()
复制代码 代码如下:
<?php
function get_file_size($url) {
$url = parse_url($url);
if (empty($url['host'])) {
return false;
}
$url['port'] = empty($url['post']) ? 80 : $url['post'];
$url['path'] = empty($url['path']) ? '/' : $url['path'];
$fp = fsockopen($url['host'], $url['port'], $error);
if($fp) {
fputs($fp, "get " . $url['path'] . " http/1.1\r\n");
fputs($fp, "host:" . $url['host']. "\r\n\r\n");
while (!feof($fp)) {
$str = fgets($fp);
if (trim($str) == '') {
break;
}elseif(preg_match('/content-length:(.*)/si', $str, $arr)) {
return trim($arr[1]);
}
}
fclose ( $fp);
return false;
}else {
return false;
}
}
?>