0

I've looked on this site to see if anyone has this exact problem to no avail. I'm trying to download a URL using file_get_contents but while it works when I type the URL of the php script into my browser, the file is not obtained when I run the script via cron.

I've put a mail command to see if anything is returned (I've removed the email addresses themselves) - the body of the email has the URL contents when I run the script directly but it is empty when run via cron

            $filen = file_get_contents( "http://forum.forteantimes.com/index.php?forums/ghosts-general.18/" );

            $to = "xxxx";
            $subject = "test";
            $from = "xxxx";

            $body=$filen;

            $headers="From: xxx\n";
            $headers.= "To: \"".$to."\" <".$to.">\n";
            $headers.= "Return-Path: <".$from.">\n";
            $headers.= "MIME-Version: 1.0\n";
            $headers.= "Content-type: text/plain; charset=utf-8\n";

            mail($to, $subject, $body, $headers);
user3713442
  • 478
  • 8
  • 22

1 Answers1

0

You may be calling a different php.ini file from the cron (i.e. PHP CLI) and the settings there could be different (for example, allow_url_fopen() may be off). You can run php --ini to check the location of php.ini and check the settings there. You can also debug directly in you file like:

try {
    file_get_contents( "http://forum.forteantimes.com/index.php?forums/ghosts-general.18/" );
}
catch (Exception $e) {
    $body = $e->getMessage();
}
  • I think you could be right about the php.ini. I forgot to mention I am running cron scripts elsewhere (ie other directories) that use file_get_contents with no problem. I tried your suggestion and get no Exceptions being thrown. – user3713442 Apr 08 '18 at 11:07
  • No, I've put the file in other directories containing other cron jobs using file_get_contents and I still get the same problem. – user3713442 Apr 08 '18 at 11:28
  • Are they remote files you are fetching in other directories? – Jake Dickerson Apr 08 '18 at 11:28
  • Yes, they are remote files. – user3713442 Apr 08 '18 at 11:33
  • Can you provide the cron you are using for this example and the cron from a working example? You could also try using CURL to isolate the problem. – Jake Dickerson Apr 08 '18 at 11:36
  • I've come up with a fix. I've used the "-c" flag to specify the location of the php.ini - which is in the same directory as the cron job. But none of the other jobs in my crontab (even the ones that grab remote files) needed the "-c" flag. It now works, but I shouldn't have had to do this. – user3713442 Apr 08 '18 at 13:02