if($url = file_get_contents("https://api.twitter.com/1/statuses/user_timeline.json?screen_name=".$user)){}
else die("Invalid User");
Is this a good way to run this script?
I'm not sure what you mean, but if you ask if your call of file_get_contents
is correct, then I must say yes, because, as stated here:
On failure, file_get_contents() will return FALSE.
Yes, your code is correct, and will fill $url
with the contents of the page, or return false if the requested URL results in an error code. Note, however, that a page with a value of 0
or the empty string will also be interpreted as false
. To avoid this, use the strong-matching !==
:
if(false !== ($url = file_get_contents("https://api.twitter.com/1/statuses/user_timeline.json?screen_name=".$user)))
If you just want to check that the URL is valid, use get_headers to only fetch the headers of the response with a HTTP HEAD request:
stream_context_set_default(
array(
'http' => array(
'method' => 'HEAD'
)
)
);
$headers = get_headers('http://example.com'. 1);
// get the response code
$parts = explode(' ', $headers[0]);
$code = $parts[1];
if($code == 200) ... // success
if($code == 404) ... // failure
This will save you from transmitting the whole page over the network.
You need to check for === false
(note the three =
), since empty content or content 0
would also fail the test.
Better check the HTTP status code via the $http_response_header
variable - it should be in the 200 range (200-299).