Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading