precontroller hooks in codeigniter - codeigniter

I am using pre-controller hook codeigniter in my project
Description:
we are using subdomain concept and three templates(theme). eg: My site is xyz.com. this is having one first template.
some business signup with this xyz site. for eg. abc(business). We create abc.xyz.com. abc chooses 2 template. abc.xyz.com in browser need to show 2nd template. It is not showing 2nd template. it is showing only 1st template.
When we clicked any link on the site more than once , then the template 2 is set for abc.xyz.com link.
I am using codeigniter. loaded session, database in autoload files.
I used precontroller hook to check whether the url is xyz or any subdomain abc.xyz.com
In hook i am setting template if the url is subdomain one.
But template is not showing when abc.xyz.com is in browser. when i refresh the url for some clicks or clicked any of the header link some count , it showing the actual template of the business abc.
Please help me to fix this issue or provide me some solution .
<?php
class Subdomain_check extends CI_Controller{
public function __construct(){
parent::__construct();
$this->CI =& get_instance();
if (!isset($this->CI->session))
{
$this->CI->load->library('session');
}
}
function checking()
{
$subdomain_arr = explode('.', $_SERVER['HTTP_HOST']); //creates the various parts
if($subdomain_arr[0] == 'www')
{
$subdomain_name = $subdomain_arr[1]; //2ND Part
}
else
{
$subdomain_name = $subdomain_arr[0]; // FIRST Part
}
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
if( $subdomain_name != 'xyz' )
{
$where = array();
$where['subdomain_name'] = $subdomain_name;
$where['status'] = 1;
$this->db->from('subdomain_map');
$this->db->where($where);
$query = $this->db->get();
if($query->num_rows() < 1)
{
header('Location:http://xyz.com/index.php?/error');
}
else
{
$result = $query->row_array();
$this->CI->session->set_userdata('subdomain_id',$result['subdomain_id']);
$this->CI->session->set_userdata('subdomain_name',$result['subdomain_name']);
$org_id = gat_organisationid_using_subdomainid($result['subdomain_id']);
$this->CI->session->set_userdata('organisation_id', $org_id);
if($org_id)
{
$templ_id = get_templid_using_organisationid($org_id);
$org_logo = get_organisation_logo($org_id);
}
if($templ_id){
if($this->session->userdata('pinlogin'))
$this->CI->session->set_userdata('template_set', 4);
else
$this->CI->session->set_userdata('template_set', $templ_id);
}
if($org_logo)
$this->CI->session->set_userdata('org_logo', $org_logo);
}
}
else
{
$this->CI->session->unset_userdata('subdomain_id');
$this->CI->session->unset_userdata('subdomain_name');
if( $this->CI->session->userdata('user_id') && $this->CI->session->userdata('user_category')<=2 )
{
$this->CI->session->unset_userdata('organisation_id');
$this->CI->session->unset_userdata('org_logo');
}
}
}
}

