PHP, checking existence/availability of file on remote web server

March 9, 2016 15 Alex

3 Ways checking existence/availability of a file on the web server.

Checking existence of file with help function get_headers()

Function PHP get_headers () - returns all the headers from the response of server in the array. If the file is exists, we must obtain a response code of server 200 OK.

Example:

  1. <?php
  2. // url of file to check for the existence of
  3. $url = "http://site.com/image.jpg";
  4. $urlHeaders = @get_headers($url);
  5. // check the server response to the presence of code: 200 - OK
  6. if(strpos($urlHeaders[0], '200')) {
  7. echo "File exists";
  8. } else {
  9. echo "File not found";
  10. }

Checking existence of file with help function fopen()

PHP function fopen() - opens the file.

Example:

  1. <?php
  2. // url of file to check for the existence of
  3. $url = "http://site.com/image.jpg";
  4. // open file for reading
  5. if (@fopen($url, "r")) {
  6. echo "File exists";
  7. } else {
  8. echo "File not found";
  9. }

Checking existence of file with help function cURL

cURL allows you to interact with the server via different protocols.

Example:

  1. <?php
  2. // url of file to check for the existence of
  3. $url = "http://site.com/image.jpg";
  4. $ch = curl_init($url);
  5. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  6. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  7. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  8. $response = curl_exec($ch);
  9. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  10. curl_close($ch);
  11. if($httpCode == 200) {
  12. echo "File exists";
  13. } else {
  14. echo "File not found";
  15. }

PHP