Try moving curlopt_followlocation line between this:

PHP Code: 
if(ini_get('safe_mode')){
    
//Paste code here

This isn't a solution but it safer code to execute. I used to have the problem with a crawler I ran on another server.