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

How Can I Create More User-Friendly URLs in PHP?

DDD
Release: 2025-01-01 00:01:16
Original
523 people have browsed it

How Can I Create More User-Friendly URLs in PHP?

Creating Friendly URLs in PHP

Oftentimes, URLs are generated in a way that displays information directly in the query string, such as:

www.domain.com/profile.php?u=12345
Copy after login

However, modern web design principles advocate for more user-friendly and readable URLs, like:

www.domain.com/profile/12345
Copy after login

To achieve this in PHP, consider utilizing one of the following methods:

Method 1: Using mod_rewrite in .htaccess

With mod_rewrite enabled in your .htaccess file, you can use a rule such as:

RewriteEngine on
RewriteRule ^/news/([0-9]+)\.html /news.php?news_id=
Copy after login

This rule maps requests from:

/news.php?news_id=63
Copy after login

to:

/news/63.html
Copy after login

Method 2: Forcing PHP Execution with ForceType

Another option is to use ForceType to redirect all requests to a specific path to be processed by PHP. In your .htaccess file, add the following:

<Files news>
    ForceType application/x-httpd-php
</Files>
Copy after login

This forces any request that includes "/news" in the path to be executed by PHP. Your index.php file can then process the request based on the $_SERVER['PATH_INFO'] variable:

<?php
    echo $_SERVER['PATH_INFO']; // Outputs '/63.html'
?>
Copy after login

The above is the detailed content of How Can I Create More User-Friendly URLs in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template