Codeigniter first segment URL variables - php

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.

Related

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';

How can I setup Laravel 3 routes for pages of focus on my default controller?

There will be several high profile links for customers to focus on, for example:
Contact Us # domain.com/home/contact
About the Service # domain.com/home/service
Pricing # domain.com/home/pricing
How It Works # domain.com/home/how_it_works
Stuff like that. I would like to hide the home controller from the URL so the customer only sees /contact/, not /home/contact/. Same with /pricing/ not /home/pricing/
I know I can setup a controller or a route for each special page, but they will look the same except for content I want to pull from the database, and I would rather keep my code DRY.
I setup the following routes:
Route::get('/about_us', 'home#about_us');
Route::get('/featured_locations', 'home#featured_locations');
Which work well, but I am afraid of SEO trouble if I have duplicate content on the link with the controller in the URL. ( I don't plan on using both, but I have been known to do dumber things.)
So then made routes like these:
Route::get('/about_us', 'home#about_us');
Route::get('/home/about_us', function()
{
return Redirect::to('/about_us', 301);
});
Route::get('/featured_locations', 'home#featured_locations');
Route::get('/home/featured_locations', function()
{
return Redirect::to('/featured_locations', 301);
});
And now I have a redirect. It feels dumb, but it appears to be working the way I want. If I load the page at my shorter URL, it loads my content. If I try to visit the longer URL I get redirected.
It is only for about 8 or 9 special links, so I can easily manage the routes, but I feel there must be a smart way to do it.
Is this even an PHP problem, or is this an .htaccess / web.config problem?
What hell have I created with this redirection scheme. How do smart people do it? I have been searching for two hours but I cannot find a term to describe what I am doing.
Is there something built into laravel 4 that handles this?
UPDATE:
Here is my attempt to implement one of the answers. This is NOT working and I don't know what I am doing wrong.
application/routes.php
Route::controller('home');
Route::controller('Home_Controller', '/');
(you can see the edit history if you really want to look at some broken code)
And now domain.com/AboutYou and domain.com/aboutUs are returning 404. But the domain.com/home/AboutYou and domain.com/home/aboutUs are still returning as they should.
FINAL EDIT
I copied an idea from the PongoCMS routes.php (which is based on Laravel 3) and I see they used filters to get any URI segment and try to create a CMS page.
See my answer below using route filters. This new way doesn't require that I register every special route (good) but does give up redirects to the canonical (bad)
Put this in routes.php:
Route::controller('HomeController', '/');
This is telling you HomeController to route to the root of the website. Then, from your HomeController you can access any of the functions from there. Just make sure you prefix it with the correct verb. And keep in mind that laravel follows PSR-0 and PSR-1 standards, so methods are camelCased. So you'll have something like:
domain.com/aboutUs
In the HomeController:
<?php
class HomeController extends BaseController
{
public function getAboutUs()
{
return View::make('home.aboutus');
}
}
I used routes.php and filters to do it. I copied the idea from the nice looking PongoCMS
https://github.com/redbaron76/PongoCMS-Laravel-cms-bundle/blob/master/routes.php
application/routes.php
// automatically route all the items in the home controller
Route::controller('home');
// this is my last route, so it is a catch all. filter it
Route::get('(.*)', array('as' => 'layouts.locations', 'before' => 'checkWithHome', function() {}));
Route::filter('checkWithHome', function()
{
// if the view isn't a route already, then see if it is a view on the
// home controller. If not, then 404
$response = Controller::call('home#' . URI::segment(1));
if ( ! $response )
{
//didn't find it
return Response::error('404');
}
else
{
return $response;
}
});
They main problem I see is that the filter basically loads all the successful pages twice. I didn't see a method in the documentation that would detect if a page exists. I could probably write a library to do it.
Of course, with this final version, if I did find something I can just dump it on the page and stop processing the route. This way I only load all the resources once.
applicaiton/controllers/home.php
public function get_aboutUs()
{
$this->view_data['page_title'] = 'About Us';
$this->view_data['page_content'] = 'About Us';
$this->layout->nest('content', 'home.simplepage', $this->view_data);
}
public function get_featured_locations()
{
$this->view_data['page_title'] = 'Featured Locations';
$this->view_data['page_content'] = 'Featured properties shown here in a pretty row';
$this->layout->nest('content', 'home.simplepage', $this->view_data);
}
public function get_AboutYou()
{
//works when I return a view as use a layout
return View::make('home.index');
}

Codeigniter shorten urls

Is it possible to create such urls in codeigniter?
http://site.com/shorturl/
Where shorturl isn't a physical controller file, but a variable.
I expect the algorythm for parsing url query to be like this:
1) Search for physical controller file. If exists, do standard codeigniter routine. If not
2) Try to load special controller file, where "shorturl" is a variable. Do further stuff inside that controller.
Thanks in advance
The previous answer seems quite good, but thought I'd share what I'd though of.
If you set your 404_override to point to a controller you have set up as follows:
$route['404_override'] = 'welcome/short';
Any URL that doesn't exist (any short URL for example) would get sent there, where you could do the following to check the value:
public function short() {
$shortCode = $this->uri->segment(1);
}
That would give you the value you need to check. If all is well, do the redirect, if the code doesn't exist, you can then use the show_404 method to actually show the 404 page.

