Posted by & filed under Programming.

I’ve been using a PHP class in a project that pulls a URL and then caches the result so it doesn’t have to get loaded again until it’s considered stale. Works pretty well, but every time it went out to get a fresh copy of a page it took forever.

I was using fsockopen and fgets to read the information. Pretty standard, and normally works for me. It wasn’t until I timed a request that I caught what was happening. The request was taking just over 15 seconds. 15 seconds happens to be the timeout on my web server. So the request was happening quickly, but waiting for the server to timeout.

One little line. That’s all that was missing. I had left out a header in the request.

Connection: Close

That was it. Added that to the headers that were sent and the request went from 15+ seconds to a few tenths of a second and all is well.

Nice that the actual fix only took about 10 seconds. Too bad that it took me half an hour of Googling to figure out that was the issue.

5 Responses to “fsockopen / fgets very slow in PHP”

  1. Jackson Chao

    Hi, I’m using predis to connect my reids server, and it was very slow. I’m trying everything I can find, how to add Connection: Close in the predis libraries?


Leave a Reply

Your email address will not be published. Required fields are marked *