Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set
When developing a commercial project, one of the first steps to take care of during the design process, is to choose which environment suits the project most and set it up. When coding for wordpress, one of the most difficult things to take care of is not the coding itself but developing something that should work on a high number of different environments. Although it might sound weird – because the wordpress scripting language is the one and only php – environments can radically change the behaviour of your application/plugin.
The great majority of wordpress users do not really own the servers where the blog is published but rely on shared / dedicated hosting services that almost never allow customers to set/change their settings.
So when users of my social networks status updater plugin started reporting environment-dependant errors I immediately googled them to find a solution and wasn’t actually able to find a clear page that helped with the Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set error.
Curl FOLLOWLOCATION option: CURLOPT_FOLLOWLOCATION
The curl follow location option tells curl to follow a redirect header or not, if the response of the current request contains a “Location: ” instruction:
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, false);
Why would you need it? Well for example when logging into the Facebook Home page, if the login succeeded Facebook redirects the request to the user home.
If the environment in the php.ini is running php in safe mode or an open base dir is set, the CURLOPT_FOLLOWLOCATION raise a (usually visible and pretty upsetting) warning on the page.
Many php.ini directives can be set during the script runtime, but not those 2 that interfere with curl followlocation.
So how to make sure you don’t get those warnings and your application run as required?
Solution
$ch = curl_init();
if(!ini_get('safe_mode') && !ini_get("open_basedir")) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
}
...
$response = curl_exec($ch); // response of a page with a redirect
if(ini_get('safe_mode') || ini_get("open_basedir") != false) {
curl_setopt($ch, CURLOPT_URL, "http://url-of-the-redirected-response.com");
$response = curl_exec($ch);
}
Which can be translated: when setting curl options, if the system is not running in safe mode and open base dir is not set, then curl can follow redirects.
When executing requests if php is running in safe mode or any value is set as open_basedir, then execute also the request where the previous response tried to redirect to.
There’s a very nice function by contacto at hardcode dot com dot ar that follows redirects with curl, even with FOLLOWLOCATION = false.





















































