How do I load a URL into a string using PHP?

Turns out to be quite trivial in fact. All you have to do is:


There is a caveat though. I've discovered a very nasty bug only recently with this approach. While trying to use this approach to send SMS messages via a HTTP gateway on an Android phone I would get long timeouts. It turned out that file_get_contents would load the URL correctly but then fail to finish and return. This would cause the whole system to block and malfunction randomly. The alternative that I used which turned out to be quite a bit better is this code:

$curl = curl_init();

if (!$curl) return FALSE;

// Set some options - we are passing in a useragent too here
CURLOPT_USERAGENT => 'Documentation Planet Bot'

// Send the request & save response to $urlContent
$urlContent = curl_exec($curl);

// Close request to clear up some resources

This saved me from the timeout issue and worked like a charm. Functionally, it gives exactly the same result, but that "little" timeout issue made it a winner for me.

Let me know your thoughts in the comments bellow!

Your thoughts

No comments

Add comment

* - required field