Remote file size without downloading file

前端 未结 14 1660
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 03:01

Is there a way to get the size of a remote file http://my_url/my_file.txt without downloading the file?

14条回答
  •  [愿得一人]
    2020-11-22 03:17

    The simplest and most efficient implementation:

    function remote_filesize($url, $fallback_to_download = false)
    {
        static $regex = '/^Content-Length: *+\K\d++$/im';
        if (!$fp = @fopen($url, 'rb')) {
            return false;
        }
        if (isset($http_response_header) && preg_match($regex, implode("\n", $http_response_header), $matches)) {
            return (int)$matches[0];
        }
        if (!$fallback_to_download) {
            return false;
        }
        return strlen(stream_get_contents($fp));
    }
    

提交回复
热议问题