Redirect to alias in Codeigniter - php

Hi I need to redirect to alias in url with codeigniter... for example
If the user type in the browser http://www.website.com/fedex, need to get the fedex like alias and find in the database by this alias and redirect to the correct url that must be http://www.website.com/pages/fedex... here is my code...
PD: By the way do not exists controller named fedex.
.. routes.php ...
$route['default_controller'] = "alias";
$route['404_override'] = '';
$route[':any'] = "alias/index/$1";
.. pages Controler ..
class Alias extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$alias = $this->uri->segment(1);
echo "Alias:" . $alias;
}
}

I think this is what you are trying to do...
class Alias extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}
public function index(){
echo 'Default page!';
}
public function get($alias)
{
$this->db->from('users')->where(array('username' => $alias));
$query = $this->db->get();
if ($query->num_rows() > 0){
//This means that a row was returned from the database and their is a user that exists with that name
redirect("/pages/$alias");
}
else{
echo 'There is no user that exists with that username';
}
}
public function pages($alias){
echo "Hey $alias!";
}
}
//Routes
$route['default_controller'] = "alias";
$route['404_override'] = '';
$route['pages/:any'] = "alias/pages/$1";
$route[':any'] = "alias/get/$1";
In the constructor it loads the database class and the URL helper. In the index() method is uses the database to select a row from the "users" table where their username is the $alias. Then it checks with an if statement if a row was returned from the database. If a row was returned that means a user exits and to redirect to /pages/username. Else it will echo saying no one exits with that username.
Make sure to change the database info match your database setup as well as make sure $active_record is set to TRUE in the database config file.

Related

unable to load second controller

In codeIgniter I have created routes to remove the controller/methodname from the url so but the problem is that when I try to access the second controller index method it is not loading it's loading the home controller
I have 2 controller Home.php and Admin.php when i type in localhost/foldername/ it is opeing home conrtollers index method but when I type in localhost/foldername/admin it is redirecting to home controller's second method which is page can any one help me out in writing the routes.
Here is my routes which I have created
$route['default_controller'] = 'home';
$route['([^/]+)/?'] = 'home/page/$1'; //If I comment this it is working properly for me
Admin Controller Admin.php
class admin extends CI_Controller {
public function index() {
if($this->session->userdata('is_logged_in') == true) {
$this->load->view('admin/dashboard');
} else {
$this->load->view('admin/login');
}
}
}
Home Controller Home.php
class home extends CI_Controller {
public function index() {
$front_page = $this->get_data->front_page();
$page_data = $this->get_data->AllData('pages', $front_page);
$data['title'] = $page_data->row()->pagetitle;
$class = explode("/", $page_data->row()->template);
$data['body_class'] = $class[1];
$this->load->view('includes/header.php', $data);
if($class[1] == 'home') {
$this->load->view('templates/slider');
}
$this->load->view('templates/navigation.php');
$page_content = $page_data->row()->template;
$this->load->view($page_content, $data);
$this->load->view('templates/footer-form.php');
$this->load->view('includes/footer.php');
}
public function page($id) {
$page_data = $this->get_data->AllData('pages', $id);
$data['title'] = $page_data->row()->pagetitle;
$class = explode("/", $page_data->row()->template);
$data['body_class'] = $class[1];
$this->load->view('includes/header.php', $data);
if($class[1] == 'home') {
$this->load->view('templates/slider');
}
$this->load->view('templates/navigation.php');
if($class[1] == 'home') {
$data['slider'] = 'templates/slider';
}
$data['content'] = $page_data->row()->template;
$this->load->view('index', $data);
$this->load->view('templates/footer-form.php');
$this->load->view('includes/footer.php');
}
}
Now can anyone help me out to solve this issue one thing more when I comment the custom routes it is working perfectly but the home controller for the page which i tried to remove method and controller name it is coming as 404 not found
According to what i undertand, Set your default controller, to check your authentication first:
$route['default_controller'] = 'admin';
//so that you can check weather the user is logged in or not.
To access your second controller's index function:
$route['Home'] = "home";
To access your second controller's page($id) function:
$route['Home/Page/(:num)'] = "home/page/$1";
// where num id the ID you will be passing to the page function.

codeigniter routes any or num not working

