Summary of common methods for obtaining remote file size using PHP. 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. there are many methods to obtain the remote file size in fsockopen code such as php. The most common methods are fsockopen, file_get_contents, and curl functions. below I will summarize them for you.
1. fsockopen
The code is as follows: |
|
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: |
|
$ File = file_get_contents ($ url ); Echo strlen ($ file ); ?> |
3. use get_headers ()
The code is as follows: |
|
$ 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: |
|
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; } |
Bytes. 1. fsockopen code such...