开发者

PHP retrieve and save remote image

With the following methods of retrieving files in PHP I keep on hitting an anti-hotlinking security picture rather than the image I'm looking for. The odd thing is, when I manually input the url in Firefox/IE or even Internet Download Manager I do get the correct file, so there must be something wrong with the methods I have tried so far.

file_put_contents:

file_put_contents($localpath, file_get_contents($remoteURL));

The following function didn't work either:

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($remoteURL,$localpath);

And fopen()

$tag = fopen($remoteURL, 'rb');

if($tag){
 while(!feof($tag)) {
     $imgt = $imgt . fread($tag, 1024);
 }
} 

and imagecreatefromjpeg() didn't do the trick either

function LoadJpeg($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefromjpeg(开发者_运维百科$imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a black image */
        $im  = imagecreatetruecolor(150, 30);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);

        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

Do I have any other options?


If this is not your website, then there is almost nothing you can do about it. The site has been set up to stop people scrapping their images or using them in their links.

You MAY however, be able to use a curl statement rather than file_get_contents, and if that doesn't work send some browser headers with the request using curl.

If this is your website, if your running on cPanel, there is an option in the security part. I forget exactly where.


Since you wrote that allow_url_fopen is on and function is not working, you could try the curl.

function save_image($inPath,$outPath){
    $ch = curl_init ($inPath);
    curl_setopt($ch, CURLOPT_HEADER, 0); // required
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); // required for images
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // maybe redirect on other side?
    curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3'); // or user agent checks?
    $rawdata=curl_exec($ch);
    curl_close ($ch);
    if(file_exists($outPath)){
        @unlink($outPath);
    }
    $fp = fopen($outPath,'x');
    fwrite($fp, $rawdata);
    fclose($fp);
}


There are probably some checking on their side, they're probably getting user agent, referer. Try to use for this to fake browser's behavior

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