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:

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

Checking existence of file with help function fopen()

PHP function fopen() - opens the file.

Example:

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

Checking existence of file with help function cURL

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

Example:

<?php
// url of file to check for the existence of
$url = "http://site.com/image.jpg";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpCode == 200) {
    echo "File exists";
} else {
    echo "File not found";
}

PHP