Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Curl check for file existence before downloading

Tags:

php

curl

I am writing a PHP program that downloads a pdf from a backend and save to a local drive. Now how do I check whether the file exists before downloading?

Currently I am using curl (see code below) to check and download but it still downloads the file which is 1KB in size.

$url = "http://wedsite/test.pdf";
$path = "C:\\test.pdf;"
downloadAndSave($url,$path);

function downloadAndSave($urlS,$pathS)
    {
        $fp = fopen($pathS, 'w');

        $ch = curl_init($urlS);

        curl_setopt($ch, CURLOPT_FILE, $fp);
        $data = curl_exec($ch);

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        echo $httpCode;
        //If 404 is returned, then file is not found.
        if(strcmp($httpCode,"404") == 1)
        {
            echo $httpCode;
            echo $urlS; 
        }

        fclose($fp);

    }

I want to check whether the file exists before even downloading. Any idea how to do it?

like image 491
aandroidtest Avatar asked Dec 12 '22 18:12

aandroidtest


2 Answers

You can do this with a separate curl HEAD request:

curl_setopt($ch, CURLOPT_NOBODY, true);
$data = curl_exec($ch);

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

When you actually want to download you can use set NOBODY to false.

like image 66
Explosion Pills Avatar answered Dec 27 '22 20:12

Explosion Pills


Call this before your download function and it's done:

<?php function remoteFileExists($url) {
    $curl = curl_init($url);

    //don't fetch the actual page, you only want to check the connection is ok
    curl_setopt($curl, CURLOPT_NOBODY, true);

    //do request
    $result = curl_exec($curl);

    $ret = false;

    //if request did not fail
    if ($result !== false) {
        //if request was ok, check response code
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  

        if ($statusCode == 200) {
            $ret = true;   
        }
    }

    curl_close($curl);

    return $ret;
}

?>

like image 38
Gil Avatar answered Dec 27 '22 19:12

Gil