If file exists function - server-side


/ Published in: PHP
Save to your folder(s)

This function can be used to check if a file exists using the HTTP header response. Example use, when looping through cached JSON objects (instagram API, etc.)


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function exists($url) {
  4. // Get file contents limited to one character as
  5. // the whole file isn't needed, only the response
  6. // header
  7. file_get_contents($url, NULL, NULL, 0, 1);
  8. // Parse response
  9. $response = $http_response_header[0];
  10. // Split response to isolate reponse number
  11. $split = explode(" ", $response);
  12. // Return true if 200 header response received
  13. if ($split[1] == "200") return true;
  14. // Return false if 403 (not found) received
  15. else if ($split[1] == "403") return false;
  16. // Any other response return false
  17. else return false;
  18. }
  19.  
  20. // Example usage - Check to see if image exists using img src url
  21.  
  22. //$url = "http://distilleryimage8.s3.amazonaws.com/4a2813d8785e11e2893322000a1f9ca0_7asd.jpg";
  23. $url = "http://distilleryimage8.s3.amazonaws.com/4a2813d8785e11e2893322000a1f9ca0_7.jpg/";
  24. if (exists($url)) echo "image exists";
  25. else echo "image does not exist";
  26.  
  27. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.