Home Backend Development PHP Tutorial Introduction to the mechanism of implementing simple pseudo-static URL in PHP

Introduction to the mechanism of implementing simple pseudo-static URL in PHP

Jul 25, 2016 am 09:05 AM

  1. RewriteEngine On
  2. RewriteRule ^index.php$ - [L]
  3. RewriteCond %{REQUEST_FILENAME} !-f
  4. RewriteCond %{REQUEST_FILENAME} !-d
  5. RewriteRule (.+) index.php/$1 [L]
Copy code

The above code is to import the URL structure into index.php. The specific rewrite details will not be described in detail.

2. Set up a routing rule configuration file routes.php in PHP. I simply used a hash array to write the rules:

  1. /**
  2. * Instructions for writing routing configuration files:
  3. * Routing configuration is in an array array, and one record represents a rule
  4. * The data of the array key represents the matching path format: use a specific string identifier such as: '/{id}'
  5. * The string can contain specific variables, all variables are wrapped in braces {}
  6. * The array value is an array array, which performs specific processing on the variables in the path in the key
  7. * The variables are written in the key of the array, The specification is written in the value of the array, such as: array('id'=>'/d+/','_m'=>'frontpage','_a'=>'index')
  8. * The specification is divided into two categories :
  9. * 1. Format judgment: For example, '/{id}'=> array('id'=>'/d+/','_m'=>'frontpage','_a'=>'index '), for example, 'id'=>'/d+/' is a format judgment,
  10. * means that the id variable can only be a number, and only regular expressions can be used after the format judgment. Since PHP does not have a regular class, I Specify strings in the format of '/XXX/' and '#XXX#' as regular expressions
  11. * 2. Default parameters: For example, '/{id}'=> array('id'=>'/d+/' ,'_m'=>'frontpage','_a'=>'index') for example, where '_m'=>'frontpage' is a default parameter,
  12. * because the previous path does not have _m and _ a information, so the default parameters will be used as the values ​​of _m and _a later
  13. *
  14. * So for the rule '/{id}'=> array('id'=>'/d+/','_m' =>'frontpage','_a'=>'index'). When I pass in /3, the system will convert it into index.php?_m=frontpage&_a=index&id=3
  15. *
  16. * The rule matching is to match one by one in the order of the $routes array. Once matched, it will not match downwards. Therefore, some specific matching rules should be placed at the front and general ones at the back.
  17. * Otherwise, specific matching rules may not be executed
  18. */
  19. $routes= array(
  20. '/' => array('_m'=>'wp_frontpage','_a'=>'index'),
  21. '/{id}'=> array('id'=>'/d+/','_m'=>'wp_frontpage','_a'=>'index'),
  22. '/{_m }/{_a}/{id}'=> array('id'=>'/d+/'),
  23. '/{_m}/{_a}'=> array()
  24. );
Copy code

3. The most complex and important part of the routing mechanism is the parser. The parser consists of two classes (perhaps poorly named). One is Route, which is the external interface of the entire parser and is used to parse rules, match and convert URLs. However, it is just a proxy, and the actual operation is not performed directly by it. One is RoutePattern. Each RoutePattern instance corresponds to a record in the rule array. A Route instance contains multiple RoutePatterns, and all operations in Route will call all internal RoutePattern instance operations and integrate them.

  1. class Route
  2. {
  3. private static $instance = null;
  4. private $routepatterns=array();
  5. private function __construct()
  6. {
  7. $routes = array();
  8. include ROOT."/ routes.php";
  9. foreach($routes as $key=>$value){
  10. $this->routepatterns[]=new RoutePattern($key,$value);
  11. }
  12. if(!isset($ _SERVER['PATH_INFO'])) return false;
  13. $urlpath= $_SERVER['PATH_INFO'];
  14. $ismatch=$this->match_url($urlpath);
  15. $strip_urlpath=str_replace('/','' ,$urlpath);
  16. if(!$ismatch&&!emptyempty($strip_urlpath)){
  17. Content::redirect(PAGE_404);
  18. }
  19. }
  20. /**
  21. * Use routing rules to match the corresponding url address. If the match is successful, put the corresponding url parameters into $_GET
  22. * @param string url address
  23. * @return bool Whether the match is successful
  24. */
  25. public function match_url($urlpath) {
  26. foreach($this->routepatterns as $router){
  27. $urlargs=$router->match_url($urlpath);
  28. if($urlargs!==false){
  29. $_GET=array_merge($urlargs, $_GET);
  30. return true;
  31. }
  32. }
  33. return false;
  34. }
  35. public function rewrite_url($urlparams){
  36. foreach($this->routepatterns as $router){
  37. $urlstr=$router-> ;rewrite_url($urlparams);
  38. if($urlstr!==false){
  39. return $urlstr;
  40. }
  41. }
  42. $actualparams=array();
  43. foreach($urlparams as $arg=>$val){
  44. $actualparams[]=$arg."=".urlencode($val);
  45. }
  46. $actualparamstr=implode('&', $actualparams);
  47. $rewriteurl="/index.php";
  48. if(! emptyempty($rewriteurl))$rewriteurl.="?{$actualparamstr}";
  49. return $rewriteurl;
  50. }
  51. public static function init()
  52. {
  53. if (null == self::$instance) {
  54. self ::$instance = new Route();
  55. }
  56. return self::$instance;
  57. }
  58. }
  59. class RoutePattern{
  60. //...
  61. }
Copy code

About routing The main details of configuration file parsing are all in the RoutePattern class. Regarding the details of rule parsing, URL matching and URL conversion in RoutePattern, the space and energy are limited, so we will not introduce them in detail today. We will analyze them in detail next time.



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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles