How to get base url in pre_controller hook in codeigniter - codeigniter

I am working on hook file, i am using pre_controller function of hook, but when i tried to use base_url() function in it, it is not working for me, it give me this error Call to undefined function base_url(), can anyone please help me to resolve this error ? here i have added my whole function
$hook['pre_controller'] = function()
{
$this->CI = get_instance();
$ci =& get_instance();
$router =& load_class('Router', 'core','uri','url');
$controller_name = $router->fetch_class();
$action_name = $router->fetch_method();
$segement = $router->uri->segment(2);
echo base_url(); die;
try {
$rc = new ReflectionClass($controller_name);
} catch (Exception $ex) {
if($segement == "") {
echo base_url(); die;
//header("Location:".$controller_name.'/overview');
//redirect($controller_name.'/overview');
//exit;
}
}
};

This won't work because base_url() gets initialized if a Controller is loaded.
And pre_controller basically means the opposite.
There are two options for you
Option 1
create a PreControllerHook.php in your application/hooks/ directory.
class PreControllerHook extends CI_Controller
{
public function initialize()
{
$controller_name = $this->router->fetch_class();
//... and so on
}
}
Setup your hooks.php config
$hook['pre_controller'] = [
[
'class' => 'PreControllerHook',
'function' => 'initialize',
'filename' => 'PreControllerHook.php',
'filepath' => 'hooks'
[
];
Option 2
create a PostControllerConstructorHook.php in your application/hooks/ directory.
class PostControllerConstructorHook
{
public function initialize()
{
$ci = get_instance();
$controller_name = $ci->router->fetch_class();
//... and so on
}
}
Setup your hooks.php config
$hook['post_controller_constructor'] = [
[
'class' => 'PostControllerConstructorHook',
'function' => 'initialize',
'filename' => 'PostControllerConstructorHook.php',
'filepath' => 'hooks'
[
];
You can find more information on their official documentation page here.

i hope this will work for you
base_url() function not working in codeigniter

Related

Hooks in login page gives error localhost redirected you too many times

I am getting error -
localhost redirected you too many times.
in hooks
This is my code in hooks.I am unable to resolve this issue please help me
and please explain how to use hooks in ci and i am using post_controller_constructor
<?php
class Example {
private $CI;
function __construct()
{
$this->CI =& get_instance();
if(!isset($this->CI->session)){ //Check if session lib is loaded or not
$this->CI->load->library('session'); //If not loaded, then load it here
}
//echo "class".$this->CI->router->class; die;
if ( $this->CI->router->class == 'student' )
{
return;
}
}
public function check_login()
{
echo $session_userdata = $this->CI->session->userdata('email');
echo "session data".$session_userdata;
// die;
if(empty($session_userdata)) {
redirect("student/index");
}
else {
echo "here";
}
}
}
?>
i'm guessing your hook array looks like
$hook['post_controller_constructor'] = array(
array(
'class' => 'Example',
'function' => 'check_login',
'filename' => 'Example.php',
'filepath' => 'hooks'
),
);
It doesn't really matter whether you return anything in your constructor or not - a constructor serves only one purpose - to instantiate their respective class.
So basically you have to do something like
class Example {
private $CI;
function __construct()
{
$this->CI =& get_instance();
if(!isset($this->CI->session)){ //Check if session lib is loaded or not
$this->CI->load->library('session'); //If not loaded, then load it here
}
}
public function check_login()
{
echo $session_userdata = $this->CI->session->userdata('email');
echo "session data".$session_userdata;
// die;
if(empty($session_userdata) && $this->CI->router->class !== 'student') {
redirect("student/index");
}
else {
echo "here";
}
}
}
First of all, if you are using hooks in the CodeIgniter for the first time then follow some steps.
Step1: Enabling Hooks
The hooks feature can be globally enabled in the application/config/config.php file
Open config.php file does following replaces
$config['enable_hooks'] = FALSE;
To
$config['enable_hooks'] = TRUE;
Step2: Defining a Hook
Hooks are defined in the application/config/hooks.php file.
$hook['post_controller'] = array(
'class' => 'firstHookFile',
'function' => 'checkHook',
'filename' => 'firstHookFile.php',
'filepath' => 'hooks'
);
Step3: Create hook file
Create file in the application/hooks.
<?php
class firstHookFile
{
public function checkHook()
{
// load the instance
$this->CI =& get_instance();
$this->CI->load->helper('uri');
echo base_url();
return;
}
}
?>
This hook is only for example purpose, this hook will return the base URL of your project.
I hope you have understood how to use hooks in Codeigniter.

Laravel 5 create middleware with oauth2 server check

I have implemented this oauth server http://bshaffer.github.io/oauth2-server-php-docs/
It has a Laravel implementation : http://bshaffer.github.io/oauth2-server-php-docs/cookbook/laravel/
This guide you and gives that code for routes :
App::singleton('oauth2', function() {
$storage = new OAuth2\Storage\Pdo(array('dsn' => 'mysql:dbname=oauth2;host=localhost', 'username' => 'root', 'password' => 'root'));
$server = new OAuth2\Server($storage);
$server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage));
$server->addGrantType(new OAuth2\GrantType\UserCredentials($storage));
return $server;
});
Route::get('private', function()
{
$bridgedRequest = OAuth2\HttpFoundationBridge\Request::createFromRequest(Request::instance());
$bridgedResponse = new OAuth2\HttpFoundationBridge\Response();
// fix for laravel
$bridgedRequest->request = new \Symfony\Component\HttpFoundation\ParameterBag();
$rawHeaders = getallheaders();
if (isset($rawHeaders["Authorization"])) {
$authorizationHeader = $rawHeaders["Authorization"];
$bridgedRequest->headers->add([ 'Authorization' => $authorizationHeader]);
}
if (App::make('oauth2')->verifyResourceRequest($bridgedRequest, $bridgedResponse)) {
$token = App::make('oauth2')->getAccessTokenData($bridgedRequest);
return Response::json(array(
'private' => 'stuff',
'user_id' => $token['user_id'],
'client' => $token['client_id'],
'expires' => $token['expires'],
));
}
else {
return Response::json(array(
'error' => 'Unauthorized'
), $bridgedResponse->getStatusCode());
}
});
It works perfectly well like that. Now I want to transform that check function in the "private" route to a middleware I could apply to each necessary route. I created the middleware using
php artisan make:middleware AuthChecker
Added it to the kernel.php, and pasted the code of the verification function inside of it. And I immediately got an error :
FatalErrorException in AuthChecker.php line 17:
Class 'Oauth2\HttpFoundationBridge\Request' not found
So, I guess I will have to "use" things, but since I'm still a beginner I don't really know what to do...
Thanks ahead for your help !
[EDIT] the content of the middleware currently look like this :
namespace App\Http\Middleware;
use Closure;
class OauthCheck {
public function handle($request, Closure $next)
{
$bridgedRequest = OAuth2\HttpFoundationBridge\Request::createFromRequest($request);
$bridgedResponse = new OAuth2\HttpFoundationBridge\Response();
// fix for laravel
$bridgedRequest->request = new \Symfony\Component\HttpFoundation\ParameterBag();
$rawHeaders = getallheaders();
if (isset($rawHeaders["Authorization"])) {
$authorizationHeader = $rawHeaders["Authorization"];
$bridgedRequest->headers->add([ 'Authorization' => $authorizationHeader]);
}
if (App::make('oauth2')->verifyResourceRequest($bridgedRequest, $bridgedResponse)) {
$token = App::make('oauth2')->getAccessTokenData($bridgedRequest);
return Response::json(array(
'private' => 'stuff',
'user_id' => $token['user_id'],
'client' => $token['client_id'],
'expires' => $token['expires'],
));
return $next($request);
}
else {
return Response::json(array(
'error' => 'Unauthorized'
), $bridgedResponse->getStatusCode());
}
}
}
Thanks again
FatalErrorException in AuthChecker.php line 17:
Class 'Oauth2\HttpFoundationBridge\Request' not found
So you want to use the Request class from Oauth2\HttpFoundationBridge namespace to your OauthCheck class from App\Http\Middleware.
You can do it in either ways:
Import the class
namespace App\Http\Middleware;
use Oauth2\HttpFoundationBridge\Request;
class OauthCheck {
public function handle($request, Closure $next)
{
$bridgedRequest = Request::createFromRequest($request);
....
}
}
Use the class explicitly
namespace App\Http\Middleware;
class OauthCheck {
public function handle($request, Closure $next)
{
$bridgedRequest = \Oauth2\HttpFoundationBridge\Request::createFromRequest($request);
....
}
}
Take note of the backslash before Oauth2\HttpFoundationBridge\Request. If you just say $bridgedRequest = Oauth2\HttpFoundationBridge\Request, then PHP will look for App\Http\Middleware\Oauth2\HttpFoundationBridge\Request.

Codeigniter redirect method is not working

This is my User.php controller
I am unable to use redirect method.
i am working on xampp localhost
?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
$this->load->library('Admin_layout');
$this->config->load('reg_rules');
$this->load->model('admin/user_model');
$this->load->helper('form');
$this->load->helper('url');
}
public function index()
{
if (!$this->auth->loggedin()) {
redirect('admin/login');
}
}
public function add(){
//if($this->input->post('submit')){
$this->form_validation->set_rules($this->config->item('reg_settings'));
$data["reg_attrib"] = $this->config->item("reg_attribute");
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run('submit') == FALSE)
{
// templating
$this->admin_layout->set_title('Add a User');
$this->admin_layout->view('admin/add_user',$data["reg_attrib"]);
// templating
}
else
{
// Develop the array of post data and send to the model.
$passw = $this->input->post('password');
$hashpassword = $this->hash($passw);
$user_data = array(
'name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'phone' => $this->input->post('contact_no'),
'email' => $this->input->post('email'),
'password' => $this->hash($hashpassword),
'doj' => time(),
);
$user_id = $this->user_model->create_user($user_data);
Here i am setting my success message using set_flashdata
and redirecting
if($user_id){
$this->session->set_flashdata('item', 'Record created successfully');
$this->redirect('admin/user/add','refresh');
}else{
echo "User Registration Failed!";
}
}//else
//} // submit
} // add
}
View_users.php
<?php
if($this->session->flashdata('item'))
{
echo $message = $this->session->flashdata('item');
}
?>
I am getting the following error
Fatal error: Call to undefined method User::redirect() in C:\xampp\htdocs\ci\application\controllers\admin\User.php on line 67
A PHP Error was encountered
Severity: Error
Message: Call to undefined method User::redirect()
Filename: admin/User.php
Line Number: 67
Backtrace:
Try to change from
$this->redirect('admin/user/add','refresh');
to
redirect('admin/user/add','refresh');
Hope it will be useful for you.

