php使用socket post数据到其它web服务器的方法

yipeiwu_com5年前服务器

本文实例讲述了php使用socket post数据到其它web服务器的方法。分享给大家供大家参考。具体实现方法如下:

function post_request($url, $data, $referer='') {
  // Convert the data array into URL Parameters like a=b&foo=bar etc.
  $data = http_build_query($data);
  // parse the given URL
  $url = parse_url($url);
  if ($url['scheme'] != 'http') { 
    die('Error: Only HTTP request are supported !');
  }
  // extract host and path:
  $host = $url['host'];
  $path = $url['path'];
  // open a socket connection on port 80 - timeout: 30 sec
  $fp = fsockopen($host, 80, $errno, $errstr, 30);
  if ($fp){
    // send the request headers:
    fputs($fp, "POST $path HTTP/1.1\r\n");
    fputs($fp, "Host: $host\r\n");
    if ($referer != '')
      fputs($fp, "Referer: $referer\r\n");
    fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
    fputs($fp, "Content-length: ". strlen($data) ."\r\n");
    fputs($fp, "Connection: close\r\n\r\n");
    fputs($fp, $data);
    $result = ''; 
    while(!feof($fp)) {
      // receive the results of the request
      $result .= fgets($fp, 128);
    }
  }
  else { 
    return array(
      'status' => 'err', 
      'error' => "$errstr ($errno)"
    );
  }
  // close the socket connection:
  fclose($fp);
  // split the result header from the content
  $result = explode("\r\n\r\n", $result, 2);
  $header = isset($result[0]) ? $result[0] : '';
  $content = isset($result[1]) ? $result[1] : '';
  // return as structured array:
  return array(
    'status' => 'ok',
    'header' => $header,
    'content' => $content
  );
}
//使用方法
// Submit those variables to the server
$post_data = array(
  'test' => 'foobar',
  'okay' => 'yes',
  'number' => 2
);
// Send a request to example.com 
$result = post_request('http://www.example.com/', $post_data);
if ($result['status'] == 'ok'){
  // Print headers 
  echo $result['header']; 
  echo '<hr />';
  // print the result of the whole request:
  echo $result['content'];
}
else {
  echo 'A error occured: ' . $result['error']; 
}

希望本文所述对大家的php程序设计有所帮助。

相关文章

python利用paramiko连接远程服务器执行命令的方法

python中的paramiko模块是用来实现ssh连接到远程服务器上的库,在进行连接的时候,可以用来执行命令,也可以用来上传文件。 1、得到一个连接的对象 在进行连接的时候,可以使用如...

利用Python如何批量更新服务器文件

前言 买了个Linux服务器,Centos系统,装了个宝塔搭建了10个网站,比如有时候要在某个文件上加点代码,就要依次去10个文件改动,虽然宝塔是可视化页面操作,不需要用命令,但是也麻烦...

Nginx服务器上安装并配置PHPMyAdmin的教程

一、 准备工作: 1. 如果mysql的root账号为空,需要设置root密码 CentOS下默认安装的mysql服务器,里面的root账号默认密码为空,首先为root设置一个密码 #m...

基于win2003虚拟机中apache服务器的访问

基于win2003虚拟机中apache服务器的访问

虽然在win2003配置PHP有点非主流,但你还是要会怎么弄。你也可以将本文的虚拟机看成是服务器,宿主机看成是客户端。 不像Linux系统,由于win2003有IIS的存在,占有了固有的...

python下paramiko模块实现ssh连接登录Linux服务器

本文实例讲述了python下paramiko模块实现ssh连接登录Linux服务器的方法。分享给大家供大家参考。具体分析如下: python下有个paramiko模块,这个模块可以实现s...