search
HomeBackend DevelopmentPHP TutorialAnswer several questions on PHPCHINA: URL mapping_PHP tutorial

After the PHPCHINA server was relocated, I basically couldn't access it and could only use a proxy, which was very frustrating. But I can't post or reply when using proxy. As a moderator, I feel deeply regretful. Today I used a proxy to go up and saw a few posts. I will answer them here by the way.

1. Let’s talk about URL mapping
Generally, there are two ways of url mapping. One is through mod_rewrite. There are many online teaching materials about this, so I won’t go into details. The other is to simulate in a program, such as /index.php/controller/action/var1/value1/var2/value2/ in zend Framework. In fact, the main method here is to use a unified input interface, then parse the URL, and finally forward it to the module in the corresponding controller.

I wrote two simple functions here to simulate.
The first function is mainly for address parsing, parsing out addresses similar to /index.php/controller/action/var1/value1/var2/value2/. Generally speaking, it needs to be parsed into three parts: controller, module, params.

Copy code The code is as follows:

 
/**
* Simple parsing of url routing, supporting /path/to/site/index.php/module/action/parm/value
* /path/to/site/index.php?/module/ Action/parm/value and
* /path/to/site/?/module/action/parm/value three forms of processing
*@param:null
*@return:router array
*/ 
function url_router(){
$path=strip_tags($_SERVER['REQUEST_URI']);
$strpos=strpos($path,'.php');
if($strpos){
$path=substr($path,$strpos+4); 
 }else{ 
  if(empty($_SERVER['QUERY_STRING'])){  
    $strpos=strpos($path,'? ');
if($strpos){
$path=substr($path,$strpos+1);
}else{
$path='';
            } 
                                                                                                                                                                                                                             $path=$_
if($path[0]=='/'){
$path=substr($path,1);
}
//Parse and route
if(! empty($path)){
$path=explode('/',$path);
$router['controller']=$path[0];
$router['action'] =(!empty($path[1]))?$path[1]:'index';
//print_r($path);
for($i=2;$i $params[$path[$i]]=(isset($path[$i+1]))?$path[$i+1]:' ';
}
$router['params']=$params;
}else{
//Default routing information
$router['controller']='index'; 🎜> $router['action']='index';
$router['params']=array();
}
return $router;
}
?>



The main url parsing function is completed here, and then the forwarding mapping is implemented. The following function is implemented (note that the implementation of this function is combined with my own architecture, so if you adopt it, you need to modify it accordingly. Of course, your If MVC is similar to zend Framework, it should not be much.)

Copy code The code is as follows:


function url_dispatch($router,$app_path='/app/controllers/')
{
require_once(SERVER_PATH.'/libs/controller.class.php');
$ controller=$router['controller'].'Controller';
//echo SERVER_PATH.$app_path.$controller.'.class.php';
if(!file_exists(SERVER_PATH.$app_path.$controller .'.class.php'))die('Missing necessary class!');
require_once(SERVER_PATH.$app_path.$controller.'.class.php');
$controller=new $controller ();
$controller->_setParam($router['params']);
$controller->{$router['action'].'Action'}();
return true;
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317725.htmlTechArticleAfter the PHPCHINA server was relocated, I basically couldn’t access it and could only use a proxy, which was very frustrating. But I can't post or reply when using proxy. As a moderator, I feel deeply regretful. I used a proxy to go up today and saw...
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.