Php has many ways to obtain the remote file size. The most common methods are fsockopen, file_get_contents, and curl functions. I will summarize them for you.
1. fsockopen
| The Code is as follows: |
Copy code |
|
Function getFileSize ($ url ){
$ Url = parse_url ($ url );
If ($ fp = @ fsockopen ($ url ['host'], empty ($ url ['Port'])? 80: $ url ['Port'], $ error )){
Fputs ($ fp, "GET". (empty ($ url ['path'])? '/': $ Url ['path']). "HTTP/1.1rn ");
Fputs ($ fp, "Host: $ url [host] rnrn ");
While (! Feof ($ fp )){
$ Tmp = fgets ($ fp );
If (trim ($ tmp) = ''){
Break;
} Else if (preg_match ('/Content-Length :(. *)/si', $ tmp, $ arr )){
Return trim ($ arr [1]);
}
}
Return null;
} Else {
Return null;
}
}
// Call Method
Echo getFileSize ("http://www.bkjia.comnet /")
?> |
2. Use file_get_contents ()
| The Code is as follows: |
Copy code |
|
$ File = file_get_contents ($ url );
Echo strlen ($ file );
?> |
3. Use get_headers ()
| The Code is as follows: |
Copy code |
|
$ Header_array = get_headers ($ url, true );
// Return results
Array
(
[0] => HTTP/1.1 200 OK
[Date] => Sat, 29 May 2004 12:28:14 GMT
[Server] => Apache/1.3.27 (Unix) (Red-Hat/Linux)
[Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
[ETag] => "3f80f-1b6-3e1cb03b"
[Accept-Ranges] => bytes
[Content-Length] = & gt; 438
[Connection] => close
[Content-Type] => text/html
)
$ Size = $ header_array ['content-length'];
Echo $ size;
?>
|
4. curl
| The Code is as follows: |
Copy code |
|
Function remote_filesize ($ uri, $ user = '', $ pw = '')
{
// Start output buffering
Ob_start ();
// Initialize curl with given uri
$ Ch = curl_init ($ uri );
// Make sure we get the header
Curl_setopt ($ ch, CURLOPT_HEADER, 1 );
// Make it a http HEAD request
Curl_setopt ($ ch, CURLOPT_NOBODY, 1 );
// If auth is needed, do it here
If (! Emptyempty ($ user )&&! Emptyempty ($ pw ))
{
$ Headers = array ('authorization: Basic '. base64_encode ($ user.': '. $ pw ));
Curl_setopt ($ ch, CURLOPT_HTTPHEADER, $ headers );
}
$ Okay = curl_exec ($ ch );
Curl_close ($ ch );
// Get the output buffer
$ Head = ob_get_contents ();
// Clean the output buffer and return to previous
// Buffer settings
Ob_end_clean ();
Echo'
Head --> '. $ head.' <---- end
';
// Gets you the numeric value from the Content-Length
// Field in the http header
$ Regex = '/Content-Length: s ([0-9]. + ?) S /';
$ Count = preg_match ($ regex, $ head, $ matches );
// If there was a Content-Length field, its value
// Will now be in $ matches [1]
If (isset ($ matches [1])
{
$ Size = $ matches [1];
}
Else
{
$ Size = 'unknown ';
}
// $ Last = round ($ size/(1024*1024), 3 );
// Return $ last. 'mb ';
Return $ size;
} |