URL segment - User Profiles - Codeigniter - php

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
Any help would be appreciated.
Thanks

It's because the controller is looking for a function called ChrisSalij.
A few ways to solve this:
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
if you don't like the idea of the index being in the URL you could change the function to be called a 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

Related

How to show sub router?

Suppose I have this controller:
class Site extends CI_Controller {
public function __constructor()
{
parent::__constructor();
echo 'test';
}
public function index()
{
$view['site'] = true;
$view['view_home'] = lang('home');
$view['view_home_url'] = base_url();
$view['view_name'] = lang('home');
$view['content'] = 'site/home';
$this->load->view('partials/template', $view);
}
public function association()
{
echo 'test';
}
}
when I type: http://localhost/mysite/association I get 404. Essentially I would like to use the same controller Site which is the default controller, to load multiple routers. How can I do this?
You are using codeigniter and you can't access url lik below as you haven't defined any routes for that. http://localhost/mysite/association . You will have to go url like
http://localhost/mysite/site/association //sometimes need index.php
if you don't configure it. first parameter is the controller and second one is a method
For going to your custom URL you will have to go to application/config/routes.php and define your new custom
route $route['association'] = 'site/association';
You can also define like below routes and access from browser
$route['association/url1/url2/url2'] = 'site/association'; //simple
Hope that you have got your answer

CodeIgniter 3 URI Paramaters and 404 Pages

I have a class named Collection with two methods named Index and Cars.
In it's basic format my controller it looks like this;
class Collection extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}
public function index(){
$data = array(
'title' => 'Index Page'
);
$this->load->view('template/Header');
$this->load->view('collection/index', $data);
$this->load->view('template/Footer');
}
public function cars(){
$data = array(
'title' => 'Cars Page'
);
$this->load->view('template/Header');
$this->load->view('collection/list_of_cars', $data);
$this->load->view('template/Footer');
}
}
The URI looks like this;
example.com/collection/cars
This does what I want, the cars method is processed and the list_of_cars view is displayed as usual.
However I notice that if I add another parameter to the URL, e.g
example.com/collection/cars/something
In fact, I can add as many additional URI parameters as I like and I still don't get a 404 error.
The page simply reloads - should it not display a 404 error as that page doesn't exist?
Any advice is appreciated.
If your URI contains more than two segments they will be passed to your method as parameters.
The segment(s) you given is/are treated as arguments for the method you are accessing, means if you given like this
example.com/collection/cars/something
you can access this parameter in your cars method like this
public function cars($param)
{
echo $param;
}
and if you given like this
example.com/collection/cars/something/testing
you can access this parameter in your cars method like this
public function cars($param,$param2)
{
echo $param;
echo $param2;
}
Update :
If you want some check condition based on segments use $this->uri->segment() in your method , do like this :
if ($this->uri->segment(3) === FALSE)
{
/*this is your error page*/
$this->load->view('error-page');
}
else
{
$arg = $this->uri->segment(3);
}
For more : https://www.codeigniter.com/user_guide/libraries/uri.html
An approach that is similar can be structured as follows. If there are more than two segments (i.e. a controller + a method) then arguments are present so force a 404.
if ($this->uri->total_segments() > 2)
{
show_404(); //shows 404 page, logs the error, and ends execution
}
Read about show_404() here.

CodeIgniter User is able to copy and paste URL and access main page

I am trying to build a simple login system using CodeIgniter. I have placed all of my functions into one controller and I have also placed a session check function called is_logged_in into the controller. However, the user can still copy and paste the URL once they have logged out and view the main page. It seems like my is logged in function isn't working. Am I missing something? It only works if I place a check in my header every time instead. Here is my code.
Controller file
function index()
{
$this->load->view('login');
}
function checklogin()
{
$this->load->model('user');
$query = $this->user->validate_login();
if($query)
{
redirect('portal/home');
}
else
{
$this->index();
}
}
function logout()
{
$this->session->unset_userdata('username');
$this->session->unset_userdata('is_logged_in');
$this->session->sess_destroy();
redirect($this->index(),'refresh');
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in)||$is_logged_in!=TRUE)
{
$this->index();
}
}
function home()
{
$this->is_logged_in();
$data['main_content'] = 'home';
$this->load->view('includes/template',$data);
}
function statements()
{
$this->is_logged_in();
$data['main_content'] = 'statements';
$this->load->view('includes/template',$data);
}
function about()
{
$this->is_logged_in();
$data['main_content'] = 'about';
$this->load->view('includes/template',$data);
}
}
?>
This is what I place into my headers that actually works instead of the function
<?php
if(!$this->session->userdata('is_logged_in'))
{
redirect('portal/index');
}
?>
User Model
<?php
class User extends CI_Model{
function __construct()
{
parent::__construct();
}
public function validate_login()
{
//$this->form_validation->set_rules('username', 'Username', 'trim|required');
//$this->form_validation->set_rules('password', 'Password', 'trim|required');
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean(md5($this->input->post('password')));
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get('accounts');
if($query->num_rows()==1)
{
foreach($query->result() as $row)
{
$sess_data = array(
'username'=>$this->input->post('username'),
'is_logged_in'=>TRUE,
'privilege'=>$row->privilege
);
}
$this->session->set_userdata($sess_data);
return true;
}
else
{
// echo $password;
}
}
}
?>
Also, how can I combine the commented out part in the user model with the next lines? I want an error message to be sent if no input is placed. Hope I can get help with this.
So much wrong in this. Do not, not ever, use a single controller for your application. Things will get pretty big, pretty fast, and then you have one unreadable blob of a file. Keep your application code normalized. That's why you are using MVC. If you then need a method accessible from every, or nearly every controller, then put this function into a base controller(MY_Controller i.e.), or a model, or a library, depending on the functionality of this method. But in your case, this is for a base controller. This wont help with your problem, but just a friendly suggestion.
The problem with your code is, the visitor hits the URL for method "statements" and this is what happens:
statements calls is_logged_in
is_logged_in determines user is not logged in and calls index
index loads the login view
statements method loads the statements view
After you check for log in, and determine that the user is not logged in, you have to prevent further execution of other parts of your code. I would suggest having is_logged_in method returning a bool(false) value, and the statements(and other methods) then stopping execution. But if you would separate your code like you should over multiple controllers, then maybe have the is_logged_in controller to redirect the user to the login page.