custom URL mappings in codeigniter like redmine?

So redmine has a very peculiar url mapping style that i observed :
http://demo.redmine.org/projects/<project-name>/controller/action
samples :
http://demo.redmine.org/projects/produto/activity
http://demo.redmine.org/projects/produto/issues/new
http://demo.redmine.org/projects/produto/issues/gantt
http://demo.redmine.org/projects/produto/files
and the url changes as the project changes.
how do i do this in codeigniter ? I'm thinking it can be done with routes.php but so far i'm not able to get anywhere.
Looking for any help. Thanks.
Use the following function inside your "application/controllers/projects.php" controller:
public function _remap($method)
{
if ($method == 'project-name')
{
//display project1
}
elseif($method == 'project-name2')
{
//display project2
}
}
You can do the same for varying methods by extracting them from database
take a look here:
http://codeigniter.com/user_guide/general/controllers.html#remapping
you can also route your controller by using custom routes in application/config/routes.php
$route['example'] = "controller/function";
$route['example2/(:any)'] = "controller/function";
You use the routes file in application/config/routes.php
You would use something like this:
// the $1 maps to :any
$route['projects/produto/:any'] = "$1";
// the $1 maps to the first any, $2 maps to the second :any
$route['projects/produto/:any/:any'] = "$1/$2";
You will want mod_rewrite enabled if you are handling clean URL's. Otherwise expect the index.php/controller/action. I cant test it myself there, but you should refer to:
Once you add a route (It has to be called $route[] inside the configuration), refresh the page and try to go to the URL!
http://codeigniter.com/user_guide/general/routing.html
add this to your routes.php (btw: you need url-rewriting enabled for routes to work, ie. using .htaccess)
$route['projects/(:any)/(:any)/(:any)'] = "$2/$3/$1";
for example /projects/produto/issues/new will call the function new in the class issues and pass it the parameter 'produto'
also check http://codeigniter.com/user_guide/general/routing.html

creating dynamic page URLs with CI (routing) - a simple message board example

I feel like I have enough experience with CI to finally start fooling around with creating a message board... Or at least thats what I thought, until I got stuck at generating dynamic pages based on subject names (slugs).
So, I creating the controller/model/views and set up a form that submits the necessary info to the database. I pulled the threads out and display them, and generate a link for each one based on the subject title...i essentially followed the CI tutorial, editing it to suit my needs.
However, understanding the concept of generating dynamic page URLs is throwing me off. I understand a lot better by hearing exactly whats happening during the process, and the codeigniter tutorial (news) doesnt explain it well. It simply tells you what to do and how, and not why.
Anyone out there feel up to attempting to explain in greater detail, the process to code dynamic pages.
What I mean by dynamic pages is :
http://your-site.com/news/1/hello-world
http://your-site.com/news/1/foo-bar
where hello world and foo bar.
Here are some parts that confuse me:
<?php
class Pages extends CI_Controller {
public function view($page = 'home')
{
}
}
And heres the routing
$route['default_controller'] = 'pages/view';
$route['(:any)'] = 'pages/view/$1';
what does $1 represent? Any specific url that there? When would you use $2? Is it built in code to CI, or can you use any variable?
I'm sure the answer can get more detailed, but If someone could answer some of the above questions, i'm sure it'd be very helpful.
With those questions answered, in theory, what should be done to produce a new page for a forum thread?
Thanks!
what does $1 represent? Any specific url that there? When would you
use $2? Is it built in code to CI, or can you use any variable?
$1 represents a reference to the variable created by the wildcard (:any). There is no $2, because you only have one wildcard.
You would have a second wildcard if you created a route like this:
$route['pages/(:num)/(:any)'] = 'pages/$1/$2';
With that said, the route setup within your question kind of defeats the purpose of CI's MVC architecture and route system, as you're redirecting ALL routes to pages/views, I'm fairly sure you want something like:
$route['default_controller'] = 'pages/view';
$route['pages/view/(:any)'] = 'pages/view/$1';
<?php
class Pages extends CI_Controller {
public function view($page = 'home')
{
}
}
The corresponding url for this method would be http://example.com/pages/view/. In the method it is set to $page = 'home' because if there is no third segment in the url, it will default to home.
$route['(:any)'] = 'pages/view/$1';
The variable $1 is whatever you have as your (:any). So if you url is http://example.com/testing, it would route to http://example.com/pages/view/testing and that would in turn set your $page var from your view method to "testing".

Categories