Retrieve Filesize from URL Without Downloading - Easy Method

Learn how to easily retrieve the filesize of a file from its URL without actually downloading it. This method saves time and bandwidth, useful for large files

Here's a PHP code snippet to get the filesize from a URL without downloading the file:

$url = ''; // Replace with your file URL

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$data = curl_exec($ch);

if ($data === false) {
    echo 'Error: ' . curl_error($ch);
} else {
    preg_match('/Content-Length: (\d+)/', $data, $matches);
    $contentLength = (int) $matches[1];
    echo 'File size: ' . $contentLength . ' bytes';

Replace $url with the URL of the file you want to check. The code uses cURL to send a HEAD request to the server, which retrieves the file headers including the Content-Length header that indicates the filesize in bytes. The code then extracts the Content-Length value from the headers using a regular expression and outputs it.