3

I am using cURL in PHP to write a function to get a remote xml file into my local folder. Everything works fine however I have a question:

  $fileIn = curl_init("http://some-remote-host.com/file.xml);
  $fileOut = fopen('myLocal.xml", "w");

  curl_setopt($fileIn, CURLOPT_FILE, $fileOut);
  curl_setopt($fileIn, CURLOPT_HEADER, 0);

  $isCopied = curl_exec($fileIn);
  curl_close($fileIn);
  fclose($fileOut);

  if(!$isCopied)
     return false;
  else
     //do something else

Based on the documentation I read, $isCopied is supposed to be false when the remote file does not exist, and there shouldn't be myLocal.xml but my if(!$isCopied) doesn't seem tobe working. And this is the content of my myLocal.xml

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL something.xml was not found on this server.</p>
<hr>
<address>Apache Server at somehost.com Port 443</address>
</body></html>

My question is: How to get a boolean variable telling me when it succeeded and when it did not. (means when the remote file doesn not exist).

Thank you.

2 Answers 2

3

You can use

curl_getinfo($fileIn, CURLINFO_HTTP_CODE); 

to see what http code was returned (you're looking for 200).

Sign up to request clarification or add additional context in comments.

3 Comments

Did you print it just after curl_exec($fileIn);? If so, please try using curl_errno($ch) to see if you got any errors (also: var_dump is better for debugging than simple echo)
That's weird. The curl_getinfo is always 0 :(
No. I used it after curl_init. Where should I use it?
2

Try this:

$isCopied = curl_getinfo($fileIn, CURLINFO_HTTP_CODE) != 404;

1 Comment

I'm afraid accepting ANY other http code value than 404 is not a good idea, for example http 500 represents server error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.