URL rewriting redirecting to a single file - php

Let's say I have the project folder as follows:
folder/models
folder/view
folder/controls
folder/public
folder/library
Now let's say that the site folder is folder/public/ and inside that folder there's just one file called index.php. This file handle all the site page request via the GET parameter index.php?page=user for example will call the user.php file of the application in another folder. The point is that I'd like that an URL such as:
www.site.com/index.php?page=user&id=1
became
www.site.com/user/id/1
How can I do that?

This was taken from CakePHP .htacess rewrite rule:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>
It will render everything under your host
http://www.site.com/* --> http://www.site.com/index.php?url=*
from here your index.php could parse $_GET['url']
//e.g browser requests www.site.com/user/id/1
$url = $_GET['url']; // user/id/1
$params = explode("/",$url); // array(0=>"user",1=>"id",2=>"1")

RewriteRule ^user/id/([0-9]+)$ index.php?page=user&id=$1
But it sounds to me that you should use so called router, redirect all trafic to index.php...
http://anantgarg.com/2009/03/13/write-your-own-php-mvc-framework-part-1/ (check out this link)

In your case there is no point in using /id/, but here you go:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/id/(.*) index.php?page=$1&id=$2
Or what's a way better approach:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php
Then handle the request in your index.php file by checking $_SERVER['REQUEST_URI'] against the patter you dream up.

Without apache rewrite rule, a micro framework named Slim can makes routing and templating for your php project. You'll define your routes only in index.php file. Like ;
Slim::get('/', function () {
Slim::render('index.template');
});

You will be implementing what is called the Front Controller pattern. If you Google that you will find several php implementations. I thought this series on building your own php framework was good.
http://fuelyourcoding.com/php-frameworks-just-roll-your-own-part-1/

Are you using Apache as web server?
If yes you can use *mod_rewrite* to accomplish that.
I have not done this myself, so I can't give you detailed instructions, but searching with google, using a search string like "mod_rewrite examples" lands you a lot of seemingly good tutorials.

Related

mod_rewrite to replace beginning of %{REQUEST_URI} for Slim Framework

I have a web directory structure like so:
root
/content
/plugins
/myplugin
/Slim (folder containing Slim Framework)
index.php
/other_folder_1
/other_folder_2
.htaccess
index.html
I'm interested in what to specify in my .htaccess file in order to refer to a directory that isn't actually present on the server, but actually point to the Slim app in the /myplugin directory.
Here are a few example URLs, which I'd like users (or myself) to be able to use in the browser's location bar, or link with in documents:
1. http://example.com/nonexistent_dir
2. http://example.com/nonexistent_dir/info
3. http://example.com/nonexistent_dir/info/details
I'm trying to rewrite these URLs to the following:
1. http://example.com/content/plugins/myplugin/index.php
2. http://example.com/content/plugins/myplugin/index.php/info
3. http://example.com/content/plugins/myplugin/index.php/info/details
...which would all actually be handled by the index.php Slim Framework app in the /myplugin directory. It's important the apparent URLs remain as they appear in the first example, without being changed in the location bar.
Here's what is currently in the .htaccess file in the root directory:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/schedule [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /content/plugins/myplugin/index.php [QSA,NC,L]
</IfModule>
This redirects all 3 of the test examples to http://example.com/nonexistent_dir, using the / route. So my thought is that I should be capturing everything after the nonexistent_dir, whether it be something or nothing, and appending it to the end of the RewriteRule somehow. But I don't understand how.
I realize that using parentheses around an expression will enable me to use the contents as a variable, referred to it with $1 (or $2, $3... for multiples), but I don't know how to apply it to this solution.
Any help will be most appreciated.
Try:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^nonexistent_dir(/.*)?$ /content/plugins/myplugin/index.php$1 [L]
Slim actually discards the base directory, and sets $env['PATH_INFO'], taking the content of this variable to match against the specified routes.
For example, lets take a /sub/index.php (Slim index file) and this rewrite rule:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^somedir(/.*)?$ /sub/index.php$1 [L]
...and this route specification:
$app->route('/info', function() use ($app) { ... });
So, with a GET request to /somedir/info, Slim strips /somedir from REQUEST_URI and sets $env['PATH_INFO'] with value /info (this is actually done in the constructor of \Slim\Environment class).
Later, the Router class will match /info and execute the closure function.
If you want to pass parameters via url, the route would be, for example:
$app->get('/info/:param', function($param) use ($app){ ... })

URL parameters with PHP

