Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a script.php on cron job on linux/apache server but restrict public access to the php file

Tags:

php

public

cron

I have this script.php file which i want to run as a cron job on my linux/apache server.

However, i do not want public to access www.mycompanyname.com/script.php and also run the script concurrently.

How can we prevent that? How can we restrict the script to the server's access only? Is it using chmod or setting something inside .htaccess file, something along the line?

Any advice ?

like image 953
flyclassic Avatar asked Nov 26 '10 03:11

flyclassic


3 Answers

You can do this as the first line of PHP in script.php...

if (PHP_SAPI !== 'cli') {
    exit;
}

If someone hits your script via HTTP, the PHP_SAPI will be cgi I believe, and not cli, causing your script to exit straight away.

Of course, this relies on your cron calling php script.php.

You could also send...

header('HTTP/1.0 404 Not Found');

... or of course, leave it outside your web root.

like image 172
alex Avatar answered Nov 07 '22 12:11

alex


If you put the script outside of the webroot folder it will not be accessible through your webserver. e.g. your webroot is at /var/www/public_html/ you put the script.php outside of that folder, for example: /var/www/

like image 34
Populus Avatar answered Nov 07 '22 11:11

Populus


You probably have something like a public_html directory, in which you have all the phps. Just put it outside of that directory.

like image 26
cambraca Avatar answered Nov 07 '22 10:11

cambraca