How to Execute a PHP File Automatically

PHP works as a server-side scripting language designed specifically for Web-based applications. Typically, a script runs when a user executes it in their Web browser. However, there are many instances where one might want a script to run at a designated time, not solely when a user executes it. This can be done by using the crontab program. Crontab allows you to run a scheduled task at a designated time. Programmers can configure crontab to run PHP scripts from the command line automatically, without having a user run it.

Things You'll Need

  • Web server with PHP installed
  • Crontab
  • PHP script
Show More

Instructions

    • 1

      Run the script from the command line. This ensures there are no errors in the script. It can be accomplished by typing: "php <file>." For example, if your filename is myscript.php, run the command "php myscript.php."

    • 2

      Open the Crontab configuration file. Use your favorite text editor (i.e., vim, pico, etc.) and open /etc/crontab. This is where cronjobs for the computer are setup.

    • 3

      Add the cronjob. Before adding a cronjob, decide how frequently you want your script to run. The default syntax for a cronjob is "* * * * /etc/cron.hourly." The * represents the minutes (asterisk 1), the hour (asterisk 2), the day of the month (asterisk 3) and the command to run (asterisk 4). For example, if you want to run the script "/public_html/myscript.php" daily at 8:17 am, you would add the line: "17 8 * * /public_html/myscript.php".

    • 4

      Test your cronjob. Whatever time you have your cronjob setup to run, be sure to test it to make sure you have it configured properly.

Tips & Warnings

  • Crontab uses military time.

Related Searches:

References

Resources

Comments

You May Also Like

Related Ads

Featured