Thursday, May 26, 2022

[SOLVED] how to set cron job if using codeigniter in cpanel?

Issue

I have a controller called Buy and it has a live method. How to install a cronjob if using codeigniter? I use codeigniter 4,and l use cpanel.

php - q /home/kuslon/kuslon/app/Controllers/Services/Buy.php

Solution

STEPS

  1. Create a command-line route in app/Config/Routes.php. I.e:
$routes->setDefaultNamespace('App\Controllers');
$routes->setAutoRoute(false);
// ...

$routes->cli("cli/ship-product/(:segment)", "Services\Buy::ship/$1");

// ...

Where:

cli/ship-product/(:segment) - Represents your route. The (:segment) is optional depending on if your Controller method requires an argument or not.

Buy - Represents your Controller.

ship - Represents your Controller method.

$1 - Represents the optional (:segment) to be forwarded to the first Controller method's argument if in case it requires one. You may omit it if your Controller method doesn't require any arguments.

Notice the use of CLI-only routing with the help of ->cli(...).

  1. Run your cron job.
/usr/local/bin/php -q /home/kuslon/kuslon/public/index.php cli ship-product "ed053cb1-29a4-42f2-a17e-3109fa4d80fe"

Where:

-q - Represents quiet-mode. Suppress HTTP header output.

/home/kuslon/kuslon/public/index.php - Represents the absolute path to your project's index.php file. This assumes that the first kuslon in the path represents your Cpanel username and the second kuslon represents your project root folder.

cli - Represents the first section of the command-line route you defined earlier.

ship-product - Represents the second section of the command-line route.

"ed053cb1-29a4-42f2-a17e-3109fa4d80fe" - Represents the third optional section of the command-line route that may be required by your Controller method.

  1. Sample Controller.
<?php

namespace App\Controllers\Services;

use App\Controllers\BaseController;

class Buy extends BaseController
{

    public function ship(string $uuid)
    {
//        echo  "{$uuid}";
    }

}

Resource: Running via the Command Line

Addendum:

If in case all your routes pass through an Authentication filter, you may want to exclude these command-line based routes in app/Config/Filters.php. I.e: As you may notice below, I've excluded all routes starting with cli/* from the authfilter.

<?php

namespace Config;

use App\Filters\AuthenticationFilter;
use CodeIgniter\Config\BaseConfig;

class Filters extends BaseConfig
{
    // ...
    public $aliases = [
        //...
        'authfilter' => AuthenticationFilter::class
    ];

    public $globals = [
        'before' => [
            //...
            'authfilter' => [
                'except' => ['cli/*']
            ]
        ],
        // ...
    ];
}



Answered By - steven7mwesigwa
Answer Checked By - Mildred Charles (WPSolving Admin)