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

前端 未结 4 1547
再見小時候
再見小時候 2020-12-19 08:26

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

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-19 08:47

    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
    

提交回复
热议问题