Reading remote file size using filesize

2019-02-26 20:06发布

I read the manual that filesize() is able to calculate file size from remote file. However, when I try to do that with snippet below. I got error PHP Warning: filesize(): stat failed for http://someserver/free_wallpaper/jpg/0000122_480_320.jpg in /tmp/test.php on line 5

Here's my snippet:

$file = "http://someserver/free_wallpaper/jpg/0000122_480_320.jpg";
echo filesize( $file );

Turns out, I can't use HTTP for filesize(). Case close. I'll use snippet here as a work-around solution.

5条回答
趁早两清
2楼-- · 2019-02-26 20:13

filesize doesn't work for HTTP - it depends on stat, which isn't supported for the HTTP(S) protocol.

The PHP man page for filesize says:

Refer to List of Supported Protocols/Wrappers for a listing of which wrappers support stat() family of functionality.

This doesn't mean every protocol/wrapper works "out of the box" with filesize. You could always get around that by doing a full GET of the remote URL and calculating the size of the data you get back, of if you can get a Content-Length header you could try a HEAD request to avoid transferring the file data.

查看更多
劫难
3楼-- · 2019-02-26 20:17

You can get file size of web url using below code

function getFileSize($file){

   $ch = curl_init($file);
   curl_setopt($ch, CURLOPT_NOBODY, true);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_HEADER, true);
   curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

   $data = curl_exec($ch);
   curl_close($ch);
   $contentLength=0;
   if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
       $contentLength = (int)$matches[1];

   }
   return $contentLength; }
查看更多
小情绪 Triste *
4楼-- · 2019-02-26 20:19

I don't know where you read that. filesize requires stat, and based on the HTTP wrapper page, I don't think it supports stat on any version of PHP.

查看更多
ら.Afraid
5楼-- · 2019-02-26 20:19

If you want to get the remote picture size, try using getimagesize()

查看更多
一夜七次
6楼-- · 2019-02-26 20:20

You might want to investigate using http_head(). I think the snippet you reference downloads the file to determine the file size, which may not be necessary. If the web server you are referencing sends back accurate header information, you should be able to determine file-size, date-modified and several other useful identifying features.

查看更多
登录 后发表回答