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
DDDOriginal
2025-01-01 00:01:16483browse

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

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

www.domain.com/profile/12345

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=

This rule maps requests from:

/news.php?news_id=63

to:

/news/63.html

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>

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'
?>

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:
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