Easy way to protect cronjobs?

I have multiple cron jobs that run every day. They are just single scripts stored in the root of the site. I have to have it in the main website root because the site has to be able to move from one host to another. So with that said, what is an easy way to make sure only the cron schedule has access to the script and not just anyone who might come across the script? Perhaps just require a passphrase and pass it via the cron path and check for that?

if (substr(php_sapi_name(),3) !== 'cli') { die(); }
2 Likes

Alternatively, if you are not using CLI to run your scripts (for example, with wget via http) then you can check the IP address of the remote client:

if ($_SERVER["REMOTE_ADDR"] != $_SERVER["SERVER_ADDR"]) {
  // not cron
}

You could also create a new user on the box and giving that user the correct permissions to run the script. You would then need to log into that user before being able to do anything.

Do I need to add anything in the php cron script or cron command path so it knows its for cli? Or will it automatically know that when the php script is called via the cron task scheduler, it will have cli in the php_sapi_name?

Thanks!

CLI is Command Line Interface. CLI is what you’re using when you type “php myscriptname.php” into the command line (hence, CLI), which would be what the cron is doing.

Note that this form of ‘protection’ does NOT prevent someone who has command line access to the server from executing the script.

@StarLion shouldn’t this be

if (substr(php_sapi_name(), 0, 3) !== 'cli') { die(); }

?

… yes, it should. Good catch.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.