0

我试图从 PHP 链接下载图像。当我在浏览器中尝试链接时,它会下载图像。我启用了 curl 并将“allow_url_fopen”设置为 true。我已经使用了这里讨论的方法从 PHP URL 保存图像,但它没有用。我也试过“file_get_contents”,但没用。我做了一些改变,但它仍然不起作用。这是代码

$URL_path='http://…/index.php?r=Img/displaySavedImage&id=68';
$ch = curl_init ($URL_path);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
$fp = fopen($path_tosave.'temp_ticket.jpg','wb');
fwrite($fp, $raw);
fclose($fp);

你有什么想法让它起作用吗?请帮忙。谢谢

4

4 回答 4

2

您可以将其用作函数:

function getFile($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $tmp = curl_exec($ch);
    curl_close($ch);
    if ($tmp != false){
        return $tmp;
    }
}

并称之为:

$content = getFile(URL);

或将其内容保存到文件中:

file_put_contents(PATH, getFile(URL));
于 2013-01-03T16:33:10.713 回答
2
<?php
    if( ini_get('allow_url_fopen') ) {
      //set the index url
      $source  = file_get_contents('http://…/index.php?r=Img/displaySavedImage&id=68');
      $filestr = "temp_ticket.jpg";
      $fp = fopen($filestr, 'wb');
      if ($fp !== false) {
        fwrite($fp, $source);
        fclose($fp);
      }
      else {
        // File could not be opened for writing
      }
    }
    else {
      // allow_url_fopen is disabled
      // See here for more information:
      // http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen
    }
?>

这是我用来保存没有扩展名的图像(服务器生成的动态图像)。希望对你有效。只需确保文件路径位置是完全限定的并指向图像。正如@ComFreek 指出的那样,您可以使用file_put_contents相当于fopen(), fwrite() and fclose()连续调用将数据写入文件。file_put_contents

于 2013-01-03T16:31:45.950 回答
0

您在第一行缺少结束引号和分号:

$URL_path='http://…/index.php?r=Img/displaySavedImage&id=68';

此外,您的 URL 在其中,但您根据问题中的代码使用未定义的URL进行$URL_path初始化。cURL$path_img

于 2013-01-03T16:28:31.317 回答
0

为什么file_get_contents()在工作时使用 cURL?

<?php

    $img = 'http://…/index.php?r=Img/displaySavedImage&id=68';

    $data = file_get_contents( $img );

    file_put_contents( 'img.jpg', $data );

?>
于 2013-01-03T16:29:33.987 回答