search
HomeBackend DevelopmentPHP TutorialThere are four methods to achieve pseudo-static in PHP, do you know them? , No. 4 Middle School_PHP Tutorial

There are four ways to achieve pseudo-static in PHP, do you think of them? , No. 4 Middle School

Speaking of the pseudo-static implementation plan, are you very happy to answer "It's simple, just configure the rewrite rules of apache and that's it"

But have you noticed this situation? You have recently developed a lot of new features. Several new features are added every day, and there are many pseudo-static configurations every day. It has only been two days since the operation and maintenance, and the classmates are willing to cooperate. After two days, the operation and maintenance Classmate Wei was about to scold him. Why don't you do it all at once and bother me every day because you are so numb and stupid? But, you are about to go online, and you have to ask the operation and maintenance classmates hard, and then say the most shameless words in the programmer world: "This is the last change", and then you have to change it again. , Sigh, your personality is completely ruined. . .

If you have such troubles, please read the following article to ensure that you will never ask for operation and maintenance again in the future, and you can do whatever you want. . .

So how many ways are there to implement pseudo-static in PHP? Personal opinions and statistics, there are four methods


1. Use apache’s URL rewriting rules. Everyone knows this. Configure it in apache. Here, students all made it. I only list a simple configuration

<span>RewriteEngine On
RewriteRule </span>^/test.html index.php?controller=index&action=test [L]

2. Use PHP's pathinfo. Have you seen some websites playing 'www.xxx.com/index.php/c/index/a/test/id/100' like this? Of course, this must be supported. You need to put the parameters in 'php.ini'

'cgi.fix_pathinfo' is set to 1. Take 'www.xxx.com/index.php/c/index/a/test/id/100' as an example

<span>echo</span> <span>$_SERVER</span>['PATH_INFO']; <span>//</span><span>输出'/c/index/a/test/id/100'</span>

At this point, you should understand it. You can then parse this paragraph and assign the actual address

3. Use the 404 mechanism. Generally, pseudo-static pages are pages that do not actually exist, so you can use apache 404 configuration. However, there are some problems. 'post' type requests will be abandoned, causing you to be unable to obtain '$ _POST',

But '$_GET' can still be obtained. Assume that the 404 page here is '404page.php', and the apache configuration is as follows:

ErrorDocument 404 /404page.php

Then embed the following code in '404page.php'

<span>header</span>("HTTP/1.1 200 OK"); <span>//</span><span>这里一定要有,不然状态就是404</span>

<span>$reqUrl</span> = <span>$_SERVER</span>['REQUEST_URI']; <span>//</span><span> 请求地址</span>

<span>/*</span><span>*
* 从URL中解析参数
</span><span>*/</span>
<span>function</span> parseUrlParams(<span>$queryUrl</span><span>)
{
    </span><span>$arr</span> = <span>explode</span>('?', <span>$queryUrl</span><span>);
    </span><span>parse_str</span>(<span>$arr</span>[1], <span>$param</span><span>);
    </span><span>if</span>(<span>$param</span><span>)
    {
        </span><span>foreach</span>(<span>$param</span> <span>as</span> <span>$key</span> => <span>$value</span><span>)
        {
            </span><span>$_GET</span>[<span>$key</span>] = <span>$value</span><span>;
        }
    }
}

parseUrlParams(</span><span>$reqUrl</span>); <span>//</span><span> url解析参数

//然后你就可以使用 $reqUrl 根据自己的规则匹配不同的实际请求地址</span>
<span>if</span>(<span>preg_match</span>('#^/test.html#is', <span>$reqUrl</span>, <span>$matches</span><span>))
{
   </span><span>include</span>('index.php'<span>);
   </span><span>die</span><span>();
}</span>

4. An improved version of method 3. Method 3 is equivalent to redirection in the internal mechanism of apache, causing the parameters passed by post(get) to be unobtainable. Analysis of the above actually shows that the relevant files cannot be found. When the server cannot find the relevant files, we specify a file for it. If it is OK, it will not need to jump. At this time, POST and the like will not be lost. The apache configuration is as follows:

<span>RewriteEngine On
RewriteCond </span>%{REQUEST_FILENAME} !-<span>f
RewriteCond </span>%{REQUEST_FILENAME} !-<span>d
RewriteRule </span>. index.php

The general meaning of the above configuration is that when the requested file or directory cannot be found, use 'index.php' in the root directory instead. Then you can get the relevant parameters in 'index.php' and parse to Actual request address

<span>/*</span><span>*
* 获取当前请求的URI地址
*@param void
*@author painsOnline
*@return string URI
</span><span>*/</span>
<span>function</span><span> getReqUri()
{
    </span><span>return</span> <span>trim</span>(<span>$_SERVER</span>["REQUEST_URI"<span>]);
}

</span><span>$reqUri</span> =<span> getReqUri();

</span><span>if</span>(<span>preg_match</span>('/^\/test.html/isU', <span>$reqUri</span><span>))
{</span><span>//</span><span>解析请求地址</span>
    <span>include</span> 'test.php'<span>;
    </span><span>exit</span><span>();
}</span>

I have little talent and knowledge, and I have some shortcomings. Welcome to make up for them

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1090919.htmlTechArticleThere are four ways to achieve pseudo-static in PHP, do you think of it? , No. 4 Middle School When talking about the pseudo-static implementation plan, do you readily answer "It's simple, just configure the rewrite rules of apache...
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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),