0

I was using file_get_contents(trim($fileUrl)); to get content of an image, and it worked before.

Now that there is a redirect on the source url the code breaks and i get this error

Failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden

i tried adding context but same thing.

$context = stream_context_create(
                    array (
                        'http' => array (
                            'follow_location' => true,
                            'max_redirects' => 20
                        )
                    )
                );
                
                $binary = file_get_contents(trim($fileUrl), false, $context);

i tried using curl like so

$url = trim($fileUrl);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_HEADER, true);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Moved? Fear not, we'll chase it!
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Because you want the result as a string
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $res = curl_exec($ch);
                //$rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
                curl_close($ch) ;
                dd($res);

and i still get a 403. here is the cURL response

HTTP/1.1 403 Forbidden
Server: xxxxxxx
Date: Fri, 28 Apr 2023 13:34:58 GMT
Content-Type: text/html
Content-Length: 568
Connection: keep-alive

<html>
<head><title>403 Forbidden</title></head>
<body bgcolor=\"white\">
<center><h1>403 Forbidden</h1></center>
</body>
</html>

But when i open the url on the browser, it works fine.

I noticed on the browser the "response header" there is the location to the new url too.

Any idea what i'm doing wrong? or how to fix this? thank you.

Shaho
  • 157
  • 3
  • 15
  • *"and i still get a 403. But when i open the url on the browser"* - sounds like whatever you hit does not like curl. try sending request with browser's [`user-agent`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent). – Bagus Tesa Apr 28 '23 at 11:37
  • i tried adding this, `curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.1 Safari/537.11');` and got the same thing. 403 error. – Shaho Apr 28 '23 at 11:43
  • maybe cookies? there are [many ways to defeat curl spiders](https://stackoverflow.com/questions/9391137/can-servers-block-curl-requests). – Bagus Tesa Apr 30 '23 at 08:17

0 Answers0