简体   繁体   中英

PHP file_get_contents and cURL raise http error 500 internal server

I am using a function inside a PHP class for reading images from array of URLs and writing them on local computer.

Something like below:

function ImageUpload($urls)
{
  $image_urls = explode(',', $urls);  
  foreach ($image_urls as $url)
  {
    $url = trim($url);
    $img_name = //something
    $source = file_get_contents($url);
    $handle = fopen($img_name, "w");
    fwrite($handle, $source);  
    fclose($handle);
  }
}

It successfully read and write 1 or 2 images but raise 500 Internal severs for reading 2nd or 3rd image. There is nothing important in Apache log file. Also i replace file_get_contents command with following cURL statements, but result is the same (it seems cURL reads one more image than file_get_contents ).

$ch=curl_init();        
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,500);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
$source = curl_exec($ch);
curl_close($ch);
unset($ch);

Also the problem is only for reading from http URLs, and if I have images on somewhere local, there is no problem for reading and writing them.

I have made some changed to your code, hope that helps :)

$opts = array( 
        'http' => array( 
            'method'=>"GET", 
            'header'=>"Content-Type: text/html; charset=utf-8" 
        ) 
    );

$context = stream_context_create($opts); 
$image_urls = explode(',', $urls);  
foreach ($image_urls as $url) {
    $result = file_get_contents(trim($url),TRUE,$context);
    if($result === FALSE) {
        print "Error with this URL : " . $url . "<br />";
        continue; 
    }
    $handle = fopen($img_name, "a+");
    fwrite($handle, $result);  
    fclose($handle);
}

I don't see any handler for reading in the loop , your $handle = fopen($img_name, "w"); is just for writing , you also need $handle = fopen($img_name, "r"); for reading ! because you can't read handle ( fread () ) for fopen($img_name, "w"); .

Additional answer :

Could you modify to (and see if it works):

.........
$img_name = //something
$context = stream_context_create($image_urls );
$source= file_get_contents(  $url ,false,$context);
.....
.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM