Home > Enterprise >  Cannot grab picture from specific site with php, how to download image via php?
Cannot grab picture from specific site with php, how to download image via php?

Time:12-03

Cannot grab pictures from the specific site with PHP, but with PYTHON is working for this site, how to download images via PHP?

image URL is https://www.autoopt.ru/product_pictures/big/bcb/054511.jpg

If I paste another URL, of another site, the picture is downloading, but this site doesn't work.

i try with file put content and so on, my last code is

<?php

function downloadImage($img_url){

    $image = file_get_contents($img_url);
    $img_save_path = realpath(dirname(__FILE__)) . '/assets/upload_products/';
    $image_name = basename($img_url);
    $image_fullpath = $img_save_path.$image_name;

    $ch = curl_init ($img_url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $raw=curl_exec($ch);
    curl_close ($ch);
    if(file_exists($image_fullpath)){
        unlink($image_fullpath);
    }
    $fp = fopen($image_fullpath,'x');
    fwrite($fp, $raw);
    fclose($fp);
    
    return true;
}

downloadImage('https://www.autoopt.ru/product_pictures/big/bcb/054511.jpg');

CodePudding user response:

You dont need to do all that to save the picture if your going to use file_get_contents. It can be done by only using:

file_put_contents($image_fullpath, file_get_contents($img_url));

Also, like mentioned by OMi Shash in the comments, you'll need to pass header info to file_get_contents for it to work with that url. I've just done the test and it worked.

//set header info
$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n")); 
//Basically adding headers to the request
$context = stream_context_create($opts);
file_put_contents($image_fullpath, file_get_contents($img_url, false, $context));
  •  Tags:  
  • php
  • Related