3

I'm wondering if it's possible to have an if statement something like this:

if file_get_contents() returns error code xxx OR xxx
    die();

I'm not sure how to check if file_get_contents() returns an error.

4 Answers 4

8

It seems you are looking to get the HTTP status code. In that case, you need to read it from here:

$http_response_header

http://php.net/manual/en/reserved.variables.httpresponseheader.php

Otherwise, if you want the generic error, follow deceze's instructions.

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

Comments

5

http://php.net/file_get_contents

The function returns the read data or FALSE on failure.

It either works or it doesn't, as such:

$file = file_get_contents(...);
if ($file === false) {
    die();
}

PS: Of course, in the above answer I expect you use file_get_contents to get the contents of a local file. If you're trying to get the HTTP status code of a remote URL, I'd suggest you use cURL or similar specialized HTTP libraries and parse the response headers.

1 Comment

Well I'm trying to get a remote JSON file, but I assume the above codes will still work, I don't need to get a specific code, like you said, it either works or it doesn't.
1

As the php docs state, file_get_contents() will return false on all errors, so all you can do is

if ($content=file_get_contents($filename)===false) die("Error reading file $filename");

Comments

0

you can call it that way:

$data = file_get_contents("http://site.com/that.php");
if ($data !== FALSE) {
   // analyze data
}

Comments

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.