Asked  7 Months ago    Answers:  5   Viewed   48 times

I need to check if a particular file exists on a remote server. Using is_file() and file_exists() doesn't work. Any ideas how to do this quickly and easily?

 Answers

31

You have to use CURL

function does_url_exists($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($code == 200) {
        $status = true;
    } else {
        $status = false;
    }
    curl_close($ch);
    return $status;
}
Wednesday, March 31, 2021
 
Gordnfreeman
answered 7 Months ago
76

This is tricky. It depends what encoding your filesystem uses for filenames and how (if) your webserver or PHP functions convert the encoding.

First of all, make sure your links never use unencoded non-ASCII characters. URLs should be in UTF-8, i.e. é should be encoded as %C3%A9. If that doesn't work, try %E9 (é in ISO-8859-1).

You might find iconv() function useful to convert encodings. rawurlencode() is obligatory.

Saturday, May 29, 2021
 
MannfromReno
answered 5 Months ago
20

This is a way to see if any XML-files exists in that folder, yes.

To check for specific files use File.Exists(path), which will return a boolean indicating wheter the file at path exists.

Thursday, June 10, 2021
 
pocketfullofcheese
answered 5 Months ago
34

WebClient is fairly limited; if you switch to using WebRequest, then you gain the ability to send an HTTP HEAD request. When you issue the request, you should either get an error (if the file is missing), or a WebResponse with a valid ContentLength property.

Edit: Example code:

WebRequest request = WebRequest.Create(new Uri("http://www.example.com/"));
request.Method = "HEAD";

using(WebResponse response = request.GetResponse()) {
   Console.WriteLine("{0} {1}", response.ContentLength, response.ContentType);
}
Thursday, July 22, 2021
 
EzzDev
answered 3 Months ago
77
$ch = curl_init();
.... curl setup
$data = curl_exec($ch);
if ($data === FALSE) {
   die(curl_error($ch));
}

// do this, instead of the header/readfile business.
file_put_contents('/some/path/on/your/webhost', $data);
Tuesday, August 24, 2021
 
jlh
answered 2 Months ago
jlh
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :