0

I am trying to download an image from the internet to my local folder:

$loc = "downloaded images/".basename($_POST["url"]);
if(file_put_contents($loc,file_get_contents($_POST["url"])));
    echo "Downloaded successfully";
else
    echo error_get_last()['message'];

The code works only in my local server. When I ran the code in my live server, this huge warning keeps popping up in my console:

Warning: file_get_contents(https://neindiabroadcast.com/wp-content/uploads/2022/11/20221122_071752.jpg): Failed to open stream: Connection timed out in

I have also tried using cURL:

set_time_limit(0); // unlimited max execution time

$loc = "downloaded images/".basename($_POST["url"]);
$host = $_POST["url"];

$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 28800);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_REFERER, $host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
    
$fp = fopen($loc, 'wb');
fwrite($fp, $result);
fclose($fp);

When I try to open the file, it says the file is corrupted. What's surprising is that, both the codes work perfectly only when I try them in my local server.

My max_execution_time is set to unlimited, so the time required to execute shouldn't be the issue here. Then why is this issue occurring? Please help me in resolving this issue

  • Try to use [cURL to get response headers](https://stackoverflow.com/questions/9183178/can-php-curl-retrieve-response-headers-and-body-in-a-single-request) to see that if it is 200 or not. On both local and real server. If it is not 200 on live server, it is possible that your server blocked network. – vee Nov 24 '22 at 06:19
  • I get 200 response status in both local and live servers. Only somehow the file gets downloaded in local server, but doesn't in live server –  Nov 24 '22 at 06:30
  • If your url from the form is `https://neindiabroadcast.com/wp-content/uploads/2022/11/20221122_071752.jpg`, try to set this url directly in the code. Download with your cURL code. open the file, if it is corrupted then try to open with text editor such as notepad++ to see what is its content. – vee Nov 24 '22 at 06:41

1 Answers1

0

After hours of struggling, I finally came up with a solution. Every website has a no CORS policy which is kind of a security feature, where the server won't allow you to read the data of that website. To bypass this, all you have to do is to use a proxy url:

var proxy_url = 'https://api.codetabs.com/v1/proxy?quest=';

Prepend this url to the url of the website whose data you want to fetch, and you are done :)