2013-01-03 53 views
0

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

$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

是对semicolonn的错误? –

+0

显示的错误究竟是什么? – alizahid

+0

没有任何语法错误。每当空图像保存在硬盘上,但当我尝试浏览器中的链接时,它会下载图像。 –

回答

0

你缺少一个右引号和分号在第一行:

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

另外,您的网址是$URL_path但你初始化cURL$path_img这是基于问题的代码未定义。

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

?> 
+0

由于cURL是一个更快的地狱 – Prash

+0

我已经尝试过,但它没有工作: –

+0

file_get_contests在某些服务器上可能被禁用以供外部使用 –

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

+0

请勿使用'@'运算符来隐藏错误!它*非常*慢。 – ComFreek

+0

@ComFreek是的。谢谢。 –

+1

我改进了一些代码。但为什么不使用'file_put_contents()'?这与调用'fopen(),fwrite()和fclose()'相同。 – ComFreek

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

感谢您的答复,但它不工作:( –

+0

现在就来试试,我已经加入CURLOPT_FOLLOWLOCATION ..也许您的网址触发重定向了。 –

+0

谢谢,但它不工作,我想这应该是关于服务器的一些事一边, ,而不是我打开blob从数据库写入临时文件 –