Draex_
Draex_

Reputation: 3474

Codeigniter CLI access without arguments

I need to run specific job through CLI, but I can select only a file - I can't put arguments in there. Now, ho to make it work?

I've tried creating cli_job.php and running it through CLI, but it returns homepage:

<?php

/* make sure this isn't called from a web browser */
if (isset($_SERVER['REMOTE_ADDR'])) die('CLI-only access.');

/* set the controller/method path */
$_SERVER['PATH_INFO'] = $_SERVER['REQUEST_URI'] = $_SERVER['QUERY_STRING'] = '/controller/method';
$_SERVER["HTTP_HOST"] = "domain.com";
$argv = array("index.php", "controller", "method");

/* call up the framework */
include(dirname(__FILE__).'/index.php');

Thank you

Upvotes: 1

Views: 701

Answers (2)

Draex_
Draex_

Reputation: 3474

I need to specify $_SERVER['argv'] variable and fake web access by extending Input class.

<?php

/* make sure this isn't called from a web browser */
if (isset($_SERVER['REMOTE_ADDR'])) die('CLI-only access.');

$_SERVER["HTTP_HOST"] = "domain.com";
$_SERVER["argv"] = array("index.php", "controller", "module");

require("index.php");



class MY_Input extends CI_Input
{
    function is_cli_request()
    {
        return FALSE;
    }
}

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227310

If you want to run a CodeIgniter controller via CLI, you need to call it via the command line, not via include.

Try to set your CRON script to something like this:

<?php
// Set the options for the CLI script you want to call
$index = 'index.php';
$controller = 'controller';
$method = 'method';
$params = array();

// Execute the CLI script
chdir(dirname(__FILE__));
$passedParams = implode(' ', array_map('escapeshellarg', $params));
exec("php {$index} {$controller} {$method} {$passedParams}");

Check the docs for CodeIgniter's CLI here: http://ellislab.com/codeigniter/user-guide/general/cli.html

Note: This works with the latest CodeIgniter version (2.1.4), I'm not sure if it works with older versions.


UPDATE: I was looking through my old CodeIgniter project, and I found a file that may help.

<?php
   $_GET["/controller/method"] = null;
   require "index.php";
?>

I haven't tested this, but it may work. I'm not sure on the documentation for this, or even who made this file, but it was in my project, so it might work.


If all else fails, you could always do this:

file_get_contents('http://yourwebsite.com/index.php/controller/method');

Upvotes: 2

Related Questions