Search code examples
phpcron-task

Getting cron job error because of <?php tag


I've set up a cron job to run. It executes a php file which is named cronj.php But it doesn't work and cron job notification I get is:

/root/website/myworld/blabla/cronj.php: line 1: ?php: No such file or directory

And line 1 in that file is simply a php tag <?php I don't know how


Solution

  • Cron is executing the file as if it was a shell script. Normally you would put in a shebang line (like #!/usr/bin/env php) at the top of the file so that the shell knows how to invoke it, but PHP doesn't like it - as it outputs everything outside its tags. Thus, instead of this:

    0     3     *     *     *         /mypath/myscript.php ...
    

    try this:

    0     3     *     *     *         /usr/bin/env php /mypath/myscript.php ...
    

    or use @Ravenex's trick.

    EDIT I was just rightly admonished for assuming PHP behaves in a consistent way. Apparently, shebang does work in PHP. My apologies to @chess007.