How to get remote file size without downloading file with PHP?

Spread the love

Sometimes, we want to get remote file size without downloading file with PHP.

In this article, we’ll look at how to get remote file size without downloading file with PHP.

How to get remote file size without downloading file with PHP?

To get remote file size without downloading file with PHP, we can use the curl_getinfo function.

For instance, we write

function retrieve_remote_file_size($url)
{
    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);

    $data = curl_exec($ch);
    $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);

    curl_close($ch);
    return $size;
}

to define the retrieve_remote_file_size function.

In it, we call curl_init with $url to get the $ch object.

Then we call curl_getinfo with $ch and CURLINFO_CONTENT_LENGTH_DOWNLOAD to get the remote file’s size.

And then we call curl_close with $ch to close the connection.

Conclusion

To get remote file size without downloading file with PHP, we can use the curl_getinfo function.

Leave a Reply

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