2

Is there a way to call a script from a cron job only and make it so no other ips can run that script?

I have a script that sends notifications to phones. It is supposed to be called by a cron job once day, but sometimes something triggers it and everyone gets notified when they shouldn't. I would like to limit it to be called from my server only.

In other words to make it not to be able to be called from a browser or a spider etc..

Thanks

Papa De Beau
  • 3,744
  • 18
  • 79
  • 137

3 Answers3

4

I'd suggest that you don't make this file available publicly.

But to answer your question directly; A way to do this is to add the following check:

if (php_sapi_name() === 'cli') {...}

More info: https://secure.php.net/manual/en/function.php-sapi-name.php

maaudet
  • 2,338
  • 4
  • 20
  • 28
  • wow, this sounds amazing. ok I am trying changing the permissions to 640 to see if that will work. We will find out tomorrow. Thanks for the great tip. – Papa De Beau May 06 '16 at 07:08
2

Your script seems to be available via public URL. Move it somewhere else. For example, if the script is within /www/site.com/public/script.php, and /www/site.com/public is the public directory of the Web server, move it to some /www/site.com/cron/script.php. Make sure that the Web server is not configured to fetch files from the cron directory.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
1

As others have written, there may be other setups you could use, (permissions and file locations) however, I've never been someone who tells someone to re-engineer their whole process to meet a single need. That feels too much like the tail wagging the dog. Therefore, if you wish to have a script that can only be executed by your cron job and not mistakenly by another process, I would offer you this solution


The php_sapi solution has been noted to provide inconsistent behavior and is system configuration specific (for example echo it's output when calling your script from the command line, and again when calling from a cron). This can lead to tracking down other bugs. The best solution I have seen and used, is to pass a command line argument to your script and evaluate the existence of that argument.

your cron job would look something like:

 * * * * * * php /path/to/script --cron

Then, inside your script you would perform an if check, that when not satisfied, stops the script.

if( $argv[0] != 'cron')
{
    //NO CRON ARGUMENT SUPPLIED, SOMETHING ELSE MUST BE CALLING THIS
    exit;
}

Take not that some systems may use the first argument as the script name, so based on your individual system configuration, you may need to check $argv[1]

Hope this helps, let me know if you have any questions, I'm happy to respond or edit if needed.

Danoweb
  • 423
  • 2
  • 9