Search code examples
phpwgetfile-get-contents

Why does wget on the command line work, but file_get_contents does not?


I am trying to download the contents of an html file to my Ubuntu Linux 16.04 computer using php's get_file_contents() function. However, when I do this, I get this Warning: "failed to open stream: the , aborting"

Yet when I use wget on the terminal command line, it quickly downloads the file contents.

So why does file_get_contents not work for this? Here is my php code, which produces the Warning:

$testDownload = file_get_contents("https://ebird.org/region/US-AL-001?yr=all");

echo $testDownload;

On my Ubuntu terminal command line, here is my bash code, which works quickly and flawlessly:

wget https://ebird.org/region/US-AL-001?yr=all

I want to use php because I want to automate the downloading of a number of files and need a fair bit of code to do it, and I feel much more comfortable using php than bash.

P.S. I tried various "context" solutions for the file_get_contents function that were suggested on Stack Overflow, but they did not solve the problem.

P.P.S. I earlier tried cURL and got the same redirects Warning, though I admit to not knowing much about cURL.


Solution

  • I found a solution: the shell_exec() function in php allows me to use bash's wget command line function within my php script. I tried it and it worked. (I will have to change the ownership of the downloaded files to get access to them.) Here is the code that worked:

    $output = shell_exec('wget https://ebird.org/region/US-AL-005?yr=all');
    

    I still don't understand why wget can get the file contents but file_get_contents cannot. But with shell_exec() I have found a php solution to complete my task, so I am happy.