2012-08-13 139 views
0

我试图下载使用从PHP卷曲的图像,但不是将图像保存到它只是输出随机字符到Web浏览器屏幕的服务器,这里的代码PHP下载文件到服务器

$final['IMAGE'] = 'http://www.google.com/images/srpr/logo3w.png'; 

$imagename = trim(basename($final['IMAGE'])); 

$url = $final['IMAGE']; 
$path = '/media/import/'; 
$path .= $imagename; 

$fp = fopen($path, 'w'); 

$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_FILE, $fp); 

$data = curl_exec($ch); 

curl_close($ch); 
fclose($fp); 

回答

5

curl_exec($ch);会将输出直接打印到屏幕上。

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

查看PHP手册“curl_setopt”的详细信息:您可以使用CURLOPT_RETURNTRANSFER - 选项时,阻止他的行为。

编辑

这个小脚本文件下载到一个可写目录:

// file handler 
$file = fopen(dirname(__FILE__) . '/test.png', 'w'); 
// cURL 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,'somethinsomething.com/something.png'); 
// set cURL options 
curl_setopt($ch, CURLOPT_FAILONERROR, true); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
// set file handler option 
curl_setopt($ch, CURLOPT_FILE, $file); 
// execute cURL 
curl_exec($ch); 
// close cURL 
curl_close($ch); 
// close file 
fclose($file); 

这一次它的CURLOPT_FILE - 选项,做的伎俩。更多信息可以在以前的相同链接中找到。

+0

更改它使用curl_setopt($ ch,CURLOPT_RETURNTRANSFER,true); 仍然不会将图像下载到/ media/import /目录 – user1155594 2012-08-13 18:24:19

+0

我已更新我的答案。试一试。 – insertusernamehere 2012-08-13 18:36:39

+1

非常感谢您的回答,您可以将任何内容下载到您的服务器,并且大文件需要几秒钟的时间才能下载 – mohade 2017-09-06 20:14:11

0

如果你相信他们会png格式,你可以利用imagecreatefromstring()和imagepng():

$c = curl_init($final['IMAGE']); 
curl_setopt($c, CURLOPT_HEADER, 0); 
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); 
$binary = curl_exec($c); 
curl_close($c); 

$imagename = trim(basename($final['IMAGE'])); 
$url = $final['IMAGE']; 
$path = '/media/import/'; 
$path .= $imagename; 

$img = imagecreatefromstring($binary); 
imagepng($img, $path, 0); 
0

你可以使用复制():

copy("http://www.google.com/images/srpr/logo3w.png", "/media/import/logo3w.png"); 
+0

运行后仍然不会将文件复制到/ media/import /中的服务器,也不会出现任何错误 – user1155594 2012-08-13 18:25:46