Here is the basic check you need to support custom themes per subdomain
// Gets the current subdomain
$url = 'http://' . $_SERVER['HTTP_HOST'];
$parsedUrl = parse_url($url);
$host = explode('.', $parsedUrl['host']);
// store $host[0], which will contain subdomain or sitename if no subdomain exists
$subdomain = $host[0];
// check for subdomain
if ($subdomain !== 'localhost' OR $subdomain !== 'mysite')
{
// there is a subdomain, lets check that its valid
// simplified get_where using activerecord
$query = $this->db->get_where('subdomain_map', array('subdomain_name' => $subdomain, 'status' => 1));
// num_rows will return 1 if there was a valid subdomain selected
$valid = $query->num_rows() === 1 ? true : false;
if($valid)
{
// set theme, user_data, etc. for subdomain.
}
else
{
// get user out of here with redirect
header('Location: http://' . $_SERVER['HTTP_HOST'] . '/error');
exit();
}
}
Note that when using subdomains with codeigniter, you should set your config > base_url to the following:
$config['base_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/poasty/poasty-starterkit/';
this will ensure things like site_url() and other CI helpers still work.
Reading through your code may I suggest utilizing more of Codeigniters built-in functionality, for example your __construct function has a lot of un-necessary code:
Original code
public function __construct(){
parent::__construct();
/**
* CI already exists
* since this controller extends CI_controller, there is already and instance of CI available as $this.
$this->CI =& get_instance();
*/
/**
* duplicate check, CI checks if library is loaded
* and will ignore if loaded already
if (!isset($this->CI->session))
{
$this->CI->load->library('session');
}
*/
$this->CI->load->library('session');
}
Optimized for Codeigniter
public function __construct()
{
parent::__construct();
$this->CI->load->library('session');
}
I suggest reading up on the Codeigniter user_guide to better understand what codeigniter can do. #see http://codeigniter.com/user_guide/
I hope you find this helpful!

Related

How to fix session being auto generated when page is reloaded/refresh using Codeigniter and Database as session driver?

I have my little project running perfectly on my local computer. However, when I run it into my laptop, an entry is automatically loaded in my ci_sessions table each time the page is being reloaded or refresh. I am using the database as my session driver.
Based on the screenshot: row 4 says that my login session store successfully. However, the 2 extra rows (5, 6) that are being added cause this code to fail:
public function isLoggedIn()
{
if($this->session->userdata('logged_in') === true) {
redirect('home', 'refresh');
}
}
public function isNotLoggedIn()
{
if($this->session->userdata('logged_in') !== true) {
redirect('login', 'refresh');
}
}
here's my config.php
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
Here's my Page Controller
<?php
class Pages extends MY_Controller
{
public function view($page = 'login')
{
if (!file_exists(APPPATH.'views/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
if($page == 'login') {
$this->isLoggedIn();
$this->load->view($page, $data);
}
else{
$this->isNotLoggedIn();
$this->load->view($page, $data);
}
}
}
MY_Controller Class
<?php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
}
public function isLoggedIn()
{
if($this->session->userdata('logged_in') === true) {
redirect('home', 'refresh');
}
}
public function isNotLoggedIn()
{
if($this->session->userdata('logged_in') !== true) {
redirect('login', 'refresh');
}
}
}
So far I have already tried adding the code below to my autoload.php but no luck.
$autoload['libraries'] = array('database', 'session');
Note: again this works in another unit with a similar setup.
after trying some work around, Codeigniter 3 is not yet compatible with php 7. I have to downgrade my php version to 5.6 to make it work. thanks folks for helping.
I suffered a lot of troubles with the original CI session library (included what you mention). Finally I arrived to this replacement that use native PHP session. It works!
Believe me, in the middle of a project, I did not stop to wonder why. Just works.
Here it is: CodeIgniter Native Session
BUT, due that it is an old library you MUST made some hacks. You can check those simple hacks in the library's forum
Just drop this file in codeigniter's library directory.

Testing laravel routes identify method type

How can I get about a Laravel route if the request is a get or post?
I try to test my laravel routes with the following
public function testRoutes()
{
$app = app();
$routes = $app->routes->getRoutes();
/**
* Test if mynamespace routes are redirected to login page if is not the login page
*/
echo PHP_EOL;
foreach ($routes as $route) {
if(strpos($route->getName(),'mynamespace::' ) !== false ) {
$url = $route->uri;
//$appURL = env('APP_URL') .'/';
$response = $this->get($url);
if((int)$response->status() !== 200 ){
echo $url . ' (FAILED) did not return 200. The response is ' . $response->status();
$this->assertTrue(false);
} else {
echo $url . ' (success ?)';
$this->assertTrue(true);
}
echo PHP_EOL;
}
}
}
but I would like exclude post requests for the moment
As we can see the Route class has a property $methods.
Your solution would look something like:
if (in_array('POST', $route->methods)) continue;
It may be interesting for you to look into the testing provided by Laravel itself. A simple way of testing response testing and much more!
Laravel testing.

Dynamic Routing (Auto Create Route) on Laravel 5 - View not rendered on App::call()

Basically, I have an admin (CMS) for my app. I have included menu and submenu setup, which are eventually populated on my nav section.
Name: User
URL: setup/user
Icon: fa fa-user
The problem is, if I add new menu (like above), I have to setup another route on web.php, like:
Route::resource('setup/user','UserController');
Well, there will be lots of menu to be created and my web.php is somehow messed up with lots of routes.
I followed this article and it gave me an idea, I tweaked it and created my own.
https://laracasts.com/discuss/channels/laravel/dynamically-calling-a-controller-method-in-laravel-5
Here's what I've done:
function wildcard($route, $controller, $verbs = ['get', 'post']) {
$stack = Route::getGroupStack();
$namespace = end($stack)['namespace'];
$controller = ucfirst(strtolower($route)).'Controller';
Route::match($verbs, rtrim($route, '/') . '/{method}', function($method, $params = null) use ($route, $namespace, $controller)
{
$controller = $namespace . '\\' . $controller;
$method = $controller . '#' . $method;
$params
? App::call($method, explode('/', $params))
: App::call($method);
});
}
wildcard('home',null);
My HomeController:
public function index()
{
return view('pages.common.dashboard');
}
But it doesn't display the view on my index method, just blank page. But it did get the method because I can dump from the method.
Maybe there's a better way on dynamic routing. Thanks.
Solution: You must return your App::call()
Route::match($verbs, rtrim($route, '/') . '/{method}', function($method, $params = null) use ($route, $namespace, $controller)
{
$controller = $namespace . '\\' . $controller;
$method = $controller . '#' . $method;
if($params){
// return the App::call
return App::call($method, explode('/', $params));
} else {
// return the App::call
return App::call($method);
}
});

maintain url in codeigniter for pages,categories,subcategories and product?

I'm trying to do URL format likes below
for pages -
www.example.com/page-name
for categories
www.example.com/category-name/sub-category-name
for product
www.example.com/category-name/sub-category-name/product-name
This should not be a problem if you are using only one controller i.e. your default controller. Say your default controller is called "Home". Then you can simply do this.
class Home extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Home_model');
}
public function _remap()
{
$category = $this->uri->segment(2);
$sub_category = $this->uri->segment(3);
$product = $this->uri->segment(4);
// Check what you have
// echo $category.'_'. $sub_category.'_'. $product;
if($category == '' || $sub_category == '' || $product == '')
{
//send user to landing page of website
$this->load->view('landing');
}
else
{
// get the product details
$render['product_details] = $this->Home_model->get_product_details($category, $sub_category, $product);
// send product details to view
$this->load->view('product_details', $render);
}
}
}

