我需要从PHP URL保存图像到我的PC。 假设我有一个页面http://example.com/image.php,上面只有一个“花”图像,没有别的。我如何保存这个图像从一个新名称的URL(使用PHP)?


当前回答

创建一个名为images的文件夹,位于您计划放置将要创建的php脚本的路径中。确保它对每个人都有写权限,否则脚本将无法工作(它将无法将文件上传到目录中)。

其他回答

Vartec的cURL方案对我来说并不奏效。确实,由于我的特殊问题,它有了轻微的改进。

例如,

当服务器上有重定向(比如当你试图保存facebook的个人资料图像),你将需要以下选项集:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

完整的解决方案是:

$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_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);
$content = file_get_contents('http://example.com/image.php');
file_put_contents('/my/folder/flower.jpg', $content);

如果allow_url_fopen设置为true:

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

否则使用cURL:

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

使用PHP的函数copy():

copy('http://example.com/image.php', 'local/folder/flower.jpg');

注意:这需要allow_url_fopen

$data = file_get_contents('http://example.com/image.php');
$img = imagecreatefromstring($data);
imagepng($img, 'test.png');