PHP Curl Users — Do Read this

I use PHP Curl to fetch weather data from Forecast.io — Totally Amazing service but it was down for 2–3 hours, 2 days ago; It happened just once in 2 years of my usage.
So when this Weather API was down rest of the website also gone down! I Panicked. Checked my web server, database server. Everything was solid.
But when I tested on another computer the website was running fine, as long as I don’t go to the page where Curl was used. When I visit that Curl page it goes down again, but only on this computer until Curl request is finished.
So I was sure that PHP Sessions are the issue here.
What normally happens is: When we do session_start(); and after that any long operation like Curl occurs so until this operation ends, if we visit the same page again the code will stuck at session_start(); until the previous operation completes.
In simple words,
session_start();waits until the previous page is completely executed.
To avoid this issue. We can close our session before any long operation and then restart it after it ends. Like this:
<?php
//before running long operation
if (session_status() == PHP_SESSION_ACTIVE) {
session_write_close(); //close session if it’s active
$weClosedSession = true;
}//long operation like Curl goes hereif (!empty($weClosedSession)){
session_start(); //reopen session if we closed it :)
}
Please note that when you do session_write_close() you can not write session until you start it again, but you can read session without any issue.
Simple Reminder:
This is only useful if you are using PHP Sessions. Otherwise your code will run just fine :)
If you like this article then please click the heart icon below :) Thanks for reading!
