Using CodeIgniter with normal PHP sessions, where to add session_start(); - php

I'm having some trouble using CodeIgniters implementation of sessions getting deleted after a redirect so I'm reverting to normal PHP sessions.
Where would the best place for session_start(); be, assuming I want it called on every page without adding it to every controller constructor?
I'd guess putting it at the top of main index.php would be would work ok, would just like to make sure that doing this doesn't break anything or if there's a better/standard place to put it?

This is why I always use an extended controller that contains application wide code.
To extend the codeigniter controller, place this code in a file called MY_Controller.php and save it to the core folder.
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
session_start();
}
}
If you decide to use this solution all your controllers will need to extend MY_Controller.
Creating Core System Classes

YOu can easily put them in index.php. THis is the entry point to your codeigniter application and is called on every request.
although this is generally not recommended becuase when you upgrade your codeigniter versions you will need to remember to copy your customizations to index.php.
instead of index.php, you could use a prerequest hook

You cannot use session_start(); directly in codeigniter.
Instead you must use:
$this->library->load('session');
$this->session->set_userdata(array('name' => 'name','age' =>
'age','etc' => 'etc');

Related

Where can I put my global code in Kohana 3.3?

Say I want a constant, a function or a class to be available in all my models, views and controllers code (within a particular web site (application)). Where can I put them? I don't mind importing them explicitly in every file I need them in but I don't know how (simple require_once does not seem to work).
You can put them in the vendor folder (in application/vendor or modules/MOD/vendor). Then you can load it like this:
require Kohana::find_file('vendor', 'folder/file','ext');
You can read up more on this in the user guide
Now, it should be stated you should in general not use functions or globals.
I declare Constants in Bootstrap.php and create my own Helpers for general functions under application/classes/Helpers.
If you need to integrate a third party library into Kohana or want to make code available to other Kohana users consider creating a module instead.
You can define all your constants in new php file and place it in the application/classes directory. In your Template controller or in the main controller like Welcome or Website, just place the code in the __constructor()
require_once Kohana::find_file( 'classes', 'filename' );
I suggest you to put your constant variables in the bootstrap.php file because this is loaded by the framework before every request.
You can simply put your classes in the root of the classes directory, the framework will find.
This worked well for me...
In application/config/constants.php:
define('SOME_COOL_CONSTANT', 'foo');
return array();
In index.php:
Kohana::$config->load('constants');
SOME_COOL_CONSTANT should then be available globally.

How to call a zend controller action from an independent php file?

I am having a controller IndexController.php in which action is something like this
class IndexController extends CustomControllerAction {
public function preDispatch() {
if (!$this->view->authenticated) {
$this->_redirect('/users/login');
}
}
public function indexemailAction() {
//somecode which calculates certain things
}
}
NOw,I need to call the action "indexmailAction" inside the IndexController.php with an independent php file
The php file is indextest.php
<?php
//Need to write some code to call indexmailAction in IndexController.php
?>
What should I write in this file ......
Thanks in advance
I know this is a few years old, and this may not be the intended use of the classes/functions, but I've found the following quite useful in isolated files that are called from the command line.
The problem this solves for me is that it eliminates spawning of Apache processes. The solution is great because I can access the some Controller/Action needed that I would from the URL.
In almost any ZF1 based app, you can copy your index file and keep everything the same and just comment out the following line.
$application->run();
Anything below this line you can access with your autoloaders etc. It's crude, but it works. Unfortunately, you'll soon find yourself with limited access to a lot of the files your application has, and the feeling the only way you can access the files needed is through a Controller/Action.
Instead, I use the following in a new file below $application->bootstrap() ( still removing the $application->run() ):
$front = Zend_Controller_Front::getInstance();
// You can put more here if you use non-default modules
$front->setControllerDirectory(array(
'default' => APPLICATION_PATH.'/controllers'
));
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setNeverRender(true);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
$req = new Zend_Controller_Request_Http("http://anydomain.tld/controller/action");
// Example just to see how this can be extended
$req->setParam("someVar", "someValue");
$front->setRequest($req);
$front->dispatch();
In the end you have a isolated PHP file that bootstraps everything the same as your main index.php for the web, but you can manually trigger a controller/action as needed, giving you easier access to the rest of the files with how ZF1 intended you to access them.
Controllers are designed to be used in an MVC, not by scripts. Your controller should assemble request variables, direct them to models and return an HTTP response of some sort. Your scripts should act directly on the models instead.
Anyhow, if you insist, you can instantiate a controller class and call methods just like any other class as long as you inject any dependencies that the MVC would have.
If you want logic used in multiple places in your actions, then it should go in an action helper or if very generic code, then in a custom library (/library/custom/)
NB: The authentication would be better suited in a plugin rather than the pre-dispatch method in every controller.
You should not have to call a controller action for this, your logic should reside in your models. Then you can create a new instance of your model and invoke the appropriate methods. example :
require_once '/path/to/mymodel.php';
$mymodel = new Mymodel();
$data = $mymodele->fetchAll();
PS: Maybe you should think of creating a restful api to handle calls from outside your application
UPDATE:
ok, I see now what you need, The best way to achieve it is to call a url instead of a file (e.g. website.com/emails/send), if you are worried about security you can use some preshared key to make sure the request comes from you, send it with the request and check if it's correct in your action.

Is there an easy way to apply logging (e.g. Zend_Log) to Zend_Controller_Action_Helper_Redirector?

I've got an application which seems to be stuck in a redirect loop when I put it in a subdirectory of my server (e.g. blah.com/testing/ instead of blah.com/), despite sharing the same code. I think I've handled the redirection stuff incorrectly, but Apache's debugging output doesn't actually list the redirections, because they're being handled inside PHP.
Is there an easy way to attach a logger to the redirection function?
class My_Controller_Action_Helper_Redirector extends Zend_Controller_Action_Helper_Redirector
{
protected function _redirect($url)
{
$this->myPrettyLoggingFunction();
parent::_redirect($url);
}
}
if My_ namespace configured right, this plugin will be loaded by PluginLoader instead of default Zend_Controller_Action_Helper_Redirector
usage - standard way $this->_helper->redirector(...)

adding new library in CodeIgniter

I've just started learning CodeIgniter, and I'm following this authentication tutorial by nettuts+. I did not understand one thing in it:
He added the following constructor code in the Welcome controller, which basically can be accessed only if the Session has variable username, otherwise it will redirect to admin controller.
function __construct()
{
session_start();
parent::__construct();
if ( !isset($_SESSION['username'])){
redirect('admin');
}
}
He said:
If you have multiple controllers, then
instead of adding the above code in
every controller, you should Create a
new library, which extends the
controller you will paste the code in,
and autoload the library into
project. That way this code runs
always when a controller is loaded.
Does it mean, I should
Create a file in application/libraries (eg. auth.php)
Paste this code in the auth.php
.
if ( !isset($_SESSION['username'])){
redirect('admin');
}
Now how to autoload this library and make it run every time a controller is loaded as he said?
Thanks
1) to autoload a library, just add it to the array in the file application/config/autoload.php, look for the 'library' section and paste the name of the library(without extension) there, as an element of the array.
$autoload['libraries'] = array ('auth');
2) I suggest you use the native session handler (session library), which works pretty well and avoids you to use php $_SESSION. You set a width $this->session->set_userdata(array('username' => 'User1', 'logged' => 'true'), and then you retrieve the values with $this->session->userdata['logged'], for ex.
Works like a charm and don't have to call session_start() and so on. Go check the help because it's really really clear on that.
3) As for your problem, I'll go, instead, for 'hooks'. There are different hooks, depending on their 'position', i.e. the moment in which you're calling them.
You can use, for ex.. the 'post_controller_constructor', which is called after controller initialization but BEFORE the methods, so it's in a midway between the constructor and the actual method. I usually insert this controls here.
You define hooks in application/config/hooks.php, and give them an array:
$hook['post_controller_constructor'] = array(
'class' => 'Auth',
'function' => 'check',
'filename' => 'auth.php',
filepath' => 'hooks',
'params' => array()
);
Anyway, for all these needs, the docs are pretty clear and straightforward, I suggest you read about hooks and session and you'll see everything gets much clearer!
The other way to do this. This is what he means in tutorial.
Create a library called MY_Controller in your application/libraries folder and extend it from CI_Controller:
Class MY_Controller extends CI_Controller {
public function __construct()
{
parent::__construct();
// do the stuff you want to execute on every page.
// like auth.
}
}
Autoload the auth class in autoload.php config file. There is no need to autoload MY_Controller CodeIgniter will automaticly recognise it and run it. You can also load the Auth library within MY_Controller
Extend your controllers with MY_Controller class. (Not CI_Controller)
Extending your controller will give to more control of your project. You can add extra methods to use everywhere on your project.
For more information about extending native libraries of CodeIgniter check Creating Libraries: CodeIgniter.
Add the new library to the autoload library array in config/autoload.php.
$autoload['libraries'] = array ('database', 'session', 'auth');
Then when you want to call the function in controller constructors use $this->auth->function_name();.
You may want to make it a hook if there's a lot of repeat functionality that you don't want to call in every single constructor.