Custom URL routing including identifier/controller/method

I'm trying to create a bug tracking software with multiple projects support.
To achieve that I'd like to use a URL like this:
http://example.com/project/default_project/tickets/view/123
project is the Project-Controller
default_project is in this case the project identifier.
tickets is the controller
view is the method in the tickets-controller
123 is the ID of the ticket passed to view
How do I create such a routing?
My controller would look like this:
class Tickets extends CI_Controller {
public function index() {
// load all tickets WHERE project_identifier = $this->uri->segment(1)
}
public function view($id) {
// load ticket WHERE project_identifier = $this->uri->segment(n)
// AND ticket_id = $id
}
}
I fixed my problem by adding this line to routes.php in the config folder:
$route['project/(:any)/ticket/(:num)'] = 'tickets/view/$1/$2';

Code Igniter RESTful Modeling and Controller

I have been developing using non framework for about 3 years and I have heard about PHP framework codeigniter.
I think I missed something using this framework which is used for API for my mobile application.
I've facing some problem to get data from database using Phil's CI framework, RESTful plugin. My browser shows error code:
{"status":false,"error":"Unknown method."}
Using my logic below:
controller: user.php
<?php
require(APPPATH.'libraries/REST_Controller.php');
class User extends REST_Controller{
public function user_get()
{
//IF USER NOT EXIST
if(!$this->get('id'))
{
$this->response(NULL, 400);
}
//CHECK TO MODEL FUNCTION
$user = $this->user_model->get_user($this->get('id'));
//IF USER EXIST
if($user)
{
$this->response($user, 200); // 200 being the HTTP response code
}
}
public function user_put()
{
// create a new user and respond with a status/errors
}
public function user_post()
{
// update an existing user and respond with a status/errors
}
public function user_delete()
{
// delete a user and respond with a status/errors
}
}
?>
model: user_model.php
<?php
class User_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_user($id){
$query = $this->db->get('mt_user', array('idmt_user'=>$id));
return $query->row_array();
}
}
?>
i'm accessing the database which is has this rows:
idmt_user,username,password, emails, createdate
accessed using mozilla:
#http://localhost/<project>/index.php/user/<userid>
Where's the error(s) ?
thanks.
update,
i am already defined the autoloads for database. But this problem still persist. Is there any helps? thanks
as stated below in answer, i tried to access the url, /user/get_user/ but still showing the same result. Is there any problem using idmt_user in database?
Insert in controllers:
function __construct() {
parent::__construct();
$this->load->model('user_model');
}
And try this route:
http://localhost//index.php/user/user/id/
I believe that the url you are accessing with is wrong.. Try accessing with the url #http://localhost/<project>/index.php/user/<method_name>/<user_id>
Another way of doing it would be using the URI Class.
Instead of writing the following:
//IF USER NOT EXIST
if(!$this->get('id'))
{
$this->response(NULL, 400);
}
Changed to:
$userid = $this->uri->segment(3);
Would be 3 based off the url being http://localhost/<project>/user/<method_name>/<user_id>
Reference for URI Class: http://www.codeigniter.com/user_guide/libraries/uri.html
In order to use $this->get(); there would have to be a query parameter to get. Example: id=
If you are passing query parameters than you could store these values in a array as shown below.
if(!empty($this->get()))
{
$params[] = $this->get();
}
I hope this helps.
You should to try include your model file into your controller file by using a __construct() function, like this:
function __construct(){
parent::__construct();
$this->load->model(array('user_model'));
}

Categories