最近在工作中需要請求第三方的一個java版的接口,起初是使用數組進行傳參,代碼寫完之後發現接口死活調試不通,總是提示傳參為空,糾結了很久之後,決定嘗試使用字串傳參的方式來請求接口,沒想到這次居然調試成功了,這讓我有了研究這兩者究竟有何區別的興趣。
本地的測試程式碼如下:
curl.php
<code><span><span><?php </span><span><span>function</span><span>curl_post</span><span>(<span>$url</span>, <span>$data</span>)</span>{</span><span>$ch</span> = curl_init(); curl_setopt(<span>$ch</span>, CURLOPT_URL, <span>$url</span>); curl_setopt(<span>$ch</span>, CURLOPT_RETURNTRANSFER, <span>1</span>); curl_setopt(<span>$ch</span>, CURLOPT_POST, <span>1</span>); curl_setopt(<span>$ch</span>, CURLOPT_POSTFIELDS, <span>$data</span>); <span>$output</span> = curl_exec(<span>$ch</span>); curl_close(<span>$ch</span>); <span>return</span><span>$output</span>; } <span>$params</span> = <span>array</span>(); <span>$params</span>[<span>'username'</span>] = <span>'ben'</span>; <span>$params</span>[<span>'password'</span>] = <span>'lalala'</span>; print_r(curl_post(<span>'http://localhost/curl/post.php'</span>, <span>$params</span>)); <span>$params</span> = <span>array</span>(); <span>$params</span>[<span>'username'</span>] = urlencode(<span>'ben'</span>); <span>$params</span>[<span>'password'</span>] = urlencode(<span>'lalala'</span>); <span>$paramsStr</span> = <span>"username={$params['username']}&password={$params['password']}"</span>; print_r(curl_post(<span>'http://localhost/curl/post.php'</span>, <span>$paramsStr</span>)); <span>?></span></span></span></code>
post.php
<code><span><?php </span><span>echo</span><span>"-------php://input-----<br>"</span>; var_dump(@file_get_contents(<span>'php://input'</span>)); <span>echo</span><span>"-------post-----<br>"</span>; var_dump(<span>$_POST</span>); <span>echo</span><span>"-------server-----<br>"</span>; var_dump(<span>$_SERVER</span>);</span></code>
執行結果可以參考如下截圖:
版權聲明:本文為部落客原創文章,轉載請註明出處和作者名,尊重別人也是尊重自己
以上就介紹了php使用curl的post方法字串和陣列傳值的區別,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。