Search code examples
phpmysqlcurlupdating

Schedule PHP script to execute via cron


I have a script that will update some columns on my database. It is written in PHP, I execute it via URL (eg. http://foo.com/xyz/yzx/dbupt8r). I did this using crontab -e then curl on the script URL, because on my mind it is like somehow similar of what I am doing: accessing it via URL. Is there any advisable or better way of doing this? Am I at security or threat flaws?


Solution

  • There are two ways to do this, the way that you're already doing it: (curling a publicly accessible URL); or executing the PHP script directly from your crontab.

    Cron Curling

    As you mentioned, this is often very convenient and comfortable since you're already developing a web application in PHP and so it's the way you're already working. There are a few risks:

    • Most importantly, security: You'll want to ensure that input is properly filtered, there are no risks of SQL injection, etc., in case someone discovers the URL and tries to take advantage of it. Hopefully you're covering most of this anyway since you're developing a web application.
    • Frequency & concurrency: You're scheduling it's execution from cron, so are there any issues if someone else starts calling the URL and making it fire more frequently or at the same time as a scheduled run is occurring?
    • Relying on curl: It also means you're relying on curl to execute your script, so you're opening yourself up to many points of failure (curl itself, DNS, etc.).

    Running PHP from Cron

    Alternatively, you may be able to run the script directly from your crontab. There are two ways of doing this:

    • Passing the PHP script to the PHP interpreter binary, which would look something like this (note the path to your PHP binary varies by platform, but should be specified as an absolute path as cron doesn't have access to many environment variables):

      */15 * * * *    /usr/bin/php -f /path/to/php/script.php
      
    • Alternatively, you can add a hashbang/shebang line to the first line of the PHP script as follows:

      #!/usr/bin/php
      

      Make it executable, for example:

      chmod 755 /path/to/php/script.php
      

      And add it directly to your crontab:

      */15 * * * *    /path/to/php/script.php
      

    The advantages of this method are that you can put the script in a location that's not publicly accessible so you can ensure tighter control over its access & execution. It may also mean you can write lighter code if you don't have to handle the web side of things. That said, if you're using a PHP framework, you may find it difficult to develop a stand-alone script such as this.