Friday, May 16, 2025

Restrict a PHP script so that it only runs via cron (CLI execution) OR cron based HTTP but prevent accessed from a browser (HTTP request)

 Restrict a PHP script so that it only runs via cron (CLI execution) OR cron based HTTP but prevent accessed from a browser (HTTP request)


define('APPLICATION_SERVER_IP', '123.123.123.123');

define('CRON_SECRET_KEY', 'e17Il1b9aA0Oa');


function writeToLog($message, $logLevel = 'INFO') {

    $logFile = __DIR__ . '/../logs/cron_logs.log'; // Change as needed

    if (!file_exists($logFile)) {

        touch($logFile);

        chmod($logFile, 0644);

    }

    $timestamp = date("Y-m-d H:i:s");

    $logMessage = "[$timestamp] [$logLevel] $message" . PHP_EOL;

    error_log($logMessage, 3, $logFile);

}


// Validate access

if (

    isset($_SERVER['REMOTE_ADDR'], $_GET['CRON_SECRET_KEY']) &&

    $_SERVER['REMOTE_ADDR'] === APPLICATION_SERVER_IP &&

    $_GET['CRON_SECRET_KEY'] === CRON_SECRET_KEY

) {

    echo "Safe execution";

    // Place your execution logic here

    writeToLog("Cron executed successfully.", "INFO");

} else {

    $ip = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';

    writeToLog("Unauthorized hit from IP: $ip", "WARNING");

    http_response_code(403);

    exit("You don't have permission to access.");

}

Total Pageviews