.htaccess URL rewrite with random parameters - php

I'm currently writing a PHP app and am about to create various controllers. Currently I have one controller with certain method, so the URL looks like this:
http://somewebsite.com/index.php?c=controller&a=action
It's being rewritten to this:
http://somewebsite.com/controller/action
With this .htaccess file:
RewriteEngine On
RewriteRule ^([a-z]+)/([a-z]+)$ index.php?c=$1&a=$2 [NC]
What I want to achieve is the ability to rewrite URL with more than one controller (the more, the better), possibly in random order. Is there a more convenient way than rewriting every possible combination of URL parameters?

Many frameworks (Codeigniter, WordPress, Laravel, etc.) use an .htaccess file similar to the following:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
This rewrites all incoming URLs to be handled by the index.php file. You can then use $_SERVER['REQUEST_URI'] variable to get the exact request URI, parse it, and then handle it how you want.

if you're going for an arbitrary routing scheme, probably your best bet is to just pass the entire url string e.g. ^(.+)$ to index.php and let your php application split the string based on '/' and handle the array however makes sense for your application

Related

how to access functions within php files using .htacess like codeigniter

I have a scenario where I want something similar to Codeigniter.
In Codeigniter my url is like:
http://www.example.com/filename/methodname
Now I want similar thing but using plain core PHP and .htaccess.
How is that possible ?
I want to have a index.php inside my folder and then redirect the http requests accordingly.
Searching the web I found this :
RewriteEngine on
RewriteRule ^([a-z0-9_-]+)\.html$ index.php/page/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|asset|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]
But I have little knowledge of .htaccess and don't know how this could help.
So I want an answer with example to understand how this can be achieved using .htaccess.
What would I need to do on my PHP side ?
Routing
Having urls like /filename/methodname is generally called routing. You have half of it done already; what you show in .htaccess is the part that will redirect all traffic towards an index.php file.
# starts rewrite engine
RewriteEngine on
# redirects direct .html page calls to their corresponding pages
RewriteRule ^([a-z0-9_-]+)\.html$ index.php/page/$1 [L]
# for anything that is not a file
RewriteCond %{REQUEST_FILENAME} !-f
# and for anything that is not a directory
RewriteCond %{REQUEST_FILENAME} !-d
# except if it's a robot
RewriteCond $1 !^(index\.php|asset|robots\.txt)
# send all that to index.php
RewriteRule ^(.*)$ index.php/$1 [L]
That index file will then parse the url and call relevant handlers with relevant arguments based on what matched.
How to create one such parser, or router, is beyond the scope of a single answer, but basically depends on the use of $_SERVER['REQUEST_URI'] and an array of urls with their corresponding handlers.
Solution
This is a "solved problem", and while it is interesting to implement such a thing by yourself, I would recommend simply to use a library that does it for you. I personally use Fast-Route, a pretty straightforward library that allows for customization in the way you handle routes, but if you google for "php routers" you will find plenty of them.
Of Filename/Methodname
(opinions follow from here on)
This point should be rethinked. While with psr-4 (and psr-0, and probably psr-whatever) the correspondance between a specific class and its file is that the file is named after the class it contains, I believe it better to not think about this as filename/methodname but rather section/action, or whatever speaks best of what the url actually does.
Moreover, if you start using namespaces (which you should do if your oop code becomes slightly more complicated than a hello world page), you obviously won't pass full namespaces in urls, and they actually are irrelevant to your users.

.htaccess routing PHP

I am trying to write some simple routing in htaccess for PHP
My file looks like this for now:
RewriteEngine On
RewriteBase /webservices/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ server.php [QSA,L]
But it does nothing.
The thing that I want with htaccess is that all the calls to server.php are caught like this:
http://localhost:8888/webservices/server.php?username=test&password=test
to be written
http://localhost:8888/webservices/server/u/test/p/test/
Can someone help me with that?
It is actually working, because it redirects all queries to server.php. Therefore
http://localhost:8888/webservices/server/u/test/p/test/
can be handled by server.php, where you can easily catch parts of the URI using explode() on the $_SERVER["REQUEST_URI"] array. Forget the
http://localhost:8888/webservices/server.php?username=test&password=test
URL structure, you won't need it anymore, because using the .htaccess you've just written, you can dynamically handle every request to your server on server.php.
[QSA] in your .htaccess appends query string to the URI, which is not needed, because we want to get rid of it, right? Since you wont use that format, you can remove QSA flag.

mod_rewrite URL with many variables

