Showing posts with label api. Show all posts
Showing posts with label api. Show all posts

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.");

}

Saturday, August 6, 2016

Why API/ file(url) request is not working/sending in cpanel / php

One of my web apps using API for SMS. I was using to send request as URL using file() function. Everything was working till i transfered my apps to another server. In new server it was not working even it was not sending the request.

I found from phpinfo() that allow_url_fopen was disable. To use file related php build-in function
like  fopen()copy()file_exists() , readfile()file() , file_get_contents() ,filesize() We need to make sure that  allow_url_fopen  is enabled.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

allow_url_fopen, how to enable

This can be done via your php.ini file by adding the following line:
allow_url_fopen = On
The php.ini file is where you declare changes to your PHP settings. You can edit the existing php.ini, or create a new text file in any subdirectory and name it php.ini.

Total Pageviews