Writing a cron job using CodeIgniter CLI? - php

Hi I am facing some problems in writing a cron job using CI CLI way. My application has a controller name called manager.php in that there is method called check_status where I am gonna get all the order_ids using one model function. Ever order_id row had a status filed in database which either success or failure.
I have an api if i pass order_id to that it will tell whether order is successfully delivered or not. But here comes the problem I have below line in controller in the top.
<?php if(! defined('BASEPATH') ) exit("NO Direct Script Access Allowed"); ?>
So when i try to run method check_status from CLI in CI it gives me an error stating NO Direct Script Access Allowed.
This is the way i called above method php application/controllers/manager.php check_status
So i decided like this i created an another class file called cron_job.php in that i didn't keep the above error line "No Direct Script Access Allowed". I thought it will give access now when i try to run but it doesn't give an error and even output also.
This is the class which i created and method in that.
<?php
class Cron_job extends CI_Controller {
public function message($to = 'World')
{
echo "Hello {$to}!".PHP_EOL;
}
}
?>
I run this controller form CLI like this php application/controller/cron_job.php message
Note: I am in ROOT directory.
No Output at all. So i tried in another way like this php index.php application/controller/cron_job.php message
Now it gives me error stating that Error 404 page not found.
What i tried in another way now i created a file in views folder and in that i am calling old controller/method url like below.
$result = file_get_contents("http://application_path/controller/method");
echo $result;
Now i am getting output which i defined in the method check_status in manager.php controller.
But here comes another problem now after the above line i will get an array output which had all the order_ids.
I am gonna send this each id to a api to check status. If it is failure it will check whether it is delivered or not. If it's done i need to update that status in the database against that order_id. But now i am in view file, is it possible to call a model file from the view file or is there any way to do this.
Any help?
Note: There is no syntax errors in any controller or any method , which are fully verified and working normally when i am accessing using urls.

You need to read the CodeIgniter help section on Running via the Command Line. It's very easy. Your original approach was correct. But you do not call your controller method directly by its path, instead CD to your project root and then the call the index.php file with the controller and method as parameters.
// This is how you call CI via the command line.
// Use spaces between index.php and your arguments.
$ php index.php <controller> <method> [params]
// And in your instance
$ php index.php manager check_status [param1 param2 param3]
Depending on your host you may need to call the PHP version compiled for CLI.

the ci helper will help you in this.
1 ) Create a helper & create a function in it, that calls your model function
function getUserDetails($userId = '') {
$CI = & get_instance();
$getUserDetailsByUserId = $CI->user_model->getUserDetailsByUserId($userId);
return $getUserDetailsByUserId;
}
2) Now you can call getUserDetails($userId); in your view.

Related

How laravel classes are included?

I want to run custom php code in laravel directly without using any routes or http requests..
I hope I can make it clear, I mean, like those online tools that runs php code by writing php code in browser, and then run it, and view result..
I found this handy project (Run-PHP-Code) to run PHP in browser directly, but I can't use models of my laravel project in PHP code..
How can I include laravel 's environment, so that I can for example:
$tag= new Tag;
where Tag is a model in laravel project, that would result into:
Fatal error: Class 'Tag' not found in D:\xampp\htdocs\widgetsRepository\app\controllers\Run-PHP-Code-master\index.php(49) : eval()'d code on line 3
Any idea? this would be very useful!
EDIT
I tried Brian suggestion at his answer, but I got this error now:
Call to a member function connection() on null
at vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php
public static function resolveConnection($connection = null)
{
return static::$resolver->connection($connection);
}
so, I think I only need to get database sorted, then I can do experiments easily..
I've never tried to run code from a laravel project directly, I just copy and paste parts of the code into Run PHP Code.
That being said, it should be possible to run the code using the method taken from this StackOverflow question:
The Composer autoload script, to autoload all of your classes:
require __DIR__.'/../bootstrap/autoload.php';
And if you need things from the IoC container, you'll:
$app = require_once __DIR__.'/../bootstrap/start.php';
Then you will be able to do things like:
$post = Post::find(1);

How to use Ajax with jQuery in Laravel 4?

