如何将图像下载到 PHP 中的文件夹


how to download images to a folder in php

我想从网址下载图像,但没有下载。请检查代码并告诉我哪里出错了。

<?php
$ch = curl_init ("http://l1.yimg.com/t/frontpage/cannes_anjelina_60.jpg");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec ($ch);
curl_close ($ch);
$fp = fopen("img.jpg",'w');
fwrite($fp, $rawdata);
fclose($fp);
?>

它工作正常,将适当的文件权限设置为应保存图像的位置。在这种情况下,它是脚本所在的文件夹,可能希望将其移动到其他位置,例如:

// where "images" folder can be written with files
// set permissions to 0755
$fp = fopen("images/img.jpg",'w');
function download_image ($url, $the_filename) {
    $cookie = tempnam ("/tmp", "CURLCOOKIE");
    $ch = curl_init ($url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Debian) Firefox/0.10.1");
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
    curl_setopt($ch, CURLOPT_ENCODING, "");
    curl_setopt($ch, CURLINFO_EFFECTIVE_URL, true);
    curl_setopt($ch, CURLOPT_REFERER, "http://tomakefast.com");
    curl_setopt($ch, CURLOPT_POST, false);
    $rawdata=curl_exec($ch);
    curl_close($ch);
    file_put_contents("../somewhere/". $the_filename, $rawdata);
}

如果您发现任何问题,请告诉我。 这偶尔会给我一个 0 字节的图像文件,但这可能由于多种原因而发生。 这可以改进为在 0 字节上返回 false,甚至可以进行基本测试以查看是否确实下载了图像。

如果你

觉得这样更好,你可以改用这个简单的代码。

$img_file = file_get_contents("http://l1.yimg.com/t/frontpage/cannes_anjelina_60.jpg");
file_put_contents("myImage.jpg", $img_file);