Archey
Archey

Reputation: 1342

PHP file_get_contents return error

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.

Upvotes: 3

Views: 13568

Answers (4)

deceze
deceze

Reputation: 522626

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.

Upvotes: 5

user1299518
user1299518

Reputation:

you can call it that way:

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

Upvotes: 0

Brad
Brad

Reputation: 163612

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.

Upvotes: 8

Eugen Rieck
Eugen Rieck

Reputation: 65342

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");

Upvotes: 1

Related Questions