Noman Ali Noman Ali - 1 month ago 11
PHP Question

Could not download image using php (bad request)

iam trying to download image from an url, tried multiple methods (almost every method i found on google) but not yet succeeded,
Some solutions gives error

Found Document has been moved here


and most solutions gives error

file_get_content: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request


One of the solutions i'v tried so far (there are more than 25 i have tried)

$fp = fopen ('mydirectory/image.jpg', 'w+'); // open file handle

$ch = curl_init('https://www.otakusmash.com/read-manga/mangas/AIKI/008/Aiki_v02_c08_000.jpg');
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
curl_setopt($ch, CURLOPT_FILE, $fp); // output to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000); // some large value to allow curl to run for a long time
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable this line to see debug prints
curl_exec($ch);
curl_close($ch); // closing curl handle
fclose($fp);


Please help me out

Answer

You have a error in your code, Please use below code

$fp = fopen ("mydirectory/image.jpg", 'w+');              // open file handle

$ch = curl_init('https://www.otakusmash.com/read-manga/mangas/AIKI/008/Aiki_v02_c08_000.jpg');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
curl_setopt($ch, CURLOPT_FILE, $fp);          // output to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000);      // some large value to allow curl to run for a long time
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_setopt($ch, CURLOPT_VERBOSE, true);   // Enable this line to see debug prints
curl_exec($ch);
curl_close($ch);                              // closing curl handle
fclose($fp);