How to get remote file size by CURL

CURL is one of the familiar debugging tools for web developers. Basically it is a command line tool for transferring data with URL syntax, supporting DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, TELNET and TFTP. You can easily get a remote file size using CURL. You can do it using following function:

function remote_filesize($url, $user = “”, $pw = “”)
{
ob_start();
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);

if(!empty($user) && !empty($pw))
{
$headers = array(‘Authorization: Basic ‘ .  base64_encode(“$user:$pw”));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}

$ok = curl_exec($ch);
curl_close($ch);
$head = ob_get_contents();
ob_end_clean();

$regex = ‘/Content-Length:s([0-9].+?)s/’;
$count = preg_match($regex, $head, $matches);

return isset($matches[1]) ? $matches[1] : “unknown”;
}

All you have to do is just to point your file and mention the filesize.

To use this you will need CURL complied with PHP. You can download the latest version of CURL from here.

Leave a Reply

Your email address will not be published. Required fields are marked *