Is there a way to get the size of a remote file http://my_url/my_file.txt without downloading the file?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
Most answers here uses either CURL or are basing on reading headers. But in some certain situations you can use a way easier solution. Consider note on
filesize()
's docs on PHP.net. You'll find there a tip saying: "As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality".So, if your server and PHP parser is properly configured, you can simply use
filesize()
function, fed it with full URL, pointing to a remote file, which size you want to get, and let PHP do the all magic.Found something about this here:
Usage:
As mentioned a couple of times, the way to go is to retrieve the information from the response header's
Content-Length
field.However, you should note that
fopen
or alike or even to invoke the curl library, when PHP hasget_headers()
(remember: K.I.S.S.)Use of
get_headers()
follows the K.I.S.S. principle and works even if the server you're probing does not support the HEAD request.So, here's my version (gimmick: returns human-readable formatted size ;-)):
Gist: https://gist.github.com/eyecatchup/f26300ffd7e50a92bc4d (curl and get_headers version)
get_headers()-Version:
Usage:
Additional note: The Content-Length header is optional. Thus, as a general solution it isn't bullet proof!
Try the below function to get Remote file size
one line best solution :
php is too delicius
Here is another approach that will work with servers that do not support
HEAD
requests.It uses cURL to make a request for the content with an HTTP range header asking for the first byte of the file.
If the server supports range requests (most media servers will) then it will receive the response with the size of the resource.
If the server does not response with a byte range, it will look for a content-length header to determine the length.
If the size is found in a range or content-length header, the transfer is aborted. If the size is not found and the function starts reading the response body, the transfer is aborted.
This could be a supplementary approach if a
HEAD
request results in a405
method not supported response.Usage: