2012-03-21 198 views
15

如何使用php从URL下载图像(例如:https://www.google.com/images/srpr/logo3w.png)然后保存它? 这是我到目前为止,它给了我'file_put_contents'函数中的错误。使用php代码从URL下载图片?

<form method="post" action=""> 
<textarea name="text" cols="60" rows="10"> 
</textarea><br/> 
<input type="submit" class="button" value="submit" /> 
</form> 

<?php 
    $img = "no image"; 
    if (isset($_POST['text'])) 
    { 
    $content = file_get_contents($_POST['text']); 
    $img_path = '/images/'; 
    file_put_contents($img_path, $content);  
    $img = "<img src=\"".$img_path."\"/>"; 
    } 
    echo $img; 
?> 

它给我的错误:

[function.file-put-contents]: failed to open stream: No such file or directory in C:\wamp\www\img.php

/images/目录位于php文件的同一目录和可写。

+0

4分钟1答案!!希望你的问题很快解决。 – 2012-03-21 09:12:22

+0

你从未接受过任何答案?请提供并接受帮助你的答案。 – 2012-03-21 09:14:46

+0

@Rohit对不起,但我该如何接受答案? – Sarah 2012-03-21 09:23:37

回答

30

由于不提供文件名,因此无法将图像与现有代码一起保存。你需要做的是这样的:

$filenameIn = $_POST['text']; 
$filenameOut = __DIR__ . '/images/' . basename($_POST['text']); 

$contentOrFalseOnFailure = file_get_contents($filenameIn); 
$byteCountOrFalseOnFailure = file_put_contents($filenameOut, $contentOrFalseOnFailure); 
+0

感谢您的回复。我已经在代码中使用了'file_get_contents'。它工作正常,但我不能保存图像。 – Sarah 2012-03-21 09:11:12

+0

@Sarah:我的错,我误解了代码。在此期间编辑答案。 – Jon 2012-03-21 09:12:21

+0

这是我得到的错误: '[function.file-put-contents]:未能打开流:没有这样的文件或目录在C:\ wamp \ www \ img.php 14行上' – Sarah 2012-03-21 09:30:24

0

file_put_contents()要求第一个参数是文件名,而不是路径。

1

你的错误是什么?但是你有正确的方式去做你想做的事情。

只要注意一下你的代码,我可以看到file_put_contents($img_path,,但是$img_path是一个文件夹的路径。 你需要写类似:

例如

$img_path="home/downloads/my_images"; 
file_put_contents($img_path."/flower.jpg"); 
+0

感谢您的回复! 所以我需要在代码中指定图像名称? – Sarah 2012-03-21 09:12:35

+1

是的,你可以使用你的$ _POST ['文本'],但要注意内容不好。您需要清理$ _POST,然后处理它以获取图像的名称。看看[basename](http://ca3.php.net/manual/fr/function.basename.php)它可能有帮助。 – NeeL 2012-03-21 09:17:11

+0

看看乔恩的答案;) – NeeL 2012-03-21 09:18:17

0
file_put_contents($img_path, $content); 

要什么你捞出来??我认为你在getput上犯了一个错误。或错过了指定包括文件名和扩展名的完整路径

5

如果您allow_url_fopen选项设置为true:

 $url = 'http://example.com/image.php'; 
    $img = '/my/folder/flower.gif'; 
    file_put_contents($img, file_get_contents($url)); 

否则使用卷曲:

 $ch = curl_init('http://example.com/image.php'); 
    $fp = fopen('/my/folder/flower.gif', 'wb'); 
    curl_setopt($ch, CURLOPT_FILE, $fp); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_exec($ch); 
    curl_close($ch); 
    fclose($fp); 
+0

我试图用cURL,它没有工作。 谢谢反正:) – Sarah 2012-03-21 09:26:40

+0

检查天气你已经启用卷曲.. – Pushparaj 2012-03-21 10:04:48

+6

这个答案看起来很熟悉http://stackoverflow.com/questions/724391/saving-image-from-php-url – Dan 2015-06-05 20:57:38

0

我增加了一个条件,接受的答案检查图像类型如下,

if (exif_imagetype($_POST['text']) == IMAGETYPE_PNG) { 
    $filename = './images/'.basename($_POST['text']); 
    file_put_contents($filename, $content); 
} 

从上例我显示ho w在下载文件之前检查png图像并查看更多内容类型,您可以找到here