views:

108

answers:

5

lets say i want to go to

http://example.com/something/a/few/directories/deep

is there a way I can process this in PHP without having to make those directories? I just want to get everything after the domain name as a variable and work from there.

A: 

This actually is not a PHP5-related quesion - URL rewriting is part of your webserver.

You can, when you use mod_rewrite on Apache (don't know about IIS, but there likely is something similar).

Martin Hohenberg
+2  A: 

The most common way of doing this is by using mod_rewrite. (There in an introduction to this at http://articles.sitepoint.com/article/guide-url-rewriting). This allows you to internally map these friendly URLs to query parameters passed to your PHP script.

Theo Spears
+1  A: 

You do not need mod_rewrite to handle such a scenario. Most of the popular PHP frameworks currently support URI segment parsing. This is a simple example which still leaves a few security holes to be patched up.

You could handle this by taking one of the global $_SERVER variables and splitting it on forward slashes like so:

if (!empty($_SERVER['REQUEST_URI'])) {
    $segments = explode('/', $_SERVER['REQUEST_URI']);
}

The $segments variable will now contain an array of segments to iterate over.

cballou
you still need mod_rewrite to redirect all calls to the singular PHP script ;)
Kent Fredric
You need mod_rewrite or some other mechanism to map all these different requests to a php script which does this segmentation (known commonly as routing).
rojoca
@Kent, kudos. I'm kicking myself for this one.
cballou
+2  A: 

Sure. You don't even need mod_rewrite if the beginning is constant or has only a few possible values. Make a php file named something (no extension) and tell Apache (via a SetHandler or similar directive) to treat it as PHP. Then, examine $_SERVER['PATH_INFO'] in the script, which will look like a/few/directories/deep IIRC. You can use that to route your request however you like.

Alternatively. as Martin says, use a simple mod_rewrite rule to rewrite it to /dispatch.php/something/a/few/directories/deep and then you have the whole path in PATH_INFO.

Walter Mundt
+1  A: 

Assuming you are using apache...

Add a re-write rule (in your vhost conf or just drop .htaccess file in you doc root), to point everything to index.php. Then inside of your index.php, parse the request uri and extract path

RewriteEngine on
RewriteRule ^.*$ index.php [L,QSA]

index.php:
$filepath = $_SERVER['REQUEST_URI'];
$filepath = ltrim($myname, '/'); //strip leading slash if you want.

discovlad
This is about the maximum amount of mod_rewrite rules you want.
staticsan