我做了一个卷曲调用函数,如下所示:
public function curl($url, $post = array()){
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.12) Gecko/20070508 Firefox/1.5.0.12");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->ckfile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->ckfile);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
// curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_URL, $url);
if(!empty($post)){
$post_string = "";
foreach($post as $key=>$value) { $post_string .= $key.'='.urlencode($value).'&'; }
rtrim($post_string, '&');
curl_setopt($ch,CURLOPT_POST, count($post));
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
}
$res = curl_exec($ch);
if (curl_errno($ch)) {
$this->deliver_responce('201','Couldn\'t send request: ' . curl_error($ch));exit();
}
else {
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus == 200) {
//echo "Post Successfully!";
return true;
}
else{
$this->deliver_responce('200','Request failed: HTTP status code: ' . $resultStatus);exit();
}
}
}我必须用URL和数组来调用它,这是我想发布的。当数组有键和值时,它就工作了,但是当我有嵌套数组时,它就不能工作了。它的作用是:
array(
'id'=>1,
'name'=>'apple'
)但不是为
array(
'id'=>5,
'cmd'=>array('password','encrypt','decrypt')
)我认为问题在于:
foreach($post as $key=>$value) { $post_string .= $key.'='.urlencode($value).'&'; }但我不知道该怎么做。
发布于 2019-03-29 10:49:11
它解决了改变前端循环的问题
foreach($post as $key=>$value) {
if (is_array($value)) {
foreach ($value as $val) {
$post_string .= $key.'[]='.urlencode($val).'&';
}
}
else{
$post_string .= $key.'='.urlencode($value).'&';
}
}发布于 2019-03-28 07:42:57
要创建一个请求uri,有一个http_build_query函数:
if (!empty($post)) {
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($post));
}然而,根据manual (由我强调):
这个参数可以作为一个像‘.’一样的用户编码的字符串传递。或者是以字段名为键,字段数据为值的数组。
因此,您可以尝试直接传递$post数组,而无需将其转换为字符串。
发布于 2019-03-28 07:49:31
对于这种post数据,您应该使用JSON数据,并在服务器端解析json。但是,如果您无法控制要向其发送数据的url,则可以使用以下行发送嵌套数组。不需要手动转换数组inyo字符串。
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch, CURLOPT_POSTFIELDS, urldecode(http_build_query($post_array)));https://stackoverflow.com/questions/55392249
复制相似问题