How to manually create Friendly URLs? (PHP)
So I have created simple php file which echos requested string. Now it has form echo.php?string=bla+bla+bla&font=times
I want to see it like echo/bla+bla+bla/times
How to do such thing (not using external libs)?
views:
124answers:
6You will have to use the Rewrite engine which is the mod_rewrite in apache server.
To turn echo.php
into echo
you'll need to use a rewriting facility for your web server. If you're running Apache, mod_rewrite is king.
For the rest of it, you just need to parse $_SERVER['REQUEST_URI']
using a regex. You can use mod_rewrite to do this part also, but in case that's not an option, it can be done in straight PHP.
This is typically done with the mod_rewrite
Apache extension. In the .htaccess file, you would put something like:
RewriteEngine On
RewriteRule ^echo/(.+?)/(.+)$ echo.php?string=$1&font=$2 [L]
The first line activates mod_rewrite
. The second sets up a regular expression to route requests matching that pattern to the PHP file you want.
Have a look at the .htaccess file that is generated in a new Zend Framework project. You can use it without the rest of the framework or use it as an example for your own URL-rewriting method.
An alternative to rewriting the URL through mod_rewrite, just set a php file to be the 404 error handler. That file can analyze the URL and determine how it should be processed.
$path_parts = explode('/', $_SERVER['PATH_INFO']);
echo $path_parts[0]. ', '.$path_parts[1].' font';
For performance reasons, you wouldn't want to configure apache to not send certain file types (i.e. gif, jpg, png, etc) to PHP for handling.
While there are a number of different things you can do, as mentioned in the responses, you can't do it without adjusting configurations in the web server.
Similar to the 404 handler idea, with a very simple RewriteRule you can easily move the URL rewriting management to PHP, which might be easier for you:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . rewrite.php [L]
In rewrite.php
you have an array of RegEx URL patterns. These can be used to match the current URL (use $_SERVER['REQUEST_URI']
) and hand over parts of the URL to a real file. The parameters can then just be put into the $_GET
array and the correct file can be included.
As an example, the array could look like this:
$rules = array(
array(
'articles/view/([0-9]+)',
'articles.php?id=$1'
),
array(
'articles/delete/([0-9]+)',
'articles.php?id=$1&action=delete'
),
);