Is it Possible to Drop Uri Segments with Codeigniter Routing - php

I have the url: http://devsite.com/page/profile/11
I would like to retain the current functionality of /controller_name/method/profile_id
BUT, I would like the url to drop the controller name, so it would just be: method/profile_id
I'm thinking this is not what codeigniter uri routing is meant for. I understand to a degree and use uri routing all the time, but it seems that this is more of something I'd need to do with apache mod_rewrite or something? Any ideas are appreciated.
Thanks.

Small bug in your route. There shoud be $1 at the end, not $2:
$route['profile/(:any)'] = 'page/profile/$1';

I figured it out, I wasn't thinking about it correctly. I have not BUILT the application yet, rather I'm building it as we speak. So if I HAD built the entire application and I was just now asking this, it would indeed be an apache rewrite situation, but since I am building the app now, some "pre-thought" will save me the trouble.
Instead of linking to 'page/profile/id', I can just link to 'profile/id' and then in my routes.php put this:
$route['profile/(:any)'] = 'page/profile/$2';

Related

Dynamically create URLs

Something that is really confusing me is how sites have urls such as:
http://example.com/shop/
-and-
http://example.com/shop/product-category/games/
Originally, I thought you could simply just create a php file and use URL rewrite in the .htaccess. For example:
http://example.com/shop.php
http://example.com/shop.php/product-category.php/games.php (It just doesn't make sense).
Clearly, this is not the case as not only is it not efficient for more trailing slashes, but CMS's such as Wordpress automatically generate the content for the 'dynamic' URLs, and then redirect to a 301 page if the URL is not recognised.
I am wanting to implement this into my site, I'm just completely clueless on how I'd approach this. I am struggling to research deep into the topic due to myself being unaware what this system actually is. Obviously, I'm looking at this completely wrong, which is causing me to confuse myself.
If someone could explain to what this system is called, and how I can do it. I'd prefer not to get spoon fed code, I just need someone to explain it all too me.
EDIT: After some further researching, I have found a perfect example to make my question clearer. Notice this url:
https://gamurs.com/g/csgo/players
has the same url as:
https://gamurs.com/g/csgo
But shows different content, it's a completely new page, that is being 'dynamically' created.
Then more random URLs from the same site:
https://gamurs.com/articles/world-esports-association-announced
https://gamurs.com/coaches
Thanks,
Sutton
So certainly if you were to use a framework like Laravel, its a very easy way of having routing.
There is a "routes.php" file in every project that defines calls to a URL and responds with a controllers method. This will generally return a view.
It makes it as easy to create something like this as adding a line like this
Route::get('home', 'PagesController#home');
to your routes file and when you go to example.com/home it will fire the controller called 'PagesController' and run its home method. Within this method you could return a view that will be the page that you want to display.
This can be expanded in other ways.
You could have another route that is nearly the same but have another method for when someone sends post data to the same controller.
Route::post('home', 'PagesController#submittedhome');
So now you have another route that will take a post input to that page and fire a completely different method from the same controller. These kind of controls + many many more can allow you to achieve what you want really easily and is part of the core fundamentals of laravel.
Here is the Routing page on the laravel page that can illuminate you a little more.
There are many frameworks that use the term url rewriting but obviously not referring to .htaccess. Frequently it's called routing. WordPress does this by using page slugs.
In WordPress, .htacces sends requests for existing files and directories directly through, bypassing WP. Anything not matching as described above must be a "virtual" page. and is sent to index.php
The URI is then parsed in one way or another usually involving regular expressions. Each part of the URI path correlates to a "slug", these are then used to create a database query to generate the relevant content.
There's a lot more going on in terms of selecting specific templates for certain slug types.
A low tech approach to achieve the same outcome without requiring routing is to create a folder with the desired name, and have an index.php (or index.html) within it. Then when the url is called - the default is to open the index file within the folder, even if it is not specified in the URL.
therefore
http://example.com/shop.php/product-category.php/games/
would be the equivalent of calling
http://example.com/shop.php/product-category.php/games/index.php
Note that I am NOT advocating this (I think it would get messy very quickly and there are way more efficient solutions), nor am I suggesting that the given examples are doing it this way, but I wanted to post this because it is a viable method to producing url's without file names or indexes listed. Just not a very good one IMO.
If someone could explain to what this system is called
It's called RewriteEngine and it's part of apache mod_rewrite, other web-servers have different mods, but this the most popular.
RewriteEngine on
RewriteRule ^shop/$ shop.php [L]
RewriteRule ^shop/products/(.*?)/$ products.php?type=$1 [L]
The 1st example will display the content of shop.php when a user accesses www.site.com/shop/
The 2nd example will send games, as argument ($1), to products.php?type=$1, if a user access www.site.com/shop/products/games/
[L] - is called a flag (L|last):
The [L] flag causes mod_rewrite to stop processing the rule set. In
most contexts, this means that if the rule matches, no further rules
will be processed. This corresponds to the last command in Perl, or
the break command in C. Use this flag to indicate that the current
rule should be applied immediately without considering further rules.
^ is relative to web root (somesite.com/^)
$ represents the end of the string (somesite.com/^somedir/test/$ this part will not be processed)
Resources:
Learn more about mod_rewrite and rewrite Flags

