Codeigniter 2.0 GET params with URI rounting - php

Hey,
I've wrote a line in my routes.php as the following:
$route['admin/trip/add'] = "admin/trip_controller/form";
But when I go to that URL in my browser, I get sent back to the main index page i.e (www.mydomain.com), does anybody know what i'm doing wrong?
I've enabled GET params in my config file too:
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = TRUE;
I've also tried going to a URL which doesnt use routing and I too get redirected back to the main index page.
Thanks

enable_query_strings is a configuration option that will allow you to send your controller and method via ?c=blog&m=view. This will cause trouble because obviously you aren't sending those in your query string, so CodeIgniter will assume nothing is passed and display the homepage.

You should try to use the _remap() function instead of messing with the routes.
So I guess you would have the admin.php controller.
Inside you would use the remap function which will use the second segment of the url to find what function to call.
<?php
class Admin extends Controller{
function _remap($method, $params =array())
{
if(method_exists($method))
{
$this->$method();
}
elseif($method == 'trip' && $this->uri->segment(3)=='add')
{
//do what you want here
}
}

Related

How to add a view?

I've been researching up on how to add views and I'm stumped. I want to add a view and all I get are 404 errors. All the examples I see on the web are just to add a default controller. I have a default controller, now I want to add a new page passed an ID in the URL.
This is the controller xyz.php:
class Xyz extends CI_Controller {
public function index() {
date_default_timezone_set('UTC');
$this->load->model('xyz_model');
$this->load->view('xyz_main_view');
}
public function activity() {
date_default_timezone_set('UTC');
$this->load->model('xyz_model');
$this->load->view('xyz_activity_view');
}
}
Model is xyz_model.php, and views are xyz_main_view.php and xyz_activity_view.php.
This is routes.php:
$route['default_controller'] = 'xyz'; // works okay
// $route['xyz'] = 'xyz/activity'; // 404
// $route['activity'] = 'xyz/activity'; // 404
// $route['xyz/activity'] = 'xyz/activity'; // 404
// ... many, many other different approaches
I'm able to use http://localhost, but I'd like to use the following:
// map to main view
http://localhost/index
http://localhost/xyz
http://localhost/xyz/index
// map to activity view
http://localhost/activity
http://localhost/xyz/activity
My understanding is that some of the URLs for the main view should work automatically, not seeing it. Just http://localhost.
I haven't even touched how to get an ID from the URL for the activity page. Just want to get over this first hurdle.
Keep this code in routes
$route['default_controller'] = 'xyz';
Then Try this URL to execute "activity()" function in xyz controller.
http://localhost/[YOUR PROJECT FOLDER NAME]/index.php/xyz/activity
To Pass Parameters such as id's you can use this url.
http://localhost/[YOUR PROJECT FOLDER NAME]/index.php/xyz/activity/[ID]
For more information please check codeigniter routing library. It is really easy to understand.
https://www.codeigniter.com/user_guide/general/routing.html

How to achieve this kind of url routing in codeigniter

i want to achieve url routing something like www.example.com/alicia
suppose alicia is not a class name or method name just something like passing data in url and with some class i want to access this and want to use it for further process.How i can use it ? Thanks in advance.
You can use Codeigniter's built-in routing, the file route.php is located in your config folder.
there you can add:
$route['alicia'] = 'welcome/index/something';
$route['alicia/:any'] = 'welcome/index/someotherthing/$1';
then in your controller, for example welcome you just create a function like:
public function index($page = null){
if($page=='something'){
// do what you need to do, for example load a view:
$this->load->view('allaboutalicia');
}
elseif ($page=='someotherthing'){
// here you can read in data from url (www.example.com/alicia/2017
$year=$this->uri->segment(2); // you need to load the helper url previously
}else{
// do some other stuff
}
}
documentation on routing and on urlhelper
edit after comment:
in case your uri segment is representing a variable, like a username, then you should use a uri scheme like www.example.com/user/alice and create your route like:
$route['user/:any'] = 'welcome/index/user';
then in your controller welcome
public function index($page=null){
if($page=='user'){
// do what you need to do with that user
$user=$this->uri->segment(2); // you need to load the helper url
}
else{
// exception
}
}
This could be tricky because you don't want to break any existing urls that already work.
If you are using Apache, you can set up a mod_rewrite rule that takes care to exclude each of your controllers that is NOT some name.
Alternatively, you could create a remap method in your base controller.
class Welcome extends CI_Controller
{
public function _remap($method)
{
echo "request for $method being handled by " . __METHOD__;
}
}
You could write logic in that method to examine the requested $method or perhaps look at $_SERVER["REQUEST_URI"] to decide what you want to do. This can be a bit tricky to sort out but is probably a good way to get started.
Another possibility, if you can think of some way to distinguish these urls from your other urls, would be to use the routing functionality of codeigniter and define a pattern matching rule in the routes.php file that points these names to some controller which handles them.
I believe that the default_controller will be a factor in this. Any controller/method situations that actually correspond to a controller::method class should be handled by that controller::method. Any that do not match will, I believe, be assigned to your default_controller:
$route['default_controller'] = 'welcome';

CodeIgniter detect if Default Controller route was used

In CodeIgniter, is there a way to know if a user was sent to the Default Controller because the route sent them there, OR because the user actually entered that controller in the URL bar.
In other words, ---.com/home and ---.com could both send you to the 'home' controller, because you have set
$route['default_controller'] = 'home';
But only ---.com/ would invoke CI to fetch the "default_controller"
So, how do I detect this? If only there was a boolean function that could tell me this.
You should be able to use $this->uri->total_segments() ... or one of the other functions in the URI class to deduce this ...
if($this->uri->total_segments() === 0){
//user came in by default_controller
}
URI Class Docs

Redirect in PHP Codeigniter

I have some problems using Code Igniter and I feel there is something I don't understand because I can't get my redirects and my headers to work. Here is the situation :
When site is entered, the default "home" controller is called.
public function initialize()
{
printf("CONSTRUCTION OF HOME CONTROLLER - \n");
// print_r($_SESSION);
//TODO : CONSIDER CREATING A LIBRARY TO AVOID WRITING THIS OFTEN. NOT
// SESSION TROLLING DETECTION
if( isset($_SESSION['banana']))
{
echo "SPLITTING THE TRUTH";
}
// GETTING AS SERIOUS AS GREG
if( !isset($_SESSION['username']))
{
printf("USERNAME IS NOT SET. SETTING UP THE LOGIN PAGE. \n");
redirect('home_invite');
}
else
{
$this->load->view('welcome_message');
}
}
public function index()
{
//INITIALIZING THE PATH USED FOR THIS NAVIGATION
printf("TROLLING THE BEGINNING OF THIS CONTROLLER HOME - ");
$this->initialize();
printf("TROLLING THE END OF THIS CONTROLLER HOME - ");
//TODO : CONSIDER CREATING A LIBRARY TO AVOID WRITING THIS OFTEN
}
Index calls initialize who verify if the user has already a session variable with username in it. If that's the case, we would proceed to check his level of privileges, etc, and load corresponding view. Thats not the problem.
If the session is not started, I want to load the "login" view, called here "home_invite". And I want to redirect him to that page. But if I use this code, the page will show a 404 error.
If I use $this->load->view('home_invite'), it works, but I don't understand and I feel it isn't what I want it to do.
Why is redirect not working in this context?
Using the redirect() method redirects to a URL. You therefore need to pass it a full URL (as it uses the header() function which according to the RFC for HTTP1.1 requires a full URL.
This means that you can use
redirect(site_url('home_invite'));
Which will redirect your user to http://www.yoursite.com/home_invite
This means that you must have a controller called home_invite available as you can't load a view from the URL. Equally you could create a method in your existing controller and use the routes.php file to masquerade /your_controller/home_invite as /home_invite
The site_url() function is also part of the URL helper you've already included to use redirect().
If you don't want to use site_url(), you could just as well hard code the URL in like
redirect('http://www.yoursite.com/home_invite');

Codeigniter first segment URL variables

I am looking to use a URL shortening scheme where I would like the variable to be in the first segment of the URL, www.example.com/0jf08h204. My default controller is "home.php" and I have .htaccess mod-rewrites in place, so what is the best way to manage this? I suppose my smarts have been blocked by the standard /controller/method/variable scheme, is this a URI Protocol setting? Thank you!
To add to Matthew's response.
This is what you'll need in your system/application/config/routes.php file:
$route['(:any)'] = "home";
This will redirect EVERYTHING.
You might not want to redirect everything if you have other controllers which you need to use. If that is the case you can use this regular expression instead:
$route['^(?!about|contact)\S*'] = "home";
This will allow you to redirect everything except the controllers 'about' or 'contact' -- these will be directed to the 'about.php' and 'contact.php' controllers.
Please note, I choose not to use the wild cards within CodeIgniter, you might find they work better for you, I however choose to parse out the $_SERVER['REQUEST_URI'] manually after the redirect. If however you wanted to use the wildcards you would just add /$1 to the routes as you see in Matthew's response.
I myself haven't played a whole lot with Routing, but I think you could try something like this:
$route['(:any)'] = "controllername/actionname/$1";
Haven't tried this myself though.
Well even though it seems a bit non-standard to whitelist certain areas, and I am still running through my head how 404 errors will be handled, here is a method that is working for now using the regex from evolve. My home.php controller file:
class Home extends Controller {
function Home()
{
parent::Controller();
$uri = uri_string();
if(!empty($uri)) {
$uri_array = explode('/',$uri);
$first_segment = $uri_array[1];
if(isset($first_segment)) {
//do stuff, load alternative view
}
}
}
function index()
{
$this->load->view('home_view');
}
}
/* EOF */
Thanks for the help, please post alternate soln's if available.

Categories