I'm new to mod-rewrite and I have tried to mod-rewrite this url with no success.
URL structure like this :
http://mysite.com/script.php?id=15751890&xp=862297&wm=1721&ls=2725&he=63530&ks=23050&eath=53588&tk=10&ck=john&rk=37
I want to mod-rewrite it to :
http://mysite.com/script.php?id=15751890
Or :
http://mysite.com/15751890/862297/1721/2725/63530/23050/53588/10/john/37
I followed this http://wettone.com/code/clean-urls and this http://net.tutsplus.com/tutorials/other/a-deeper-look-at-mod_rewrite-for-apache/
But just can't do it write
What to type in htaccess file
Well, if you really want to write such a rewrite you should be able to use this in your htaccess file. There are probably better ways to handle the URL's however, I'm giving you what you asked for.
NOTE: I'm going off of the URL you provided.
RewriteEngine on
RewriteRule (.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*) script.php?id=$1&xp=$2&wm=$3&ls=$4&he=$5&ks=$6&eath=$7&tk=$8&ck=$9&rk=$10&%{QUERY_STRING}$ [L]
So you can use this type of URL with that rewrite.
http://mysite.com/15751890/862297/1721/2725/63530/23050/53588/10/john/37
Refer to my answer to this question:
php, handle unique URLs
This will give you this:
http://mysite.com/15751890/862297/1721/2725/63530/23050/53588/10/john/37
Instead of trying to figure out every rewrite combination possible, you should learn the MVC routing method.
This way, you route everything to a PHP router, and then direct the request to controllers, etc, as needed.
HTACCESS to rewrite everything:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
In your PHP script, you can use: $_SERVER['REQUEST_URI'] to get the requested URI.
Example: http://example.com/foo/bar/95 would rewrite to index.php, and $_SERVER['REQUEST_URI'] would then be /foo/bar/95 - and then you route accordingly.
Typically, your URL structure would be like:
http://example.com/controller/action/param_1/param_2/param_3/etc
Whereas "action" is just another name for a controllers method. How you code it is up to you.

PHP MVC with better htaccess

I have no idea how htaccess works, and the theory of it just wont connect in my head no matter how many tutorials I read.
I am building a simple MVC framework which works beautifully, except I don't like the way I am dealing with htaccess. To rewrite the URL's properly, this is what I am doing:
RewriteEngine on
RewriteRule ^users/([^/]+)(/([^/]+))?$ controller/users.php?method=$1&param=$3
If I add a new controller, I then have to go into htaccess and add a new line:
RewriteRule ^access/([^/]+)(/([^/]+))?$ controller/access.php?method=$1&param=$3
Is there a way to make it all automatic with wildcard fields so I don't have to access htaccess every time I do an update?
You can move logic for parsing query string into your framework/application. For this, make you rewrite rule like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
In this case, any request to server will be processed by index.php (if static file with same name not exists). And $_SERVER['REQUEST_URI'] will be equal real request uri - just parse it and use for your logic.
For example, if send /user/registry request with that .htaccess
$_SERVER['REQUEST_URI'] => '/user/registry'
You can try this:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)(/([^/]+))?$ controller/$1.php?method=$2&param=$4
The two extra rules will skip the rewrite if the file or directoy referenced actually exists on the disk, eg: it won't try to rewrite requests for http://site.com/images/logo.jpg.
I'd redirect all URIs to index.php and allow another well established MVC concept handle the controller dispatching: Routers.
Many (most) MVC (and some non-MVC) applications use this by default because it allows advanced routing techniques (not only controller/action structured URIs).
Controllers can "register" (new) routers and set their priorities. The application can run all routers (in order of priority) until one router finds a matching route (and is able to discern which controller should be used).
For example many blog-like applications will need SEO friendly URIs meaning something like category/subcategory/subsubcategory/blog-article.html. Many cms-like applications will need the same for their hierarchical pages: top-level-page/mid-level-page/low-level-page.html. As well as many eCommerce applications will want that for their products: category/subcategory/product.html.
The above URIs need a router which will check the database to find out which article/page/product has that URI-key.

How to Convert Query String to Segment URI?

