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使用SocketServer模块编写基本服务器程序的教程

SocketServer简化了网络服务器的编写。它有4个类:TCPServer,UDPServer,UnixStreamServer,UnixDatagramServer。这4个类是同步...

PHP向socket服务器收发数据的方法

本文实例讲述了PHP向socket服务器收发数据的方法。分享给大家供大家参考。具体如下: 在PHP要向其它程序发送数据,则需要使用到php的socket功能来实例了,下面我们简单看一个实...

Python Web程序部署到Ubuntu服务器上的方法

Python Web程序部署到Ubuntu服务器上的方法

在本文记录了我在Ubuntu中部署Flask Web站点的过程, 其中包括用户创建、代码获取、Python3环境的安装、虚拟环境设置、uWSGI启动程序设置,并将Nginx作为前端反向代...

php实现从ftp服务器上下载文件树到本地电脑的程序

复制代码 代码如下:/* 用ftp_nlist()函授时,返回的数组值会有两种类型:因服务器不同而异 a:单独的文件名 b:包含目录的文件名。 如果挪用,请注意更改此处。 */ <...

python paramiko远程服务器终端操作过程解析

这篇文章主要介绍了python paramiko远程服务器终端操作过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.with...