當前位置:才華齋>計算機>php語言>

php中curlpost 時出現的問題解決

php語言 閱讀(3.04W)

文章主要介紹了php curl post 時出現問題的解決方法,需要的朋友可以參考下,就跟隨本站小編一起去了解下吧,想了解更多相關資訊請持續關注我們應屆畢業生考試網!

php中curlpost 時出現的問題解決

在 中以 POST 方式向 提交資料,但是 下就是無法接收到資料,而 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, '');

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);

也就是將所要提交的資料以陣列的形式通過 POST 傳送,而這樣就會導致 CURL 使用“錯誤"的編碼“multipart/form-data",其效果相當於我們直接以“<form method="post" action="" enctype="multipart/form-data">"這樣的表單來完成操作,大家可以試試,這時的“"是無論如何也無法通過 $_POST 來接收資料的。

所以,正確的做法應該是將上述範例程式碼中的 $data 由陣列變為經 urlencode() 編碼後的

  【相關閱讀】

  php的curl實現get和post的程式碼

程式碼實現:

1、http的get實現

複製程式碼 程式碼如下:

$ch = curl_init("") ;

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;

curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;

$output = curl_exec($ch) ;

$fh = fopen("", 'w') ;

fwrite($fh, $output) ;

fclose($fh) ;

2、http的post實現

複製程式碼 程式碼如下:

//extract data from the post

extract($_POST) ;

//set POST variables

$url = '' ;

$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) ;