- 相關推薦
php中curlpost 時出現的問題解決
文章主要介紹了php curl post 時出現問題的解決方法,需要的朋友可以參考下,就跟隨百分網小編一起去了解下吧,想了解更多相關信息請持續關注我們應屆畢業生考試網!
在 a.php 中以 POST 方式向 b.php 提交數據,但是 b.php 下就是無法接收到數據,而 CURL 操作又顯示成功,非常詭異。原來,“傳遞一個數組到CURLOPT_POSTFIELDS,cURL會把數據編碼成 multipart/form-data,而然傳遞一個URL-encoded字符串時,數據會被編碼成 application/x-www-form-urlencoded。
",而和我一樣對 CURL 不太熟悉的人在編寫程序時,代碼往往是下面的樣子:
復制代碼 代碼如下:
$data = array( 'Title' => $title, 'Content' => $content, 'ComeFrom' => $comefrom );
curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
curl_setopt($ch, CURLOPT_URL, 'http://example.com/b.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
也就是將所要提交的數據以數組的形式通過 POST 發送,而這樣就會導致 CURL 使用“錯誤"的編碼“multipart/form-data",其效果相當于我們直接以“<form method="post" action="b.php" enctype="multipart/form-data">"這樣的表單來完成操作,大家可以試試,這時的“b.php"是無論如何也無法通過 $_POST 來接收數據的。
所以,正確的做法應該是將上述范例代碼中的 $data 由數組變為經 urlencode() 編碼后的
【相關閱讀】
php的curl實現get和post的代碼
代碼實現:
1、http的get實現
復制代碼 代碼如下:
$ch = curl_init("http://www.jb51.net/") ;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
$output = curl_exec($ch) ;
$fh = fopen("out.html", 'w') ;
fwrite($fh, $output) ;
fclose($fh) ;
2、http的post實現
復制代碼 代碼如下:
//extract data from the post
extract($_POST) ;
//set POST variables
$url = 'http://www.jb51.net/get-post.php' ;
$fields = array(
'lname'=>urlencode($last_name) ,
'fname'=>urlencode($first_name) ,
'title'=>urlencode($title) ,
'company'=>urlencode($institution) ,
'age'=>urlencode($age) ,
'email'=>urlencode($email) ,
'phone'=>urlencode($phone)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&' ; }
rtrim($fields_string ,'&') ;
//open connection
$ch = curl_init() ;
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL,$url) ;
curl_setopt($ch, CURLOPT_POST,count($fields)) ;
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string) ;
//execute post
$result = curl_exec($ch) ;
//close connection
curl_close($ch) ;
【php中curlpost 時出現的問題解決】相關文章:
PHP中json-encode格式中文問題解決辦法10-27
PHP中的Trait09-29
出現頻率最高的PHP面試題08-21
PHP中php://input和$-POST的區別08-26
PHP中的表單處理09-19
Session在PHP中的使用07-24
PHP中的Reload操作06-26
PHP中$-SERVER的詳解06-25
PHP中Json應用09-05