很多时候,项目需要以web方式调用外部程序的接口,curl模拟提交便是极好的选择。
public static function curl_post($url, $data = array(), $header = array(), $timeout = 5, $port = 8080) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); //设置cURL允许执行的最长秒数。
//curl_setopt($ch, CURLOPT_PORT, $port);
!empty($header) && curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = array();
$result['result'] = curl_exec($ch);
if (0 != curl_errno($ch)) {
$result['error'] = "Error:\n" . curl_error($ch);
}
curl_close($ch);
return $result;
}
备注:
CURLOPT_TIMEOUT 用于防止请求页面对于无响应返回,自动停止请求外部url