Phalcon: HMVC view not working

I got a problem rendering nested view, here is what I'm trying to do
I changed your 'request' of HMVC (HMVC-GitHub or/and HMVC-Pattern) function into an Elements module
namespace Modules\Main\Libraries;
/**
* Elements
*
* Helps to build UI elements for the application
*/
class Elements extends \Phalcon\Mvc\User\Component
{
public function loadModule($path = '', $data = array()) {
$di = clone $this->getDI();
$dispatcher = $di->get('dispatcher');
$paths = explode('/', $path);
$data = is_array($data) ? $data : array($data);
// get controller name
if (isset($paths[0])) {
$controller = $paths[0];
}
// get action name
if (isset($paths[1])) {
$action = $paths[1];
}
// get params
if (isset($paths[2])) {
array_splice($paths, 0, 2);
$params = array_merge($paths, $data);
} else {
$params = $data;
}
if (!empty($controller)) {
$dispatcher->setControllerName($controller);
} else {
$dispatcher->setControllerName('index');
}
if (!empty($action)) {
$dispatcher->setActionName($action);
} else {
$dispatcher->setActionName('index');
}
if (!empty($params)) {
if(is_array($params)) {
$dispatcher->setParams($params);
} else {
$dispatcher->setParams((array) $params);
}
} else {
$dispatcher->setParams(array());
}
$dispatcher->dispatch();
$response = $dispatcher->getReturnedValue();
if ($response instanceof ResponseInterface) {
return $response->getContent();
}
return $response;
}
}
and I have 2 controllers:
namespace Modules\Main\Controllers;
class IndexController extends ControllerBase
{
public function indexAction()
{
$secondContent = $this->elements->loadModule('test/hello/json');
$this->view->setVar('secondContent', $secondContent);
}
}
and
namespace Modules\Main\Controllers;
use \Phalcon\Http\Response;
class TestController extends ControllerBase
{
public function indexAction()
{
}
public function helloAction($format='html', $param = 'empty')
{
$this->view->setVar('content', 'Hello this is test value "'.$param.'"');
$content = $this->view->getContent();
return (string)$content;
// return 'Hello this is test value "'.$param.'"';
}
}
my DI
$di['elements'] = function() {
return new \Modules\Main\Libraries\Elements();
};
Views files
IndexController::Index
<h1>Congratulations!</h1>
<p>You're now flying with Phalcon. Great things are about to happen!</p>
<p>Second content: {{ secondContent}}</p>
<p>HMVC: {{ elements.loadModule('test/hello/json', 'test') }}</p>
and HelloController::test
This is :: {{ content }}
expecting to get
Congratulations!
You're now flying with Phalcon. Great things are about to happen!
Second content: This is :: Hello this is test value "empty"
HMVC: This is :: Hello this is test value "test"
but it only rendering the HelloController (First call from IndexController::indexAction):
This is :: Hello this is test value "empty"
if I change IndexController::indexAction to
public function indexAction()
{
$secondContent = '';
$this->view->setVar('secondContent', $secondContent);
}
and TestController::helloAction to
public function helloAction($format='html', $param = 'empty')
{
$this->view->setVar('content', 'Hello this is test value "'.$param.'"');
$content = $this->view->getContent();
//return (string) $content;
return 'Hello this is test value "'.$param.'"';
}
the result that i get is (Second content is empty):
Congratulations!
You're now flying with Phalcon. Great things are about to happen!
Second content:
HMVC: Hello this is test value "test"
Any solution to solve this ?
Thanks,
Helman
Phalcon have built-it modules feature, you dont have to built your own module loader, you just need create module bootstrap that extend ModuleDefinitionInterface.
Just take a look this sample from phalcon multi module
https://github.com/phalcon/mvc/tree/master/multiple
this example below is taken from link above, This contain module bootstrap code.
<?php
namespace Multiple\Frontend;
class Module
{
public function registerAutoloaders()
{
$loader = new \Phalcon\Loader();
$loader->registerNamespaces(array(
'Multiple\Frontend\Controllers' => '../apps/frontend/controllers/',
'Multiple\Frontend\Models' => '../apps/frontend/models/',
));
$loader->register();
}
/**
* Register the services here to make them general or register in the ModuleDefinition to make them module-specific
*/
public function registerServices($di)
{
//Registering a dispatcher
$di->set('dispatcher', function () {
$dispatcher = new \Phalcon\Mvc\Dispatcher();
//Attach a event listener to the dispatcher
$eventManager = new \Phalcon\Events\Manager();
$eventManager->attach('dispatch', new \Acl('frontend'));
$dispatcher->setEventsManager($eventManager);
$dispatcher->setDefaultNamespace("Multiple\Frontend\Controllers\\");
return $dispatcher;
});
//Registering the view component
$di->set('view', function () {
$view = new \Phalcon\Mvc\View();
$view->setViewsDir('../apps/frontend/views/');
return $view;
});
$di->set('db', function () {
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
});
}
}
you can load module using this code below
$app = new \Phalcon\Mvc\Application();
$app->registerModules(array(
'frontend' => array(
'className' => 'Multiple\Frontend\Module',
'path' => '../apps/frontend/Module.php'
),
'backend' => array(
'className' => 'Multiple\Backend\Module',
'path' => '../apps/backend/Module.php'
)
));

