<span></span>Scenario: The project has two different ways of handling ajax requests and ordinary requests, such as error handling. When an error occurs when accessing through the browser, jump to the DEBUG page. As shown below (this is a framework written by myself, ThinkPHP of style copy, because I am just a pure technical person. Sorry - -):
OK Let’s get back to the topic. If it is an Ajax request, I need to return the information in JSON format. Convenient for front-end (JS, IOS, ANDROID, etc.). Such as:
Then, on the server side, we need a mark to help us identify whether this request is an ajax request or a normal request. What I refer to here is the JQuery method, and many people As we all know, js can be set through the setRequestHeader method of the XMLHttpRequest object. But what if the request is issued by the server through CURL. The processing method is as follows:
<span>function </span><span>Get</span><span>(</span><span>$url</span><span>)</span>
<span><span>{</span></span>
<span><span><span></span>$ch </span><span>= </span><span><em>curl_init</em></span><span>(); </span><span><em><span></span>curl_setopt</em></span><span>(</span><span>$ch</span><span>, </span><span><em>CURLOPT_URL</em></span><span>, </span><span>$url</span><span>); </span><span><em><span></span>curl_setopt</em></span><span>(</span><span>$ch</span><span>, </span><span><em>CURLOPT_HEADER</em></span><span>, </span><span>0</span><span>); </span><span><em><span></span>curl_setopt</em></span><span>(</span><span>$ch</span><span>, </span><span><em>CURLOPT_RETURNTRANSFER</em></span><span>, </span><span>1</span><span>);</span></span>
<span></span><pre class="brush:php;toolbar:false"><span><span><span></span>$HEADER </span><span>= </span><span>array</span><span>( </span><span><span></span></span><span>'X-REQUESTED-WITH: XMLHTTPREQUEST' </span><span><span></span>); </span><span><em><span></span>curl_setopt</em></span><span>(</span><span>$ch</span><span>, </span><span><em>CURLOPT_HTTPHEADER</em></span><span>, </span><span>$HEADER</span><span>); </span><span><span></span>$return </span><span>= </span><span><em>curl_exec</em></span><span>(</span><span>$ch</span><span>); </span><span><em><span></span>curl_close</em></span><span>(</span><span>$ch</span><span>); </span><span></span><span><span></span>return </span><span>$return</span><span>;</span></span>
<span><span>}</span></span>
<span>总结: 设置的头如: A-B-C, 在_SERVER变量中打印出来的key会变成 HTTP_A_B_C的形式.</span>
<span></span>
Copyright statement: This article is an original article by the blogger and may not be reproduced without the permission of the blogger.
The above introduces how PHP CURL simulates JQuery's Ajax request header and adds parameters that can be displayed in _SERVER, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.