Htaccess rewrite for user profile and possible conflictions

I need to ask something about htaccess redirection. I know there are lots of questions about htaccess, rewrite and pretty profile urls, but I've never found real answer of my question and I hope I can find with your help.
That pretty url rules as you know would work like changing "mydomain.com/profile.php?username=myuser" to "mydomain.com/myuser".
But let's say I have a rewrite rule for my login url : www.mydomain.com/login
That means if user try to have exact same username as "login" how could you handle that possible confliction on rewrite?
actually possible solution might be minimum character limitation like minimum 6 chars, but it's not looking elegant since you loose your option to use more than 6 chars like "/resetpassword".
Probably a "banned words" kind of array control would be a solution when user picks a username but then you need to foresee all kind of possibilities which shouldn't be used.
Many of giant websites use this rewrite methods. Particularly Facebook uses "/username" kind of rule for pages and users in the same time.
Anyway, if someone has what is the magic behind that kind of url redirection/rewrite rules please help me out on this :)
Thanks
P.S. : I know there is another solution like "/user/username" but nowadays pointing directly to the base url and shortening full url is getting more and more popular, and I just need to understand possibilities on that.
Why not just have a login sub directory in the root of your site that contains the relevant files for logging a user in? That way, the rewrite rules in your htaccess file only have to deal with the whole user redirect stuff.
What you're looking for is something called "routes". They're typically implemented by MVC frameworks like Zend Framework, CakePHP of Symfony.
What they essentially do is forwarding every request to some index.php which in turn figures out from $_SERVER['REQUEST_URI'] which PHP files should handle the request.
I wouldn't recommend putting rewrite rules into your .htaccess file by PHP. Instead, try getting into PHP frameworks. They do the hard lifting for you.
Personally, I use Zend Framework. But I wouldn't recommend the new version 2 to beginners. Try ZF1. It's actually pretty easy to get into.

Rewriting url to hide index.php and to make query nice

