Home > Backend Development > PHP Tutorial > How Can I Implement URL Rewriting in PHP Using `.htaccess` or PHP's Built-in Functions?

How Can I Implement URL Rewriting in PHP Using `.htaccess` or PHP's Built-in Functions?

Barbara Streisand
Release: 2024-12-20 03:33:09
Original
1017 people have browsed it

How Can I Implement URL Rewriting in PHP Using `.htaccess` or PHP's Built-in Functions?

URL Rewriting in PHP: Creating Friendly URLs

Introduction

URL rewriting is a technique used to transform a complex, potentially lengthy URL into a more user-friendly and readable format. In this article, we'll explore how to implement URL rewriting in PHP using two different approaches: the .htaccess route and the PHP route.

The .htaccess Route with mod_rewrite

This method involves adding a .htaccess file to the root directory and configuring the Apache web server to use mod_rewrite. Here's an example RewriteRule:

RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=
Copy after login

This rule instructs the web server that any URL matching the pattern "Some-text-goes-here/" should be internally rewritten to "picture.php?id=" without being visible to the end user.

The PHP Route

An alternative approach is to use PHP to handle URL rewriting. This involves setting up a "FallbackResource" in .htaccess:

FallbackResource /index.php
Copy after login

This configuration tells the server to direct all requests to the index.php file if the requested file does not exist. In index.php, you can implement your own URL parsing logic:

$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);
            break;
        case 'more':
            ...
        default:
            header('HTTP/1.1 404 Not Found');
            Show404Error();
    }
}
Copy after login

This technique allows for greater flexibility in URL parsing and support for database-driven and conditional URLs.

The above is the detailed content of How Can I Implement URL Rewriting in PHP Using `.htaccess` or PHP's Built-in Functions?. 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