Come risolvere il problema fopen(): URL file-access is disabled in the server configuration

Questo problema può accadere quando si lanciano script PHP da riga di comando oppure attraverso un cron job: se il server su cui gira lo script non permette di aprire file remoti, viene mostrato l'errore

fopen(): URL file-access is disabled in the server configuration

Possiamo aggirare questo problema usando la libreria cURL, già inclusa in PHP.

$cartella = "/home/user/";
$srcfile1 = fopen("http://sito.com/file.jpg", "r");
$nomefile=basename("http://sito.com/file.jpg");
 
if (!($fp1 = fopen($cartella.$nomefile,"w")));
while ($contents = fread( $srcfile1, 8192 )) {
fwrite( $fp1, $contents, strlen($contents) );
}
 
fclose($srcfile1);
fclose($fp1);

Diventa:

$cartella = "/home/user/";
$nomefile=basename("http://sito.com/file.jpg");
 
if (function_exists('curl_init')) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, http://sito.com/file.jpg);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
  $srcfile1 = curl_exec($ch);
 
  $nomefile=basename($remotefile1);
  if (!($fp1 = fopen($cartella.$nomefile,"w")));
    fwrite( $fp1, $srcfile1, strlen($srcfile1) );
  curl_close($ch);
} else {
  echo "cURL problem on the server";
}