Technology Blog

How to execute PHP scripts automatically using Cron + Curl


There are times when you need to schedule some daily or weekly task to be executed on the server side, like mass mailing, heavy mysql queries or generate content for your webpage, in those cases the best thing you could do is use Linux cronjobs. So, on this post I will show you how to execute a php script using cronjobs with curl tool.

Cronjobs are tasks handled by the Unix/Linux cron daemon, which is constantly checking if you have pending crons, when the exact time you scheduled is happening, then the cron will execute all the commands you scheduled, at the date and time you specified. This is the basic way crons work on Unix/Linux, if you need more information read this.

Curl on the other hand is a tool that will allow you to execute remote php scripts without any issue, it’s very easy to use and supports many popular protocols like HTTP, HTTPS, FTP, FTPS, SCP, SFTP, IMAP, POP3, SMPT, etc. If your Linux/Unix distribution doesn’t have curl installed, you can grab a copy from here: Let’s begin.

First, let’s try to use curl with a simple URL, let’s say Mr Google:


You can also send the output to a file, example:

 curl > google.html

How can I execute a php script using curl?

 curl http://localhost/myscript.php

If you need to login into a protected area, curl also can pass the username and password information on the same command to execute scripts behind admin areas, example:

 curl -u username:password http://localhost/protected/massmail.php

Now that you know how to use curl, let’s add a cronjob so you can schedule your tasks:

Suggestion: in order to execute your scripts from a cronjob without any issues, you may need to grab the full path of your curl binary, which is located usually at: /usr/bin/curl, type ‘which curl’ to know where it is located.

Now, type:

 nano -w /var/spool/cron/root

or type

 crontab -e

Now add your desired cronjob, example of hourly cronjob:

 01 * * * * /usr/bin/curl -u username:password


 01 * * * * /usr/bin/curl

Remember to read the full man page and documentatin for cron and curl to fully understand how this two tools work: