Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the file size by url in php script [duplicate]

Tags:

php

how can I make sure that the file exists on the server and find out its size on the URL without first downloading the file

$url = 'http://site.zz/file.jpg';
file_exists($url); //always is false
filesize($url); //not working

Help eny one worked exemple pls

like image 775
Evgeniy Chorniy Avatar asked Oct 23 '25 16:10

Evgeniy Chorniy


1 Answers

The function file_exists() only works on file that exists on the server locally.

Similarly; filesize() function returns the size of the file that exists on the server locally.

If you are trying to load the size of a file for a given url, you can try this approach:

function get_remote_file_info($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);
    $fileSize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
    $httpResponseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return [
        'fileExists' => (int) $httpResponseCode == 200,
        'fileSize' => (int) $fileSize
    ];
}

Usage:

$url = 'http://site.zz/file.jpg';
$result = get_remote_file_info($url);
var_dump($result);

Example output:

array(2) {
  ["fileExists"]=>
  bool(true)
  ["fileSize"]=>
  int(12345)
}
like image 110
Latheesan Avatar answered Oct 26 '25 05:10

Latheesan