php can not copy remote file, but it downloads via browser

2

Hello. This file:

link

I can download through the browser, but I can not copy directly to my server using PHP. I have tested all possible ways (copy (), file_gets_content (), fopen (), curl (), etc) and there is no way to make it work. How should I do it?

    
asked by anonymous 10.11.2016 / 16:33

1 answer

3

What happens is the following:

Ascanbeseenfromtheimage,theserverimplementsacookie(security=true)andshouldredirecttothesameurl,ifithasthecookie,itallowsdownloading,otherwiseitgoesintotheredirectionloopuntil'seeing'thecookieintherequest.Iwonderedwhatthatwasmissingfromhisrequisition.Try%w/%ofthefollowing:

$curl=curl_init();curl_setopt($curl,CURLOPT_RETURNTRANSFER,True);curl_setopt($curl,CURLOPT_HTTPHEADER,array("Cookie: security=true"));
curl_setopt($curl, CURLOPT_URL, 'http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_megase.zip');
curl_setopt($curl,CURLOPT_USERAGENT,'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1');
$return = curl_exec($curl);
curl_close($curl);
file_put_contents('file.zip', $return);

As you can see in this way we also sent the cookie, which was what was necessary for the server to authorize the download of the file.

Here's the same request with file_get_contents :

$opts = array(
    'http' => array(
        'method'=>"GET",
        'header' => array(
            'Cookie: security=true'."\r\n",
            'User-Agent' => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1",
        )
    ),
);
$context = stream_context_create($opts);
file_put_contents('file.zip', file_get_contents('http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_megase.zip', false, $context));
    
10.11.2016 / 17:04