I have url like that http://lp.dev/sisters/adab/1 but the route is not working when i use (:num) or (:any) to get the value 1 because the route give me 404 page
routes as follows
$route['default_controller'] = "frontend/home";
$route["sisters/adab/(:num)"] = "frontend/pages/$1"; //<-- this is my issue
$route['404_override'] = 'errors/error_404';
controller : pages.php inside frontend folder
class Pages extends CI_Controller {
function __construct() {
parent::__construct();
$this->name = $this->uri->segment(2);
}
public function index($variable = NULL)
{
dd($variable);
if(is_page($this->name))
load_view("$this->name/home");
else
load_view('errors/error_404');
}
}
I guess you want this
$route["sisters/adab/(:num)"] = "frontend/pages/index/$1"; //correct
$route["sisters/adab/(:num)"] = "frontend/pages/$1"; // is wrong because
//it is redirecting to your page's controller and looking for a method (:num)

Read a specific post on a page

My problem is that I can't read a piece of data on an individual page. For example, on the front page, I have a number of jokes pulled in from the db; I want to be able to click on a joke and send the user to a url such as jokes.com/read/a-chicken-crossed-the-road. At the moment, it sends me to my custom 404 page with the url being jokes.com/read/1 (1 being the joke_id) and I haven't been able to get past this problem for a while, so I though I would try here.
Here is my setup :
main view:
<p class="joke-content"><?php echo $joke; ?></p>
read view:
<?php
foreach($results as $row){
echo "<li>$row->joke</li>";
echo "<li>$row->name</li>";
echo "<li>$row->date_added</li>";
}
?>
controller:
//constructor class enables a function called to be used in any function within this controller
function __construct(){
// Call the Controller constructor
parent::__construct();
$this->load->model('getjokes_m');
}
public function index(){
$this->read();
}
//main jokes functions grabs all the jokes in the database and orders them in their correct category
public function read(){
$data['results'] = $this->getjokes_m->readJokes($this->uri->segment(3));
$this->load->view('template/header');
$this->load->view('template/sidebar');
$this->load->view('content/read', $data);
$this->load->view('template/footer');
}
and finally my model:
function readJokes()
{
$query = $this->db->query('SELECT j.*, c.name FROM jokes j LEFT JOIN category c ON c.category_id = j.category_id WHERE joke_id = ?');
//displays the results if the table has data inside
return $query->result();
}
routes:
$route['default_controller'] = "top";
$route['404_override'] = 'not_found';
$route['register'] = 'login/register';
$route['logout'] = 'login/logout';
$route['admin'] = 'admin/login';
$route['noaccess'] = 'login/noaccess';
I think it might be the sql statement I am using, because it doesn't return any data.
If somebody could point me in the right direction as to why this is not working and to get the first 55 characters in the URL slug, it would be brilliant.
If I understand this problem correctly you want a slug as a parameter of your read() function.
you did not specify controllers name lets assume you want it to be call "read"
The easiest way is to do following:
edit routes.php as following:
$routes['read/(:num)/(:any)'] = "read/read_it/$1";
line above takes URL as following: server.ufo/read/1/my-super-joke and translates it to this server.ufo/read/read_it/{id}
lets have controller structure as following:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Read extends CI_Controller {
public function __construct()
{
parent::__construct();
//Do your magic here
}
public function index()
{
//leave empty or redirect somewhere
}
public function read_it($id = FALSE)
{
if ($id === FALSE) redirect(); //go to default controller
$data['results'] = $this->getjokes_m->readJokes( $id ); //id is NUMERICAL auto incremented value!!
$this->load->view('template/header');
$this->load->view('template/sidebar');
$this->load->view('content/read', $data);
$this->load->view('template/footer');
}
}
/* End of file read.php */
/* Location: ./application/controllers/read.php */
and lastly generation of links is simple:
<p class="joke-content"><?php echo $joke; ?></p>
remember joke_id is autoincremented ID, and joke_name is your magic slug (name)

How to block acces for all methods to Admin Controller