Is it possible to have global class variables in CodeIgniter?

I am developing an application in CodeIgniter that has a member login system. I have a model that gets all the information of a requested member.
class Member extends CI_Model {
var $info = array();
var $error = NULL;
function __construct(){
parent::__construct();
}
public function get_info($member_id = ''){
$this->db->where('member_id', $member_id);
$this->db->limit(1);
$query = $this->db->get('members');
if($query->num_rows() > 0){
$member = $query->row_array();
$info = array(
'id' => $member['member_id'],
'display_name' => $member['display_name'],
'email_address' => $member['email_address'],
'password' => $member['password'],
'status' => ($member['status'] == 0) ? FALSE : TRUE,
'activation_code' => $member['activation_code'],
'location' => $member['location'],
'date_joined' => date('M jS, Y', $member['date_joined']),
'gender' => ($member['gender'] == 0) ? 'Male' : 'Female',
'results_per_page' => $member['results_per_page'],
'admin_emails' => ($member['admin_emails'] == 0) ? FALSE : TRUE,
'member_emails' => ($member['member_emails'] == 0) ? FALSE : TRUE
);
$this->info = $info;
} else {
$this->error = 'The member you requested could not be found in our database.';
}
}
At the top of my controllers and other models, I use the following to get the information of the current user to pass it along to all of the methods.
function __construct(){
parent::__construct();
$this->member->get_info($this->session->userdata('member_id'));
$this->user = $this->member->info;
}
function index(){
if($this->user['id'] > 0){
echo "You are logged in!";
} else {
echo "You are NOT logged in!";
}
}
Is there a way to do this on a global scale? It's kind of tiresome to type out the construct code at the top of every controller.
So I managed to find another post here on StackOverflow that solved my problem.
enter link description here
In application/core, I extended the existing Controller and Model classes with a few additions. Then I had to change my controllers and models to suit.
class Home extends MY_Controller {
}
application/core/MY_Model.php
class MY_Model extends CI_Model {
var $user = array();
function __construct(){
parent::__construct();
$this->load->model('member');
$this->member->get_info($this->session->userdata('member_id'));
$this->user = $this->member->info;
}
}
application/core/MY_Controller.php
class MY_Controller extends CI_Controller {
var $user = array();
function __construct(){
parent::__construct();
$this->load->model('member');
$this->member->get_info($this->session->userdata('member_id'));
$this->user = $this->member->info;
}
}
In construct simply try to access session data
function __construct() {
if($this->session->userdata('member_id')) {
echo 'You are logged in';
} else {
echo 'You are not logged in';
}
}
It is simple rather than getting all the data and selecting 'user id',if we check whether ths session data is there then a user is logged in orelse no one is logged.You can add this at your each controller construct function and you can check without help of any DB

Resources