codeigniter redirecting to a url

I have a website with a url like so (which works fine)
http://www.page.com/en/controller
But there always have to be a language and a controller in the url otherwise the page doesn't load or there is no language (no text).
Is it possible that when I enter a url like this
http://www.page.com
I get redirected to
http://www.page.com/en/controller
And the controller would be hidden? Only this would be left (my links require first segment to load a page with a particular language)
http://www.page.com/en
p.s tried routing and redirect, but with no luck
Sorry for the late response, I was away.
my routes
$route['default_controller'] = 'arena/display';
$route['(:any)/renginiai'] = "renginiai/getevents";
$route['(:any)/arena'] = "arena/display";
$route['(:any)/paslaugos'] = "paslaugos/displayServices";
$route['(:any)/kontaktai'] = "kontaktai/displayContacts";
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
My_Controller which is located in core folder. I load my language libraries from here.
/**
*
*/
class MY_Controller extends CI_Controller{
public function __construct()
{
parent::__construct();
$languages = array("lt", "en");
if(in_array($this->uri->segment(1), $languages)){
$this->lang->load($this->uri->segment(1), $this->uri->segment(1));
}
}
}
And this is my front page controller
<?php
class Arena extends MY_Controller{
public function display($year = NULL, $month = NULL){
/*$this->load->model('Mycal_model');*/
$this->load->model('Image_model');
$data['images'] = $this->Image_model->get_image_data();
$this->load->view('includes/head');
$this->load->view('includes/nav', $data);
$this->load->view('includes/header', $data);
//$this->load->view('includes/calendar', $data);
$this->load->view('includes/section');
$this->load->view('includes/footer');
}
}
open application/config/routes.php file and change
$route['default_controller'] = "en/controller";

Resources