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
Release: 2024-12-29 12:30:14
Original
834 people have browsed it

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

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

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();
    }
}
Copy after login

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!

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