简体   繁体   中英

Unable to call CodeIgniter controller function from command line

I'm writing a cron job function and my project is built upon CodeIgniter framework . Following is my controller class ( Cron.php ) present in my authentication server.

class Cron extends CI_Controller {

    public function log_update() {

        $opts = array('http' =>
          array(
              'method' => 'GET',
              'timeout' => 10
          )
      );
      $context = stream_context_create($opts);

      $url = "http://lamp.co.uk/project/data_controller/get_log_update";

        $contents = file_get_contents($url, TRUE, $context);

      var_dump($contents);
    }
 }

And following is my Data_controller class present in my project server.

class Data_controller extends MY_Controller {

public function __construct() {
  parent::__construct();
  echo "hi ";
}

public function get_log_update() {
  echo "welcome";
}

}

When I executed php index.php cron log_update from auth server command line, only the string "hi" gets displayed instead of "hi welcome".

But it works when I call $this->get_log_update() inside the Data_controller constructor and also when I directly access the url from the browser

Have I done anything silly or is there a bigger problem.

This probably has to do with a CLI issue.

First see what happens if you use php-cli index.php cron log_update instead of php index.php cron get_log_update() (just add -cli ).

Then if that doesn't work, try wrapping your echo on a if (is_cli()) statement and see what happens. Actually, try echo "inside cli" and another echo "not cli" on an else to that if in order to get more hints on what's going on.

Please let me know if this helped.

EDIT here is a working example with is_cli:

class Rutinas extends CI_Controller {

function __construct()
{

    parent::__construct();
    $this->load->database();
    // html y url autoloaded

    if (is_cli()) {
        $this->load->model('Trips_model');
        echo "ejecutando cronjob...\r\n";
     } else {
        echo "creo que has perdido el camino...";
     }
}

//redirect if needed, otherwise display the user list
function index()
{
    if (is_cli())
     {
        $viajes_por_archivar = $this->Trips_model->trips_to_update();
        echo "Viajes archivados:\t".$update_past_trips_result;
        echo "\r\n";
        echo "Acuerdos archivados:\t".$update_lost_deals_result;
     } else {
        echo " en el index";
        // $this->output->enable_profiler(TRUE);
        // phpinfo();
     }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM