php 发送请求-php发送post请求的三种方式

2023-08-24 0 5,153 百度已收录

php发送post请求的三种方式

更新时间:2014年2月11日 09:16:22 贡献者:zxhpj

php 发送请求-php发送post请求的三种方式

本文主要介绍PHP发送post请求的三种方式,分别使用curl、file_get_content、fsocket来实现post提交数据。 有需要的同学可以参考以下

方法一:

/**
 * 发送post请求
 * @param string $url 请求地址
 * @param array $post_data post键值对数据
 * @return string
 */
function send_post($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' => 15 * 60 // 超时时间(单位:s)
    )
  );
  $context = stream_context_create($options);
  $result = file_get_contents($url, false, $context);
  return $result;
}
//使用方法
$post_data = array(
  'username' => 'stclair2201',
  'password' => 'handan'
);
send_post('https://www.jb51.net', $post_data);

方法二:Socket版本


方法三:卷曲版


其他网友的做法是这样的:

php 发送请求-php发送post请求的三种方式

class Request{
  public static function post($url, $post_data = '', $timeout = 5){//curl
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_POST, 1);
    if($post_data != ''){
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    }
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $file_contents = curl_exec($ch);
    curl_close($ch);
    return $file_contents;
  }
  public static function post2($url, $data){//file_get_content
    
    $postdata = http_build_query(
      $data
    );
    
    $opts = array('http' =>
           array(
             'method' => 'POST',
             'header' => 'Content-type: application/x-www-form-urlencoded',
             'content' => $postdata
           )
    );
    
    $context = stream_context_create($opts);
    $result = file_get_contents($url, false, $context);
    return $result;
  }
  public static function post3($host,$path,$query,$others=''){//fsocket
    $post="POST $path HTTP/1.1rnHost: $hostrn";
    $post.="Content-type: application/x-www-form-";
    $post.="urlencodedrn${others}";
    $post.="User-Agent: Mozilla 4.0rnContent-length: ";
    $post.=strlen($query)."rnConnection: closernrn$query";
    $h=fsockopen($host,80);
    fwrite($h,$post);
    for($a=0,$r='';!$a;){
        $b=fread($h,8192);
        $r.=$b;
        $a=(($b=='')?1:0);
      }
    fclose($h);
    return $r;
  }
}

大家可以根据自己的需要选择适合自己的。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悟空资源网 php php 发送请求-php发送post请求的三种方式 https://www.wkzy.net/game/148932.html

常见问题

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务