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实现简单http服务器

Python实现简单http服务器

写一个python脚本,实现简单的http服务器功能: 1.浏览器中输入网站地址:172.20.52.163:20014 2.server接到浏览器的请求后,读取本地的index.htm...

python3发送邮件需要经过代理服务器的示例代码

现象:已知,连接的WIFI网络需要通过代理服务器才能连接外网,按照正常的程序无法发送邮件,而直连一个没有代理的网络【如自己的wifi热点】,可以发送邮件。无法发送邮件的提示是: Time...

使用Python实现简单的服务器功能

socket接口是实际上是操作系统提供的系统调用。socket的使用并不局限于Python语言,你可以用C或者Java来写出同样的socket服务器,而所有语言使用socket的方式都类...

使用Python创建简单的HTTP服务器的方法步骤

如果需要一个简单的Web Server,而不是安装那些复杂的HTTP服务程序,比如:Apache,Nginx等。那么可以使用Python自带的包完成一个简单的内建 HTTP 服务器。于是...

php模拟服务器实现autoindex效果的方法

php模拟服务器实现autoindex效果的方法

本文实例讲述了php模拟服务器实现autoindex效果的方法。分享给大家供大家参考。具体实现方法如下: 1.PHP代码如下: 复制代码 代码如下:<?php //文件浏...