NYCPHP Meetup

NYPHP.org

[nycphp-talk] Friendly URL's

Hans Zaunere lists at zaunere.com
Tue Nov 22 15:00:49 EST 2005



Stefan Klopp wrote on Monday, November 21, 2005 3:06 PM:
> Hello All,
> 
> I wanted to get your feedback on the best (and
> securest) way to do friendly URL's. I currently have
> implemented a simple one that basically appends
> directories onto the end of the php file, for example:
> 
> http://www.example.com/script.php/variable1/variable2/
> 
> To get the variables I am splitting on / in the
> $_SERVER['PATH_INFO']. This appears to work quite well
> for me. However the only problem I am facing now is
> when my page has included header information such as
> CSS or javascript. Since the includes are not full URL
> they try to find the files in:
> 
> http://www.example.com/script.php/variable1/variable2/
> 
> instead of in:
> 
> http://www.example.com/
> 
> Now I know I can do this via mod_rewrite but I would
> rather keep it all in the php. So one way I found
> around this was to put:
> 
>         $path = preg_split("/\//",
> $_SERVER['PATH_INFO']);
>         $file = array_pop($path);
>         if (preg_match("/\.(js)$/", $file)) {
>             include($file);
>             exit;
>         }
>         if (preg_match("/\.(jpg|gif|png|css)$/",
> $file)) {
>             $extra_path = array_pop($path);
>             include($extra_path . "/" .$file);
>             exit;
>         }
> 
> Basically this just checks if the last block on the
> url is a file. If it is and is javascript simple
> include the file directly (from the current working
> dir). If it is a image or css file get the extra
> directory information then include the file.
> 
> Now again this works for my current app, however I
> very much fear doing a dynamic include. Can anyone
> think of a better way to handle this?

This is always an interesting problem; the filesystem/URL relationship.  So
far, there are a few of ways to handle this, most of which you've mentioned:

-- mod_rewrite
-- "fusebox" everything through index.php and *carefully* parse PATH_INFO
-- catch 404 errors and handle accordingly (either through include/require
or redirect)
-- create ghost directories with a single index.php that knows what to do
for that request

Non of which are very elegant IMO.

The main problem is that PHP can't reach far enough up into Apache's request
stages to truly deal with non-existent filesystem paths.  AFAIK, both Python
and Perl can.  There's another option, apache_hooks, that does allow the
same level of Apache/PHP interaction as lets say Apache/mod_perl.  However,
development seems to have stalled, and it's still in a very experimental
stage from what I hear.  One day, perhaps, we can get it back into action
again :)


---
Hans Zaunere / President / New York PHP
   www.nyphp.org  /  www.nyphp.com





More information about the talk mailing list