Quick PHP Tip: close your connection between stream_get_contents calls

Posted on 22 April 2009 (10:07 PM)

Here's a quick solution to a problem I encountered which might save you some headaches.

When fetching data from a remote location, for instance a web service (like the one Last.fm provides), you can use the native PHP function stream_get_contents.

This method works fairly simple, as shown in the following code snippet:

  1. <?php
  2. $handle = fsockopen($myHostName);
  3. fwrite($handle, 'my message');
  4. $response = stream_get_contents($handle);
  5. fclose($handle);
  6. ?>
  7. Download this code: /code/close-your-connection-between-stream_get_contents-calls1.txt

This code opens a socket connection to a certain host, sends 'my message' to it, and retrieves the response data using stream_get_contents. Easy!

Just a warning, though: if you send consecutive messages to the same host, using the same handle, stream_get_contents will return an empty string as the response.

I'm not sure why this happens, but I've noticed this behavior in two different use cases and can therefore safely say it's got something to do with the function, not the web service.

To prevent this from happening, just make sure you use a fresh handle each time you communicate with the remote host:

  1. <?php
  2. // send message 1...
  3. $handle = fsockopen($myHostName);
  4. fwrite($handle, 'my message');
  5. $message1 = stream_get_contents($handle);
  6. fclose($handle);
  7. // send message 2...
  8. $handle = fsockopen($myHostName);
  9. fwrite($handle, 'my second message');
  10. $message1 = stream_get_contents($handle);
  11. fclose($handle);
  12. ?>
  13. Download this code: /code/close-your-connection-between-stream_get_contents-calls2.txt

As an aside, I've been working on a handy SocketConnection class that's part of a package of classes which communicate with various social networks. More on that later. I intend to release it to the public domain, I'm just not sure yet in what form.

In the meantime, take note of this little technique, it'll save you some precious debugging time.

Back to top

Filed under PHP

Comments:

No comments have been added yet, you could be the first!

Sorry, due to spam, comments are temporarily out of order.

Back to top

Preferences

These settings will be saved for your convenience.