Are there ways to pass variables in a URL similarly to GET data? For example, with slashes?
I currently have a single .php file which reloads a div with different content using javascript to navigate pages, but as you can imagine, the address in the address bar stays the same.
I want users to be able to link to different pages, but that isn't possible conventionally if there is only one file being viewed.
You're probably going to want to use something along the lines of Apache's mod_rewrite functionality.
This page has a nice example http://www.dynamicdrive.com/forums/showthread.php?51923-Pretty-URLs-with-basic-mod_rewrite-and-powerful-options-in-PHP
Try using:
$_SERVER['QUERY_STRING']; // Or
$_SERVER['PHP_SELF'];
If that doesn't help, post an example of what kind of URL you are trying to accomplish.
Something like this might do the trick;
place this in /yourdir/
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ yourindexfile.php?string=$1 [QSA,L]
All requests will be sent to yourindexfile.php via the URL. So http://localhost/yourdir/levelone becomes yourindexfile.php?string=levelone.
You'll be able to break down the string like so;
$query= explode('/', rtrim($_GET['string'], '/'));
the technology your looking for is .htaccess. technically this isn't possible, so you'll have to hack your mod rewrite to accomplish this.
RewriteRule On +FollowSymLinks
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(user)/([^\.]+)$ ./index.html?tab=user&name=$2
add this to your .htaccess page in your top directory. you'll have to alter your website structure a little bit. assuming that index.html is your index. this is a backwards rewrite so if one was to go to the page with the query string it won't redirect them to the former page and if one went to the page without the query string it will work like GET data still.
you GET this data with your php file using $_GET['tab'] and $_GET['name']
I think the Symfony Routing Component is what you need ;) Usable as a standalone component it powers your routing on steroids.
I'm doing it like this (in my like framework, which is a fork of the JREAM framework):
RewriteEngine On
#When using the script within a subfolder, put this path here, like /mysubfolder/
RewriteBase /mysubfolder/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
Then split the different URL segments:
$url = isset($_GET['url']) ? $_GET['url'] : null;
$url = rtrim($url, '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$url_array = explode('/', $url);
Now $url_array[0] usually defines your controller, $url_array[1] defines your action, $url_array[2] is the first paramter, $url_array[3] the second one etc...

Htaccess - redirect every request to a single page. Side effects?

I am creating my own mvc framework to use in little projects and by default, I am rewriting the url so that every single request goes to index.php. Index.php is only 4-5 lines, which calls the application class and then, the application class calls the corresponding controller and so on.
Basically, this is my htaccess file and index.php:
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA]
index.php:
<?php
include 'config.php';
$app = new Application();
?>
What I'd like to learn is whether this method has or could have any negative effects in the future in terms of speed and bandwidth. I appreciate your answers and comments.
If the class is there just to wrap you bootstrap stage, then it is pointless. simply have a plain file, which initializes application, load configuration and does all the wiring.
You could also want the index.php file to only contain one line: something that includes file outside DOCUMENT_ROOT. This way, if something goes tits-up with PHP extension, you won't show everyone your DB password and other sensitive details about your code.
As for your current .htaccess setup - no , it will not cause any additional bandwidth usage, but you might think about utilizing browser's cache for image and other assets.
Why redirect and not url rewrite?
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
as for example, this is used by a lot of applications/websites, and you have absolute control of the URL accessed.
And yes, redirecting is another call to the server.

URL Routing method for core php

I have web site in core php and I want to make my SEF URL.
In my web site for transferring control from one page to other i have used something like
header("Location: edit.php?id=12");
I read one article but couldn't get it how to implement it.
Link of article
So how i can make url to read like "mysite.com/usr/edit"
I read lot on google i got the idea that i need to do something in .htaccess but i dont know what needs to do with url in php so i dont have to change major code in site.
Thanks in advance.
You can do it with the .htaccess code given below:
RewriteEngine On
DirectoryIndex index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
after creating .htaccess file with above code. You will have all the stuff after the file name ex. "/usr/edit" in the GET parameter $GET['url']. After that you can do anything.
Here is the working example of my MVC framework: https://bitbucket.org/ManthanB/my-framework/
You can contact me for further information.

Site URLs using a PHP "pretty url" framework

I have been experimenting with the lightweight NiceDog PHP routing framework, which routes like this:
R('entries/(?<id>\d+)')
->controller('Entries_Controller')
->action('show')
->on('GET')
Now the .htaccess file is set up to do this redirect like so:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
My problem is when I want to make a URL to somewhere, it seems impossible to do so.
Say I've requested the page entries/5, and on that page I would like to link to another entry entries/6:
Next Entry
This resolves to the address http://localhost/folder/to/project/entries/5/entries/6
Not what I want.
The href /entries/6 would link to http://localhost/entries/6
Also not what I want.
To work around this, I created a function to handle this problem:
function url($route) {
return "http://localhost/folder/to/project/$route";
}
So I can now write
Next Entry
which now links to http://localhost/folder/to/project/entries/6, which is exactly what I want.
However, I have to do this for EVERY in-site link, and it seems like there could be a better solution that doesn't involve an externally created URL.
Is there a "better" way to fix this problem? Is this a "common" problem with PHP frameworks? (It seems it would be)
The easy alternative would be to use <base href="http://example.org/your/project/index" /> in your page templates <head>. But that's basically like having full URLs generated. And yes, it's also valid for XHTML and still in HTML5.
I don't know about NiceDog but other frameworks I have used have a built in function that can convert a route to the corresponding URL.
For example in Symfony this would look something like:
Link Text
The routing system will then reverse resolve this into the URL relative to any root you set in the config.
Could you use:
RewriteBase /folder/to/project/
in your htaccess file making
RewriteEngine On
RewriteBase /folder/to/project/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html

Categories