PHP Curl check for file existence before downloading

后端 未结 4 606
一整个雨季
一整个雨季 2021-01-19 07:43

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

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-19 08:15

    Since you are using HTTP to fetch a resource on the internet, what you really want to check is that the return code is a 404.

    On some PHP installations, you can just use file_exists($url) out of the box. This does not work in all environments, however. http://www.php.net/manual/en/wrappers.http.php

    Here is a function much like file_exists but for URLs, using curl:

    
    

    source: http://www.php.net/manual/en/function.file-exists.php#75064

    Sometimes the CURL extension isn't installed with PHP. In that case you can still use the socket library in the PHP core:

    
    

    source: http://www.php.net/manual/en/function.file-exists.php#73175

    An even faster function can be found here: http://www.php.net/manual/en/function.file-exists.php#76246

提交回复
热议问题