从PHP URL保存图像

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


#1楼

参见file() PHP手册服务器

$url    = 'http://mixednews.ru/wp-content/uploads/2011/10/0ed9320413f3ba172471860e77b15587.jpg';
$img    = 'miki.png';
$file   = file($url);
$result = file_put_contents($img, $file)

#2楼

我没法使任何其余解决方案起做用,但我可以使用wget: curl

$tempDir = '/download/file/here';
$finalDir = '/keep/file/here';
$imageUrl = 'http://www.example.com/image.jpg';

exec("cd $tempDir && wget --quiet $imageUrl");

if (!file_exists("$tempDir/image.jpg")) {
    throw new Exception('Failed while trying to download image');
}

if (rename("$tempDir/image.jpg", "$finalDir/new-image-name.jpg") === false) {
    throw new Exception('Failed while trying to move image file from temp dir to final dir');
}

#3楼

建立一个名为images的文件夹,该文件夹位于您计划放置要建立的php脚本的路径中。 确保它具备每一个人的写权限,不然脚本将没法工做(它将没法将文件上载到目录中)。 ui


#4楼

Vartec对 cURL 的回答对我不起做用。 因为个人具体问题,它确实略有改善。 url

例如, spa

当服务器上有重定向时(例如当您尝试保存Facebook我的资料图像时),您将须要如下选项集: code

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

完整的解决方案变为: get

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

#5楼

$data = file_get_contents('http://example.com/image.php');
$img = imagecreatefromstring($data);
imagepng($img, 'test.png');
相关文章
相关标签/搜索