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

旧时模样 提交于 2019-11-28 03:55:33

问题


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 ?


回答1:


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




回答2:


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.




回答3:


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/




回答4:


Method 1.

If you are executing PHP directly from the Cron Job e.g. php /path/to/your_script.php then add the following line at the top of your PHP script:

if (php_sapi_name() !='cli') exit;

Method 2.

If the Cron Job uses wget, curl or lynx to run your script via its URL, then insert this code at the top of your PHP script (change the User Agent string to one known only by you) :

if ($_SERVER['HTTP_USER_AGENT'] != 'yourSecretAgent') exit;

You will also have to set the User Agent in the Cron Job; as in this wget example:

wget -O - --user-agent=“yourSecretAgent” http://example.com/your_script.php


来源:https://stackoverflow.com/questions/4282296/run-a-script-php-on-cron-job-on-linux-apache-server-but-restrict-public-access-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!