I had developed project with custom MVC architecture. And I am new to Apache world, so I would appreciate help with this matter. On a Web I had found lots of tutorials, but no one like mine interests.
I have URL like this: http://knjiskicrv.comoj.com/index.php?page=book&id=1
I would like to be display like this: http://knjiskicrv.comoj.com/book/id/1
Or this: http://knjiskicrv.comoj.com/index.php?page=faq
Into this: http://knjiskicrv.comoj.com/faq
If there is no page in query (http://knjiskicrv.comoj.com/index.php), I would like to show: http://knjiskicrv.comoj.com/
Also with no page in query (http://knjiskicrv.comoj.com/index.php?category=2), it should be like this http://knjiskicrv.comoj.com/category/2
Hope someone will help. Thanks.
Actually, your problem is a two step proble. You first need to understand what is "Routing" in MVC. If you have your own implementation of an MVC like framework and you don't support routing, then it probably means you didn't even know how it worked before. (Sad but true)
In an MVC framework you setup routes using a ROUTER and the router analyses the urls for you saying HEY, i found this url that matches your request, go ahead and do work with it.
So then, your controller receives a request to route into itself and PARSES the url as he sees fit. Such as using explode('/', $_SERVER['REQUEST_URI']) and then reading the different parts of the url to map to expected variables.
All of this is very theoretical because there are ZILLIONS of way to implement it in a custom way. The only thing you will have to use is a little mod_rewrite magic to pass all requests to your index.php that will route everything. Look at the url below to learn about mod_rewrite, it's a VERY COMPLEX subject:
http://www.addedbytes.com/for-beginners/url-rewriting-for-beginners/
What i usually go for but i don't have access to it from home is something like this:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^assets/
RewriteRule .* index.php
This will redirect all traffic to index.php and you can then use $_SERVER['REQUEST_URI'] to analyze the request. Everything in assets/ folder will not be touched and work correctly.
Note, i built that part off my hat, it might not work...

Rewriting a CI url

I have never before rewritten a URL except for removing the index.php part of my CodeIgniter installs, and that I do by using a copy-pasted snippet in my .htaccess file. I haven't had the time to actually learn about what the snippet does; I'm basically very new to rewriting URLs.
I have a mobile version of my web application. I got as far as redirecting mobile users to a subdomain: m.myhost.tld. However, since I'm using (one) CodeIgniter (install), I have to send these mobile users to a mobile-specific controller, in my case /mobile/. So, the controller always shows up in my address bar.
I just don't think this is very clean, and I'm looking for a way to rewrite the URL; but truth be told, I'm not even sure if this is possible.. hence my question.
I want to get rid of the /mobile controller part. Is this possible?
Some examples:
My current mobile 'root' folder is
http://m.myhost.tld/mobile
I would like to turn this one into
http://m.myhost.tld/
At the moment, when I go to http://m.myhost.tld/, it redirects to the default controller for my CodeIgniter application, which is part of the 'desktop' version of the web app.
Another example:
Turning
http://m.myhost.tld/mobile#mobile/about
into
http://m.myhost.tld/#mobile/about
I'm not sure if I'm making any sense here. I am in my head, but like I said, I don't know what exactly is possible. If the user is on the m subdomain, I want to hide the /mobile part of my URLs. However, only when we're on the m subdomain, so the 'desktop' version (which sits at www ) does not get touched at all.
Like I said a couple of times now, I'm not sure what is possible and what I'm looking for might just be too complex or whatnot. I figured I would ask though, since learning by asking is what I do best. Please don't be too hard on me if this turns out to be a dumb question, sirs professionals ;)
EDIT:
I thought I'd edit because I don't want to come off wrong. I'm not necessarily looking for exact answers to my question. I also welcome documentation/tutorials/articles that might guide me to a solution. If I can manage to come up with a solution of my own, I will of course learn a lot more.
Thanks a lot.
This could be too simple of a solution but why not in your routing config do something simple like
in your config do something like
if ($_SERVER['SERVER_NAME'] == 'm.myhost.tld')
$route['default_controller'] = "mobile";
This would make the default controller mobil so you wouldn't have to have /mobile...
As i said maybe too simple
EDIT: Doesn't work, but maybe someone can turn it into something that does
Try this:
RewriteCond $1!^mobile/
RewriteCond %{HTTP_HOST} ^m\.myhost\.tld
RewriteRule (.*) /mobile/$1 [L]

passing GET parameters that look like URI directories

I've seen a lot of URIs that look something like this:
www.fakesite.net/stories/1234/man_invents_fire
and I was wondering if the /1234/man_invents_fire part of the URI are actually directories or if they are GET parameters (or something else). I've noticed that a lot of times the /man_invents_fire segment is unnecessary (can be removed with no consequences), which led me to believe that the /1234/ is the id number for the story in a database table (or something along those lines).
If those segments of the URI are GET parameters, is there an easy way of achieving this?
If they aren't, what is being done?
(also, I am aware that CodeIgnitor gives this kind of functionality, but I was curious to find out if it could be easily achieved without CodeIgnitor. I am, however, generally PHP, if that is relevant to an answer)
Thanks
Easiest thing to do is route everything into a main index.php file and figure out your routing from there by running $pieces = explode("/", $_SERVER['REQUEST_URI']);
After installing/enabling mod_rewrite, make sure allow override is not set to false in your apache config (to allow .htaccess to be read), then throw this in your docroot's .htaccess file.
<ifModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-s #Make sure the file doesn't actually exist (needed for not re-routing things like /images/header.jpg)
RewriteRule . /index.php [L,QSA] #re-route everything into index.php
</IfModule>
That is called url rewriting, google for it, you will find a lot of information about that.
Implementing this in PHP is typically done via an .htaccess file and using apache's mod_rewrite module.
They make the url like that so that people can easily bookmark it, and it can return safely in the search.
Depends on what language you're using to decode it. In this case, it appears "stories" is the main script, and "1234" is the id, and "man_invent_fires" is the title.
If you're using php, you can use the $_SERVER['PHP_SELF'] or $_SERVER['REQUEST_URI'] variable to decode it.
If you're planning to make a website like that, certain safety must be kept in mind. Look them up in google, but key one to look out for is sql injectors.
Just like permalinks in WordPress, this is done typically done via Apache's mod_rewrite (or an equivalent thereof if not using Apache); however, you can also use a 404 error page handler to achieve the same result (but this is not usually recommended).
Typically, all page requests are redirected to a gateway that parses the requested URI to determine if it fits the specified pattern (in your case likely to be /{category}/{article_id}/{article_title}). From there, the gateway can typically use just the article_id to retrieve the appropriate content.
Depending on the system, category and article_title can usually be thrown away/ignored and are typically for SEO value; however, in some cases category might be used to augment article_id in some way (e.g.: to determine what DB table to query, etc).
MVC's, like Zend, also use a similar technique to determine which controller and method therein to execute. An example format for this type of use is /{module}/{controller}/{method}; however, this is highly customizable.
Well, you are kind of right in assuming that the 1234 and main_invents_fire are parameters. They are not truly GET parameters in the sense that the HTTP protocol describes them but they accomplish the same task, while keeping the URL "friendly". The technique is called URL rewriting and the web is full of info on this these days..
Here's an article about friendly URLs in PHP but I'm sure googling for the topic will render more useful results.
As some background information in addition to the answers before me, a URL is just that - a 'Uniform Resource Locator'. Although in the old days, it often used to map 1:1 to a file/directory structure, all that is required in the HTTP spec is to identify a certain resource. Basically that means that, given a certain string, it should indicate a certain 'resource' on the server. In practice, in a HTTP environment this is usually implemented with a rewriting mechanism such as mod_rewrite. RFC's such as this one: http://www.ietf.org/rfc/rfc1738.txt give a nice, albeit abstract, overview. The concepts only come to life after designing and implementing some non-obvious uses, though.
If you are using Symfony, then you can use the routing feature to do this.

Categories