从PHP URL保存图像

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

回答(9)

2 years ago

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

2 years ago

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

2 years ago

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

2 years ago

在这里,示例将远程图像保存到image.jpg .

function save_image($inPath,$outPath)
{ //Download images from remote server
    $in=    fopen($inPath, "rb");
    $out=   fopen($outPath, "wb");
    while ($chunk = fread($in,8192))
    {
        fwrite($out, $chunk, 8192);
    }
    fclose($in);
    fclose($out);
}

save_image('http://www.someimagesite.com/img.jpg','image.jpg');

2 years ago

Vartec's answercURL对我不起作用 . 由于我的具体问题,它确实略有改善 .

e.g.,

当服务器上有重定向时(例如当您尝试保存Facebook Profiles 图像时),您将需要以下选项集:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

The full solution becomes:

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

2 years ago

我无法使任何其他解决方案工作,但我能够使用wget:

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

2 years ago

$img_file='http://www.somedomain.com/someimage.jpg'

$img_file=file_get_contents($img_file);

$file_loc=$_SERVER['DOCUMENT_ROOT'].'/some_dir/test.jpg';

$file_handler=fopen($file_loc,'w');

if(fwrite($file_handler,$img_file)==false){
    echo 'error';
}

fclose($file_handler);

2 years ago

file()PHP Manual

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

2 years ago

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