我试图从PHP链接下载图像。当我在浏览器中尝试链接时,它会下载图像。我启用了curl并将“allow_url_fopen”设置为true。我已经使用了这里讨论的方法Saving image from 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);
你有什么想法让它有效吗?请帮忙。谢谢
答案 0 :(得分: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
答案 1 :(得分: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));
答案 2 :(得分:0)
您在第一行错过了结束语和分号:
$URL_path='http://…/index.php?r=Img/displaySavedImage&id=68';
此外,您的网址位于$URL_path
,但您使用cURL
初始化$path_img
,而{{1}}根据问题中的代码未定义。
答案 3 :(得分: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 );
?>