本文将介绍如何通过header发送自定义数据。发送请求时,除了可以使用$_GET/$_POST发送数据,也可以把数据放在header中传输过去。
发送header:
我们定义了三个参数,token、language、region,放入header发送过去
<code><span><span><?php </span><span>$url</span> = <span>'http://www.example.com'</span>; <span>$header</span> = <span>array</span>(<span>'token:JxRaZezavm3HXM3d9pWnYiqqQC1SJbsU'</span>,<span>'language:zh'</span>,<span>'region:GZ'</span>); <span>$content</span> = <span>array</span>( <span>'name'</span> => <span>'fdipzone'</span> ); <span>$response</span> = tocurl(<span>$url</span>, <span>$header</span>, <span>$content</span>); <span>$data</span> = json_decode(<span>$response</span>, <span>true</span>); <span>echo</span><span>'POST data:'</span>; <span>echo</span><span>'<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">'
'
接收header
我们可以在$_SERVER中获取header数据,自定义的数据都是使用HTTP_作为前缀的,所以可以把HTTP_前缀的数据读出。
<code><span><span><?php </span><span>$post_data</span> = <span>$_POST</span>; <span>$header</span> = get_all_headers(); <span>$ret</span> = <span>array</span>(); <span>$ret</span>[<span>'post'</span>] = <span>$post_data</span>; <span>$ret</span>[<span>'header'</span>] = <span>$header</span>; header(<span>'content-type:application/json;charset=utf8'</span>); <span>echo</span> json_encode(<span>$ret</span>, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT); <span>/** * 获取自定义的header数据 */</span><span><span>function</span><span>get_all_headers</span><span>()</span>{</span><span>// 忽略获取的header数据</span><span>$ignore</span> = <span>array</span>(<span>'host'</span>,<span>'accept'</span>,<span>'content-length'</span>,<span>'content-type'</span>); <span>$headers</span> = <span>array</span>(); <span>foreach</span>(<span>$_SERVER</span><span>as</span><span>$key</span>=><span>$value</span>){ <span>if</span>(substr(<span>$key</span>, <span>0</span>, <span>5</span>)===<span>'HTTP_'</span>){ <span>$key</span> = substr(<span>$key</span>, <span>5</span>); <span>$key</span> = str_replace(<span>'_'</span>, <span>' '</span>, <span>$key</span>); <span>$key</span> = str_replace(<span>' '</span>, <span>'-'</span>, <span>$key</span>); <span>$key</span> = strtolower(<span>$key</span>); <span>if</span>(!in_array(<span>$key</span>, <span>$ignore</span>)){ <span>$headers</span>[<span>$key</span>] = <span>$value</span>; } } } <span>return</span><span>$headers</span>; } <span>?></span></span></span></code>
输出:
<code>POST data: <span>Array</span> ( [name] => fdipzone ) Header data: <span>Array</span> ( [token] => JxRaZezavm3HXM3d9pWnYiqqQC1SJbsU [language] => zh [region] => GZ )</code>
以上就介绍了php通过header发送自定义数据,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。