Loading custom classes in CodeIgniter?

Just starting to use CodeIgniter, and I'd like to import some of my old classes for use in a new project. However, I don't want to modify them too much to fit into the CI way of doing things, and I'd like to be able to continue to use NetBeans' autocomplete functionality, which doesn't work too well with CI.
So, what is the best way to load custom classes & class files into CodeIgniter without having to use the library/model loading mechanisms?
I apologise if this is something I should be able to find quickly, but I can't seem to find what I'm after. Everything I see is just telling me how to go through CI.
To do it codeigniter way, place your custom classes in libraries folder of codeigniter. And then use it by adding that class as library in your controller like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Someclass {
public function some_function()
{
}
}
/* End of file Someclass.php */
using in controller:
$this->load->library('someclass');
checkout complete article at http://www.codeigniter.com/user_guide/general/creating_libraries.html
Libraries are easy to write but they have a few restrictions. Constructors can only take an array as a parameter and it's assumed that only one class will exist per file.
You can include any of your own classes to work with them however you want, as this is only PHP ofc :)
include APPPATH . 'classes/foo.php';
$foo = new Foo;
Or set up an __autoload() function in your config.php (best place for it to be) and you can have access to your classes without having to include them.
I'd say you at least write a wrapper class that could require the classes and instantiate the objects and make them accessible. Then you could probably autoload such library and use it as needed.
I would recommend that you at least tried to have them fit in the CI way, as moving forward this will make you life much more easy. I've been in kind of the same position and learned just this along the way.
require_once(PHYSICAL_BASE_URL . 'system/application/controllers/abc.php');
$report= new abc();
Next use the function detail in abc contoller:
$mark=$report->detail($user);
If you're just starting to use CodeIgniter, maybe you ought to check Kohana (http://kohanaframework.org/). It is very similar to CodeIgniter in many ways but it loads classes in the normal way (using new ClassName()) so Netbeans' autocompletion features should works normally.

Categories