4

have a cron job that is located in a folder in the normal directory.

I am trying to not allow access to this file by anyone else EXCEPT my server for running the cron job.

I tried:

order deny,allow
deny from all
allow from 127.0.0.1

But no luck. I have gone down the root of putting the cron job outside the web root but i could not get it to run no matter what me and my host tried.

Thanks.

Lovelock
  • 7,689
  • 19
  • 86
  • 186

2 Answers2

4

Two things here: (a) getting the cronjob to run, (b) access restriction.

Cronjob

New crontab entry:

*/10 * * * * /usr/bin/php /somewhere/www/cronjob.php

Set correct permissons on cronjob.php:

  • Execute flag: chmod +x /somewhere/www/cronjob.php

Access Restriction

In general, it is a good practice, to place the script files for cronjobs outside of the www path.

If you really need to place them in www, then you might protect them with an access restriction. For the webserver Apache, this would work via .htaccess, like so:

.htaccess inside /somewhere/www/:

<Files "cronjob.php">
Order Allow,Deny
Deny from all
</Files>

This protects the file cronjob.php from outside access, but allows cron to execute the file.

If nothing works, follow my step by step guide: https://stackoverflow.com/a/22744360/1163786

Community
  • 1
  • 1
Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141
  • tested that but it doesnt run. The cronjob works fine without any htaccess restrictions. What do you mean by the first part, how do i set permissions on the cronjob? – Lovelock Aug 05 '14 at 18:53
  • `chmod +x /somewhere/www/cronjob.php`. keep in mind that different users are involved here. please check the user related permissions with `chown` and `chgrp`. the web-user is often "www-data" - that's not the "cron" executing user, right... – Jens A. Koch Aug 05 '14 at 19:00
0

You can restricted the access by set the environment in crontab file

SCRIPT_RUN_ENV=mycronenv

and validte the environment string within the function:

if (get_env('SCRIPT_RUN_ENV') != 'mycronenv') {
    die('Access denied');
}

OR you can restrict the access by IP

if( $_SERVER['REMOTE_ADDR'] != $_SERVER['SERVER_ADDR'] || $_SERVER['REMOTE_ADDR'] != "127.0.0.1" ){
    die('Access denied!');
}

And you can set the permission to your scripting file through .htaccess like:

Order deny,allow
Allow from THIS_SERVER_IP
Allow from 127.0.0.1
Deny from all
Sadee
  • 3,010
  • 35
  • 36
  • I thought at the second solution and came here for better ones, still gonna use that one, it's the easiest one. – Martzy Oct 03 '20 at 22:24