Home > Backend Development > PHP Tutorial > How Can I Create Clean and User-Friendly URLs in PHP?

How Can I Create Clean and User-Friendly URLs in PHP?

Mary-Kate Olsen
Release: 2024-12-19 12:28:10
Original
805 people have browsed it

How Can I Create Clean and User-Friendly URLs in PHP?

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]
Copy after login

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>
Copy after login

With this approach, index.php can then access the path information using the $_SERVER['PATH_INFO'] variable:

echo $_SERVER['PATH_INFO']; // outputs '/profile/12345'
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template