Creating Friendly URLs in PHP
URLs like www.domain.com/profile/12345 offer a more user-friendly experience compared to a traditional URL with query parameters like www.domain.com/profile.php?u=12345. In PHP, this can be achieved using mod_rewrite, which is a feature of the Apache web server.
To set up mod_rewrite, add the following lines to your .htaccess file located in the root directory of your web application:
RewriteEngine on RewriteRule ^/profile/([0-9]+)$ /profile.php?id= [L]
This rule instructs the web server to rewrite any request that starts with /profile/ followed by one or more digits to the profile.php file, while passing the digits as the id query parameter.
Another option is to use ForceType, which forces certain paths to be handled by PHP. In your .htaccess file, add the following:
<Files profile> ForceType application/x-httpd-php </Files>
With this approach, index.php can then access the path information using the $_SERVER['PATH_INFO'] variable:
echo $_SERVER['PATH_INFO']; // outputs '/profile/12345'
In profile.php, you can use the $_SERVER['PATH_INFO'] variable to retrieve the user ID and display the respective profile. By combining mod_rewrite or ForceType with PHP, you can create clean and user-friendly URLs for your web application.
The above is the detailed content of How Can I Create Clean and User-Friendly URLs in PHP?. For more information, please follow other related articles on the PHP Chinese website!