I am brand new to Laravel 4 and seeing if I can convert my website over to it (previously written without a framework). I can't get AJAX (via jQuery) to interact properly with my controller.
So firstly, the controller I am working in is called IndexController.php and has a function called types which is shown below:
class IndexController extends BaseController {
// Other controller functions
public function types($brand) {
$types = DB::select('select * from aircraft_types where brand_id = ?', array($brand));
echo json_encode($types);
}
}
The function returns the data from the database (in JSON format). I have then created a route to this controller and function as follows:
Route::get('types/{id}', array('uses'=>'IndexController#types'));
I have doubled checked that the route and function are working by going to //localhost/lavarel/public/types/1 and indeed it returns the correct JSON data.
The jquery function in question is below:
function updateTypes($brand) {
$("#type").append('<option value="test">Test...</option>'); // This executes correctly
$.getJSON('/types/'+$brand, function(data) {
$("#type").append('<option value="test 2">Test 2...</option>'); // This does not
// Some other JSON related code
});
To test where the function works, I have inserted two lines which edit the item I am using. The function is being called correctly as the first 'Test' option is being appended. However, it never seems to activate the callback function as the second line of test code is not executed.
I suspect the issue is the URL I am providing to JavaScript '/types/'+$brand. I have seen in some tutorials a BASE var used before the URL I provide, but I don't see why my code above wouldn't work. Any pointers?
Can anyone explain to me where I am going wrong?
Your base path to your laravel project is localhost/laravel/public/ but your AJAX-request goes to just localhost. There're some methods for fixing this.
Method 1:
This is the most preffered method. (in my opinion)
Instead of using nginx, apache for starting a web server, you can use PHP's built in web server.
Open a terminal window (or cmd in Windows), cd into the main directory for your project (the one with vendor, app and public directories) and type the command php artisan serve. This will create a PHP-server on localhost:8000 and your base path will be /.
There's a lot of options, for example php artisan help serve" if you want to see them all.
After you've done so your code should work.
Method 2
If you want to use nginx or apache you should add a virtualhost for your project.
That can be done though the configs.
Apache: http://httpd.apache.org/docs/current/vhosts/examples.html
Nginx: http://wiki.nginx.org/ServerBlockExample
After that you should add a new entry to the hosts file.
Method 3
As you said you could add a BASE variable before the '/types/'+$brand.
Your request goes to localhost/types/$brand.
It should go to localhost/laravel/public/types/$brand.
Just replace '/types/'$brand with '/laravel/public/types'+$brand
Use HTML 'base' meta tag
<!doctype html>
<html lang="en">
<head>
...
<base href="{{ URL::to('/') }}"/>
...
Declaring this tag, you ensure that every relative URL will be based on project's real, absolute URL (http://localhost/my-laravel-project/public/), not on Localhost's URL (http://localhost)

CodeIgniter, Know the controller which called function

I am trying to create library that will write "error" messages in database, I do not think that I will be able to write PHPs errors nor CodeIgniters, but I can write my own "errors" something like
$this->error->write("User is not allowed to go in here");
I know there is a error handling already built in CodeIgniter on top of all it only supports writing errors/infos/debugs in file not database.
The real question is: how to get controller that called function.
Lets say I am in controller -> ./admin/settings.php and error ocures, code will call my library and I want it to store controller that called it. (I may be forced to send it as parameter but I don't want to write manually that it was fcn("error text", "/settings.php");
Assumed output: /controllers/admin/settings.php somewhere inside class that is called by controller.
You can use the router class to get this info
Also works with Codeigniter v3.0.x
To get the controller(class)
$this->router->class
To get the method(function)
$this->router->method

Codeigniter app returns blank output in CLI

I'm setting up my cron job controller that will only run within the CLI, I've not started with anything built, just in the testing phase with CI's examples. However, when running it I get no output or anything else, just a new line, this is the command I ran:
root#serv$ php /var/www/ci/index.php tools message
root#serv
As you can see in the second line, I get no output, just a new line to run an command but I don't understand why and I cannot debug it. The code contains this:
<?php
class Tools extends CI_Controller {
public function message($to = 'World')
{
echo "Hello {$to}!".PHP_EOL;
}
}
?>
In my configuration file, the $config['uri_protocol'] is set to AUTO so this does not seem to be the problem.
How can I debug this? What are the options that I may need to deal with?
I also have display_errors on and error_reporting on to E_ALL.
I found the problem, it was a problem with a redirect('domain.com'); exit; I had on an autoloaded library, because it was matching against the domain in a database, that way CLI doesn't serve a domain when it detects, hence I included a redirect('domain.com') with an exit which is why I'm not seeing any output.
I also encountered this while i was playing w/ cli for codeigniter. It took me a while to troubleshoot the issue and found out that I forgot to except my controller on my login model which runs a redirect function.
This may be a silly suggestion, but might as well give it a shot... #lolwut, what if instead of using "echo", maybe you have to "return" the output?
I have an application following this guide: http://codeigniter.com/wiki/Category:Advanced::CronScript running (and producing output). CI was only 1.7.2 when I did so, but it might still hold
(CodeIgniter 2.2.0)
Add a route in /application/config/routes.php
for...
<?php
class Cron extends CI_Controller
{
public function process_dumps()
{
echo "Processing dumps..." . PHP_EOL;
}
}
?>
add...
$route['cron/process_dumps'] = 'cron/process_dumps'
Without this line there was no output on the CLI!
I think you can find the answer in the Codeigniter Wiki.
By calling to the cron.php with parameters controller and function, and then define CRON_CI_INDEX to the refer to the file path of your main index.php.
For example,
php /var/www/ci/cron.php --run=/tools/message

CodeIgniter: Can't Get My New Controller/View To Show

I am learning how to use codeIgniter as my php framework. I am reading through the documentation and watching the intro video and just generally following along with the first tutorial, but it's not working for me.
I have created a controller called "test.php" and a view called "test_view". The controller for this class is exactly like "welcome.php" and the view file just has some static html. However, when I go to index.php/test I get a 404 error.
I have also tried manipulating the original welcome files so that instead of calling a view it just echos "testing", yet I still see the original welcome message! I've tried clearing my browsing cash and refreshing, but to no avail.
Any suggestions? Thanks.
Edit: Here's the code for controllers/test.php
<?php
class Test extends Controller {
//Just trying to get it to echo test
public function index()
{
echo "test";
//$this->load->view('test_view');
}
}
?>
Try looking at this page in the documentation - this might solve your problem.
This basically means you should try typing index.php?/test/ instead (notice the question-mark).
First of all, check the above link. Might be useful.
If not, then...
Try changing the default controller in the config file ('routes.php') to something else (probably, to 'test'), then try loading index.php. Just to test whether the whole system works (or not).
Check whether mod_rewrite is loaded (in your server .conf-file, if you're using Apache).
Try using the latest build of the framework. AFAIK, the name of the controller class for now is "CI_Controller".
Finally, try removing the word 'public' before the declaration of the function. AFAIR, CI enable you to make private functions in controllers just by using prefix (which is set in the config file) at the beginning of the name of the function (thus making all the other functions public).
But most certainly the problem is with the mod_rewrite. If not, try debugging with die('Page found'); instead of echo - this will allow you to track possible redirects on the page.

Categories