file-get-content-cron

File_Get_Contents in CRON Job

Written by | Date Updated: November 13, 2019
file-get-content-cron

If you are having difficulty executing the PHP file_get_contents within a CRON job, this quick post may be just what you’re looking for.

File_Get_Contents Not Working in CRON Job: What is Happening?

So, in a particular circumstance that I just had with a client, they were running a CRON job that executed the PHP file_get_contents similar to the code below:

 $homepage=file_get_contents('http://www.example.com/'); 

This CRON job had been working fine for years and, suddenly, it was not working.

I asked: “Well, can you tell me what has changed because things generally don’t change on their own?”

“Ah,” they replied: “we just upgraded to PHP 7.3”.

Hmmm, odd. I checked the latest PHP documentation. And, while it’s true that many things had to be modified to work in PHP 7.3, I did not see any updates regarding file_get_contents with PHP 7.3.

After some experimentation, I ran the file in the browser and all worked fine. Then, after the CRON job ran again, I checked the database that was supposed to be updated with the file_get_contents data and…nada.

The database was showing updates, but the updates were blank. So, this meant that the CRON was running but it wasn’t getting the data from the web address listing in the file_get_contents command.

Some online solutions mentioned file paths and timeout issues but none of that seemed relevant to this situation.

I asked the customer again: “So, aside from your PHP upgrade, nothing else changed?”

“Oh yeah,” they mentioned: “One other thing. We upgraded our web server.”

Ah-hah. Now, we’re getting somewhere.

Sure enough, upon checking their PHP configuration, they had new default settings that prevented file_get_contents from functioning in a CRON environment.

This particular setting for file_get_contents to function in a CRON environment is called allow_url_fopen.

You must enable it as you see in the photo below:

file-get-contents-CRON-solution

And that’s it. After doing this, the file_get_contents command in your CRON job will work as you intended.

If you do not have the ability to edit your PHP configuration, send the photo above to your web host or web server administrator and they should be able to get it configured for you.

Hope this helps! Cheers, Richard

Richard Cummings

Director of SEO, Social Media, and Web Content Development at The SEO System
Richard Cummings has been practicing online marketing for many years and has setup and optimized hundreds of WordPress sites.He founded The SEO System to provide SEO, social media, and online marketing services and software to businesses.

Latest posts by Richard Cummings (see all)

Richard CummingsFile_Get_Contents in CRON Job