Home > Mobile >  Call JSON API from within PHP Cron Job
Call JSON API from within PHP Cron Job

Time:09-27

I have a large system with an API. On the frontend, JavaScript uses AJAX to talk to the API.

I have a PHP file that runs every 5-min as a CRON job. I want this PHP code to interact with the API. All it has to submit is query-vars. All that is sent back is a single number.

For Example: https://examplesite.com/api/create?id=1&data=2 This replies with a simple number that is the SQL last-insert-id.

EXTRA: The API also needs two Session variables (user-id and system-id) Can I just start session and set them before calling the API I guess? I need the PHP script, ran by the CRON system, to talk to this API.

I have tried using cURL but no luck yet:

        //Need to add a user-id to session, does this work?
        session_start();
        $_SESSION['user-id'] = 1;

        //HOW TO CALL API FROM CRON?
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch, CURLOPT_URL, 'https://example.com/api/create?id=1&gid=2');
        //curl_setopt($ch, CURLOPT_URL, 'http://example.com/api/create?id=1&gid=2');
        curl_setopt($ch, CURLOPT_URL, 'file://../framework/api/create.php?id=1&data=2');

        $result = curl_exec($ch);
        curl_close($ch);
        
        $result = str_replace("\n", '', $result); // remove new lines
        $result = str_replace("\r", '', $result); // remove carriage returns
        
        //Expect Result to be a number only
        file_put_contents("curl.log", "[".date('Y-m-d H:i:s')."] $result\n\n", FILE_APPEND);

The file method doesn't seem to work... maybe path issue with ../ The http method doesn't seem to work... server loopback issue?

Any advice on how to best have my PHP CRON robot use my API will be much appreciated. I have simply copied API code into the CRON, but then I am duplicating code, and not allowing the robot to test the real API.

Thanks.

CodePudding user response:

Assuming you still wanted to use a session. Your first curl should be a request that to a script that will create the SESSION then respond.

I created this get_cookie.php this to test this concept:

<?php
session_start();
$_SESSION['time'] = time();
echo 'Time=' . $_SESSION['time'];
?>

I called this script to get the PHPSESSID from the response cookie

$ch = curl_init('http://example.com/get_cookie.php');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

$skip = intval(curl_getinfo($ch, CURLINFO_HEADER_SIZE)); 
$head = substr($response,0,$skip);
$data = substr($response,$skip);
$end = 0;
$start = strpos($head,'Set-Cookie: ',$end);
$start  = 12;
$end = strpos($head,';',$start );
$cookie = substr($head,$start ,$end-$start );
file_put_contents('cookie.txt',$cookie);
echo "\ncookie=$cookie";
echo "\n$data\n";

RESPONSE:

cookie=PHPSESSID=bc65c95468d08dd02cc5ab8ab87bbd39
Time=1664237484

The CRON job URL, session.php:

<?php
session_start();
echo 'Time=' . $_SESSION['time'];
?>

This is the CRON job script.

$cookie = file_get_contents('cookie.txt');
$ch = curl_init('http://example.com/session.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIE, $cookie );
curl_setopt($ch, CURLOPT_HEADER, false);
$response = curl_exec($ch);
echo $response;

RESPONSE:

Time=1664237484

The result "Time" ($_SESSION['TIME']) is always the same as the time from the get_cookie.php.

CodePudding user response:

Thanks for the help, but in the end my alternate approach will be easiest and work best. Here is the answer for others in need...

To have an external PHP (run via CRON) test an internal PHP API (that the frontend JavaScript usually talks to via AJAX), this is the easiest solution, including passing query-variables and session-vars.

STEP 1: Don't worry about start_session() or passing any query variables, just add what you need to the arrays ahead of time.

STEP 2: Capture the output buffer and simply include the PHP API file:

        $_SESSION['user-id'] = ' works! ';
        $_REQUEST['var']     = ' too ';

        ob_start();
        include '/var/www/sitename.com/framework/api/create.php';
        $result = ob_get_contents();
        ob_end_clean();              

        file_put_contents("/var/www/sitename.com/cron/curl.log", "[".date('Y-m-d H:i:s')."] Result: $result\n\n", FILE_APPEND);

        /* OUTPUT in curl.log:
        [2022-09-26 22:30:01] Result:  works! / too 
        */

        /* create.php API
        $user = $_SESSION['user-id']??' did not work ';
        $req  = $_REQUEST['var'    ]??' novar ';
        echo $user.'/'.$req;
        */

(obviously the CRON has to be on the same server as the website/api, otherwise you will have to use cURL with Cookie/Session/QueryVar-Arrays)

  • Related