URL Rewriting with PHP
When developing web applications, it is often desirable to create user-friendly URLs that are both concise and descriptive. A common approach to achieving this is through URL rewriting.
In this context, URL rewriting involves modifying the structure of a URL to make it more readable and cohesive. For instance, you may have a URL that appears as:
url.com/picture.php?id=51
You can modify this URL to:
picture.php/Some-text-goes-here/51
This rewritten URL retains the functionality of the original but offers improved readability.
To implement URL rewriting in PHP, you can leverage two primary approaches:
The .htaccess Route with mod_rewrite
RewriteEngine on RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=
This code enables Apache's mod_rewrite module and sets up a rule that rewrites URLs matching the regular expression to the desired format.
The PHP Route
FallbackResource /index.php
$path = ltrim($_SERVER['REQUEST_URI'], '/'); $elements = explode('/', $path); if (empty($elements[0])) { ShowHomepage(); } else switch (array_shift($elements)) { case 'Some-text-goes-here': ShowPicture($elements); // passes rest of parameters to internal function break; case 'more': ... default: header('HTTP/1.1 404 Not Found'); Show404Error(); }
This code parses the requested URI and directs the request to the appropriate internal function. The "Some-text-goes-here" case will handle the rewritten URLs.
Choosing the most suitable approach depends on the specific requirements of your project. The .htaccess method is simpler to implement, while the PHP route offers greater flexibility.
The above is the detailed content of How Can PHP Be Used to Rewrite URLs for Improved Readability and Functionality?. For more information, please follow other related articles on the PHP Chinese website!