URL segment - User Profiles - Codeigniter
-
11-09-2019 - |
Question
Hey guys, I'm trying to create user profiles for my site where the url is something like
mysite.com/user/ChrisSalij
Currently my controller looks like so:
<?php
class User extends Controller {
function user(){
parent::Controller();
}
function index(){
$data['username'] = $this->uri->segment(2);
if($data['username'] == FALSE) {
/*load default profile page*/
} else {
/*access the database and get info for $data['username']*/
/*Load profile page with said info*/
}//End of Else
}//End of function
}//End of Class
?>
At the moment I'm getting a 404 error whenever i go to;
mysite.com/user/ChrisSalij
I think this is because it is expecting there to be a method called ChrisSalij. Though I'm sure I'm misusing the $this->uri->segment(); command too :P
Any help would be appreciated. Thanks
Solution
Its because the controller is looking for a function called ChrisSalij.
The few ways to solve this:
1) change
function index(){
$data['username'] = $this->uri->segment(2);
to be
function index($username){
$data['username'] = $username;
and use the url of mysite.com/user/index/ChrisSalij
2) if you dont like the idea of index being in the URL you could change the function to be called profile or the like, or look into using routing
and use something along the lines of
$route['user/(:any)'] = "user/index/$1";
to correctly map the URL of mysite.com/user/ChrisSalij