Part 1: PHP: How to get size of a remote file
With a local file, we can get file size of it by using filesize, but with a remote file, how to get size of a remote file?
We offer some methods to get size of a remote file.
Method 7:
<?php /** * @author tutorialspots.com * @copyright 2015 */ function get_size($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_NOBODY, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_exec($curl); $data = curl_getinfo($curl); return isset($data["download_content_length"])?$data["download_content_length"]:false; } ?>
Note: after use curl_getinfo, we get the data
array(20) { ["url"]=> string(57) "http://tutorialspots.com/wp-content/uploads/2013/04/1.png" ["content_type"]=> string(9) "image/png" ["http_code"]=> int(200) ["header_size"]=> int(283) ["request_size"]=> int(89) ["filetime"]=> int(-1) ["ssl_verify_result"]=> int(0) ["redirect_count"]=> int(0) ["total_time"]=> float(0.758) ["namelookup_time"]=> float(0.375) ["connect_time"]=> float(0.571) ["pretransfer_time"]=> float(0.571) ["size_upload"]=> float(0) ["size_download"]=> float(0) ["speed_download"]=> float(0) ["speed_upload"]=> float(0) ["download_content_length"]=> float(3955) ["upload_content_length"]=> float(0) ["starttransfer_time"]=> float(0.758) ["redirect_time"]=> float(0) }
Method 8: similar as method 7
<?php /** * @author tutorialspots.com * @copyright 2015 */ function get_size($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD'); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_exec($curl); $data = curl_getinfo($curl); return isset($data["download_content_length"])?$data["download_content_length"]:false; } ?>
Method 9: use get_headers
<?php /** * @author tutorialspots.com * @copyright 2015 */ function get_size($url) { if (function_exists('version_compare') && version_compare(phpversion(), '5.3.0') > 0) { stream_context_set_default(array('http' => array('method' => 'HEAD'))); } $data = get_headers($url); foreach ($data as $header) { if (strpos($header, 'Content-Length:') === 0) { return trim(substr($header, 16)); } } return false; } ?>
2 Comments
PHP: How to get size of a remote file | Free Online Tutorials
(December 10, 2015 - 1:37 pm)[…] Next: PHP: How to get size of a remote file – Part 2 […]
PHP: How to check if a remote file exists | Free Online Tutorials
(January 11, 2018 - 5:35 pm)[…] PHP: How to get size of a remote file PHP: How to get size of a remote file – Part 2 […]