I'm trying to convert a query string;
http://atwd/books/course?course_id=CC100&format=XML&submit=Submit
Into a segment URI;
http://atwd/books/course/CC100/XML
I'm working in CodeIgniter.
I was looking at a stackoverflow answer that said to check CodeIgniter's URL segment guide, but I don't think there's any information on how to convert a query string into a segment URI. There is, however a way to convert a segment URI into a query string, which is bringing up a load of results from Google too.
Following another stackoverflow answer, I tried this in my .htaccess file but nothing seemed to work
RewriteCond %{QUERY_STRING} ^course_id\=([^&]+)\&format\=([^&]+)$
RewriteRule ^$ /course/%1/format/%2 [R,L]
In my entire .htaccess file I have this;
<IfModule mod_rewrite.c>
RewriteEngine on
#Source: http://codeigniter.com/user_guide/general/urls.html
#Removal of index.php
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php?route/$1 [L]
#Source: https://stackoverflow.com/questions/3420204/htaccess-get-url-to-uri-segments
#Format Course function requests
RewriteBase /
RewriteCond %{QUERY_STRING} ^course_id\=([^&]+)\&format\=([^&]+)$
RewriteRule ^$ /course/%1/format/%2 [R,L]
</IfModule>
This is in my root directory of Codeigniter screenshot
My code in the .htaccess file isn't working, I refresh the page and nothing happens. The code to hide the index.php is working though. Does anyone know why?
The notion of "converting URLs" from one thing to another is completely ambiguous, see the top part of this answer for an explanation of what happens to URLs when redirecting or rewriting: https://stackoverflow.com/a/11711948/851273
There's 2 things that happen, and I'm going to take a wild stab and guess that you want the 2nd thing, since you're complaining that refreshing the page doesn't do anything.
When you type http://atwd/books/course?course_id=CC100&format=XML&submit=Submit into your browser, this is the request URI that gets sent through mod_rewrite: /books/course. In your rule, you are matching against a blank URI: RewriteRule ^$ /course/%1/format/%2 [R,L]. That's the first reason your rule doesn't work. The second reason why it doesn't work is because above that, everything except images and index.php and robots.txt is being routed through index.php. So even if you were matching against the right URI, it gets routed before your rule even gets to do anything.
You need to correct the pattern in your rule to match the URI that you expect to redirect, and you need to place this rule before the routing rule that you have. So everything should look roughly like this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{QUERY_STRING} ^course_id\=([^&]+)\&format\=([^&]+)$
RewriteRule ^/?books/course$ /course/%1/format/%2 [R,L]
#Source: http://codeigniter.com/user_guide/general/urls.html
#Removal of index.php
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php?route/$1 [L]
</IfModule>
You'll need to tweak the paths to make sure they match what you are actually looking for.
To both redirect the browser and internally rewrite back to your original URL, you need to do something different.
First, you need to make sure all of your links look like this: /course/CC100/format/XML. Change your CMS or static HTML so all the links show up that way.
Then, you need to change the rules around (all before your codeigniter routing rule) to be something liek this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
# redirect browser to a URI without the query string
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /books/course/?\?course_id=([^&]+)&format=([^&]+)
RewriteRule ^/?books/course$ /course/%2/format/%3? [R,L]
# internally rewrite query string-less request back to one with query strings
RewriteRule ^/?course/([^/]+)/format/([^/]+)$ /books/course?course_id=$1&format=$2&submit=Submit [L]
#Source: http://codeigniter.com/user_guide/general/urls.html
#Removal of index.php
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php?route/$1 [L]
</IfModule>
I'm not going to address the misunderstanding already addressed pretty well in the other answer and comments, and I can't speak for CodeIgniter specifically, but having given their URL routing docs a quick skim, it seems pretty similar to most web frameworks:
You probably just want to direct all traffic (that doesn't match physical files) to the frontend web controller (index.php) and handle the URL management in CodeIgniter's routing, not a htaccess file.
To do that, your htaccess could be as simple as:
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php [QSA,L]
</IfModule>
This, as I said, will redirect any traffic that doesn't match an physical file such as robots.txt or an image to your index.php.
Then, using the routing as described in the docs (http://ellislab.com/codeigniter/user-guide/general/routing.html) you can take in parameters and pass them to your controllers as you see fit, there is no need to 'convert' or 'map' anything, your URL's don't need to resolve to /?yada=yada internally, based on your routing rules CodeIgniter can work it out.
You'll need wildcard routes such as this from the docs:
$route['product/:id'] = "catalog/product_lookup";
A rough example of what yours might end up looking like would be something like:
$route['course/:id/format/:format'] = "course/something_or_other_action";
If I'm understanding you correctly, you might be over-thinking it. I have something similar in my own code.
I have a controller named Source. In that controller, I have the following method:
public function edit($source_id, $year)
{
# Code relevant to this method here
}
This produces: http://localhost/source/edit/12/2013, where 12 refers to $source_id and 2013 refers to $year. Each parameter that you add is automatically translated into its own URI segment. It required no .htaccess trickery or custom routes either.

Categories