I need to block access to other methods in Admin controller if admin is not logged in.For example if I write base_url/administration/show/index I can access without login in system
Pleez help,Thx
Login Controller:
class Login extends CI_Controller{
function __construct(){
parent::__construct();
}
public function index(){
// Load our view to be displayed
// to the user
$this->load->view('admin/authentification_view');
}
public function process()
{
// Load the model
$this->load->model('login_model');
// Validate the user can login
$result = $this->login_model->validate();
// Now we verify the result
if(! $result){
// If user did not validate, then show them login page again
$this->index();
}else{
// If user did validate,
// Send them to members area
redirect('administration/show/index');
}
}
}
Login Model
class Login_model extends CI_Model{
function __construct(){
parent::__construct();
}
public function validate()
{
$login = $this->security->xss_clean($this->input->post('login'));
$password = $this->security->xss_clean($this->input->post('password'));
$this->db->where('login', $login);
$this->db->where('password', $password);
$query = $this->db->get('admin_details');
if($query->num_rows == 1)
{
// Creare date sesiuni
$row = $query->row();
$data = array(
'id' => $row->id,
'login' => $row->login,
'password' => $row->password,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
return false;
}
}
Administration Controller
class Administration extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('administration_page_model');
$this->load->model('crud');
$this->load->helper('url');
}
public function logout()
{
$this->session->sess_destroy();
redirect('login');
}
public function show($admin_page)
{
$data = array();
$data["news"] = $this->administration_model->allNews();
switch($admin_page)
{
case 'index':
$name = 'admin/index';
$this->display_lib->admin_page($data,$name);
break;
case 'add_news':
$name = 'admin/addnews';
$this->display_lib->admin_page($data,$name);
break;
case 'all':
$name = 'admin/all';
$this->display_lib->admin_page($data,$name);
break;
}
}
}
The easiest seperation would be to define the following classes in application/core:
Base_Controller extends CI_Controller
- some basic stuff, setting vars etc
Admin_Controller extends Base_Controller
- integrate your logic/library that determines a user as an admin
- for example: If(!isAdmin) -> redirect to login
Auth_Controller extends Base_Controller
- for example: If(!isLoggedIn) -> redirect to login
Front_Controller extends Base_Controller
- no need for auth or admin, then use this one
You can simply put in the constructor of any admin controller :
function __construct()
{
parent::__construct();
if(!$this->session->userdata('validated')) redirect('login');
}
You can also check out Ion_Auth plugin (it manages authentifications, accounts, etc). You will just need to call :
function __construct()
{
parent::__construct();
if(!$this->ion_auth->logged_in()) redirect('login');
}
Create a helper function check_login() to cjeck if user is logged in and the call this helper in your constructor for every class where you need to check login .
public function check_login(){
$ci = & get_instance();
if(!isset($ci->session->userdata['validated']))
{
//do what u want if user is not loogged in
//for example redirect('home page url');
}
}
Now in every constructor just add this line
check_login();
to learn more about helper functions see
http://ellislab.com/codeigniter/user-guide/general/helpers.html

CodeIgniter reUse/extend controller

I have my controller
class Page extends CI_Controller {
public function id() {
$this->load->model('content');
$page = $this->uri->segment(3, 0);
if($page == 0)
$page = $this->content->get_default_page($page);
$data['navigation'] = $this->content->getNav();
$data['pagename'] = $this->content->get_pagename($page);
$data['content'] = $this->content->get_content($page);
$this->load->view('main', $data);
}
}
Now I'll try to explain.
Im getting navigation, and navigation text from mysql (id, navName, navText).
then im returning those elements in views/main_view.php in url like: http://abc.com/page/id/1 etc...
Now i need to create other controller like mySuperDuperModule which have some functions not just text.
The problem is that if i create new controller like Gallery(), i need to copy all the stuff from Page() controller to make website show the same.
Is there any way not to do that ?
You can create base controller under /application/core/MY_Controller.php
Here MY_ is the value specified for $config['subclass_prefix'] in /application/config/config.php
class MY_Controller extends CI_Controller
{
protected $data;
public function __construct()
{
parent::__construct();
$this->data = array();
}
public function loadPage($page)
{
$this->load->model('content');
if($page == 0)
$page = $this->content->get_default_page(); // I hope this function will give default page from database table. (A Change from your code)
$this->data['navigation'] = $this->content->getNav();
$this->data['pagename'] = $this->content->get_pagename($page);
$this->data['content'] = $this->content->get_content($page);
}
}
Your modified Page Class in /application/controllers/page.php
class Page extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function id()
{
$page = $this->uri->segment(3, 0);
parent::loadPage($page);
$this->load->view('main', $this->data);
}
}
and your new gallery controller can be in /application/controllers/gallery.php
class Gallery extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function id()
{
$page = 10; // Assuming gallery page index is 10 in database table OR you can change any logic here.
parent::loadPage($page);
$this->load->view('main', $this->data);
}
}
you can create as many controllers as you want by extending MY_Controller.
You can pass these two lines to any controller
and they will display the same template.
$data['navigation'] = $this->content->getNav();
$data['pagename'] = $this->content->get_pagename($page);
If you still dont understand try to use this library
https://github.com/philsturgeon/codeigniter-template

Categories