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

yipeiwu_com6年前服务器

本文实例讲述了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 通过微信控制实现app定位发送到个人服务器再转发微信服务器接收位置信息

考虑到女友的安全问题,就做了一个app实现定位和服务器实现转发的东西。刚学python,竟没想到用对象编程会更加方便,全程过程式开发,代码有点臃肿,就当学习下python吧. 效果就是:...

python实现linux服务器批量修改密码并生成execl

批量修改linux服务器密码,同时生成execl表格 复制代码 代码如下:#!/usr/bin/env python#coding:utf8#随机生成自定义长度密码from random...

python实现静态web服务器

HTTP协议简介 HTTP请求 1:浏览器首先向服务器发送HTTP请求,请求包括: 方法:GET还是POST,GET仅请求资源,POST会附带用户数据; 路径:/full/url/pat...

Python搭建HTTP服务器和FTP服务器

Python搭建HTTP服务器和FTP服务器

本教程为大家分享了Python搭建HTTP服务器和FTP服务器的具体步骤,供大家参考,具体内容如下 默认安装版本为pytho2.7 http服务器搭建教程: 进入要开放访问的目录下,执行...

flask应用部署到服务器的方法

flask应用部署到服务器的方法

flask是我学习的第一个python的web框架,在应用flask写完一个应用后,当然是把它部署到我们的服务器上了。 首先,准备我们部署项目所需要的部分 1.完整的flask项目 2....