Yudhistira Bayu Yudhistira Bayu - 5 months ago 83
PHP Question

Custom Profile URL Codeigniter

I'm trying to create the custom profile url like site/u/username
i found this one How to make url /username in codeigniter?

but until now it still show 404. when i'm trying to access site/u/username

my routes.php

$route['default_controller'] = "guest";
$route['404_override'] = 'u';


my model

function cekuser($username)
{
$query = $this->db->query("SELECT * FROM usertable WHERE username = '$username'");
$query = $query->result_array();
if($query){
return $query[0];
};
}


my controller

<?php class U extends CI_Controller {
public function __construct() {
parent::__construct();
}

public function index()
{
$username = $this->uri->segment(1);

if (empty($username)) {
$this->show_404();
}

$this->load->model('m_login');

// Check if parameter is not a valid username.
if (!$this->m_login->cekuser($username)) {
$this->displayPageNotFound();
} else {
$this->load->view('template');
}
}

protected function displayPageNotFound() {
$this->output->set_status_header('404');
$this->load->view('notfound');
}
}

Answer

route.php

instead of $route['404_override'] = 'u';

Add

$route['u/(:any)'] = 'u/showuserinfo';

In Controller

Add a method

function showuserinfo($name)
{
 $this->load->model('m_login');
  if (empty($name))
  {
        $name = $this->uri->segment(2);
  }
  $user = $this->m_login->cekuser($name);
  if (!empty($user))
  {
        $this->load->view('template', $user);
  }
  else
  {
        echo 'User Not found';
  }
}