Skip to content

Instantly share code, notes, and snippets.

@agusmu
Created February 10, 2022 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agusmu/3e07b6ed7a3d4a9b7daea0e8da9ff027 to your computer and use it in GitHub Desktop.
Save agusmu/3e07b6ed7a3d4a9b7daea0e8da9ff027 to your computer and use it in GitHub Desktop.
How to prevent direct access to a cron job file in RunCloud

How to prevent direct access to a cron job file in RunCloud

Lets say I have created one php cron job file mycron.php with this content

<?php 

// my cron function start here
echo "yea! my cron is running \n";

Then I create a cron job to run this file automatically, for example

For Nginx server

/RunCloud/Packages/php74rc/bin/php /home/runcloud/webapps/myapp/mycron.php

For Openlitespeed

/usr/local/lsws/lsphp74/bin/php /home/runcloud/webapps/myapp/mycron.php

In this example, /home/runcloud/webapps/myapp is my webapp rootpath, you can change it with your own.

The cron job should work properly.

But the mycron.php file is still accessible from the browser http://yourdomain/mycron.php

If you want to make it only accessible to terminal / cronjob, not by direct access in the browser, then you have to do something.

There are some possible ways to do it, for example, you can modify your code and use php_sapi_name function to detect if it is called from terminal / cronjob.

For example

<?php 

// allow via cronjob or via cli
if (php_sapi_name() !== "cli") {
  die("invalid request");
}

// my cron function start here
echo "yea! my cron is running \n";

Now, if you try to access this file from your browser, you will see "invalid request" message in your browser.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment