Home >Backend Development >PHP Tutorial >How to Rewrite URLs in PHP: `.htaccess` vs. PHP Approach?

How to Rewrite URLs in PHP: `.htaccess` vs. PHP Approach?

Susan Sarandon
Susan SarandonOriginal
2024-12-29 12:30:14853browse

How to Rewrite URLs in PHP:  `.htaccess` vs. PHP Approach?

URL Rewriting with PHP

Creating user-friendly URLs is an essential aspect of web development. Rewriting URLs involves transforming complex and verbose URLs into more concise and meaningful ones.

How to Convert a URL from 'picture.php?id=51' to 'picture.php/Some-text-goes-here/51'?

There are two primary methods for URL rewriting in PHP:

1. .htaccess with mod_rewrite

Create a .htaccess file in the root directory and add the following code:

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

This instructs Apache to use mod_rewrite and rewrite URLs matching the specified pattern to the desired format.

2. PHP

In the .htaccess file, add:

FallbackResource /index.php

In index.php, you can implement URL parsing and rewriting using the following code:

$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();
    }
}

This approach allows for more flexibility and can be used to implement complex URL parsing rules.

The above is the detailed content of How to Rewrite URLs in PHP: `.htaccess` vs. PHP Approach?. 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