php post请求 post提交代码

PHP 1050 0 2020-07-10

php post请求 post提交代码

常规方法post请求:

function sendPost($url, $post_data) {
  $postdata = http_build_query($post_data);
  $options = array(
    'http' => array(
      'method' => 'POST',
      'header' => 'Content-type:application/x-www-form-urlencoded',
      'content' => $postdata,
      'timeout' => 5 // 超时时间(单位:s)
    )
  );
  $context = stream_context_create($options);
  $result  = file_get_contents($url, false, $context);
  return $result;
}


curl方法post请求:

function sendPost($url,$data=array()){
  $ch = curl_init();
  //设置选项,包括URL
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch,CURLOPT_TIMEOUT,5); //定义超时5秒钟 
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));  //所需传的数组用http_bulid_query()函数处理一下
  $result = curl_exec($ch);
  $errorCode = curl_errno($ch);
  //释放curl句柄
  curl_close($ch);
  if(0 !== $errorCode) { return false; }
  return $result;
}


调用示例:

$url='http://www.hilo8.com/xxx';
$data=array('act'=>'abc','id'=>168);
$res = sendPost($url, $data);
echo $res;


上一篇:PHP字符串转数组或数组转字符串

下一篇:php7与php5都有哪些区别,性能怎样?

讨论数量:0

请先登录再发表讨论。 2024-04-17

天涯网魂
3 杠 5 星
TA 的文章
TA 的随言
TA 的资源链