繁体   English   中英

使用curl和PHP从PHP URL保存图像

[英]Saving an image from a PHP URL using curl and PHP

我试图从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);

您有什么主意使其可行吗? 请帮忙。 谢谢

<?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()调用fopen(), fwrite() and fclose()将数据写入文件。 file_put_contents

您可以将其用作功能:

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));

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

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

另外,您的URL在$URL_path但是您使用$path_img初始化cURL ,该URL根据问题中的代码未定义。

为什么要在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 );

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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