这里给大家分享一段使用PHP Socket 编程模拟Http post和get请求的代码,非常的实用,结尾部分我们再讨论下php模拟http请求的几种方法。

  1. <?php /**
  2. * 使用PHP Socket 编程模拟Http post和get请求
  3. * @author koma
  4. */ class Http{
  5. private $sp = "\r\n"; //这里必须要写成双引号 private $protocol = 'HTTP/1.1';
  6. private $requestLine = "";
  7. private $requestHeader = "";
  8. private $requestBody = "";
  9. private $requestInfo = "";
  10. private $fp = null;
  11. private $urlinfo = null;
  12. private $header = array();
  13. private $body = "";
  14. private $responseInfo = "";
  15. private static $http = null; //Http对象单例
  16. private function __construct() {}
  17. public static function create() {
  18. if ( self::$http === null ) {
  19. self::$http = new Http();
  20. }
  21. return self::$http;
  22. }
  23. public function init($url) {
  24. $this->parseurl($url);
  25. $this->header['Host'] = $this->urlinfo['host'];
  26. return $this;
  27. }
  28. public function get($header = array()) {
  29. $this->header = array_merge($this->header, $header);
  30. return $this->request('GET');
  31. }
  32. public function post($header = array(), $body = array()) {
  33. $this->header = array_merge($this->header, $header);
  34. if ( !empty($body) ) {
  35. $this->body = http_build_query($body);
  36. $this->header['Content-Type'] = 'application/x-www-form-urlencoded';
  37. $this->header['Content-Length'] = strlen($this->body);
  38. }
  39. return $this->request('POST');
  40. }
  41. private function request($method) {
  42. $header = "";
  43. $this->requestLine = $method.' '.$this->urlinfo['path'].'?'.$this->urlinfo['query'].' '.$this->protocol;
  44. foreach ( $this->header as $key => $value ) {
  45. $header .= $header == "" ? $key.':'.$value : $this->sp.$key.':'.$value;
  46. }
  47. $this->requestHeader = $header.$this->sp.$this->sp;
  48. $this->requestInfo = $this->requestLine.$this->sp.$this->requestHeader;
  49. if ( $this->body != "" ) {
  50. $this->requestInfo .= $this->body;
  51. }
  52. /*
  53. * 注意:这里的fsockopen中的url参数形式为"www.xxx.com"
  54. * 不能够带"http://"这种
  55. */
  56. $port = isset($this->urlinfo['port']) ? isset($this->urlinfo['port']) : '80';
  57. $this->fp = fsockopen($this->urlinfo['host'], $port, $errno, $errstr);
  58. if ( !$this->fp ) {
  59. echo $errstr.'('.$errno.')';
  60. return false;
  61. }
  62. if ( fwrite($this->fp, $this->requestInfo) ) {
  63. $str = "";
  64. while ( !feof($this->fp) ) {
  65. $str .= fread($this->fp, 1024);
  66. }
  67. $this->responseInfo = $str;
  68. }
  69. fclose($this->fp);
  70. return $this->responseInfo;
  71. }
  72. private function parseurl($url) {
  73. $this->urlinfo = parse_url($url);
  74. }
  75. } // $url = "http://news.163.com/14/1102/01/AA0PFA7Q00014AED.html";
  76. $url = "http://localhost/httppro/post.php"; $http = Http::create()->init($url); /* 发送get请求
  77. echo $http->get(array(
  78. 'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36',
  79. ));
  80. */
  81. /* 发送post请求 */ echo $http->post(array(
  82. 'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36',
  83. ), array('username'=>'发一个中文', 'age'=>22));
  1. <?php /**
  2. * 使用PHP Socket 编程模拟Http post和get请求
  3. * @author koma
  4. */ class Http{
  5. private $sp = "\r\n"; //这里必须要写成双引号 private $protocol = 'HTTP/1.1';
  6. private $requestLine = "";
  7. private $requestHeader = "";
  8. private $requestBody = "";
  9. private $requestInfo = "";
  10. private $fp = null;
  11. private $urlinfo = null;
  12. private $header = array();
  13. private $body = "";
  14. private $responseInfo = "";
  15. private static $http = null; //Http对象单例
  16. private function __construct() {}
  17. public static function create() {
  18. if ( self::$http === null ) {
  19. self::$http = new Http();
  20. }
  21. return self::$http;
  22. }
  23. public function init($url) {
  24. $this->parseurl($url);
  25. $this->header['Host'] = $this->urlinfo['host'];
  26. return $this;
  27. }
  28. public function get($header = array()) {
  29. $this->header = array_merge($this->header, $header);
  30. return $this->request('GET');
  31. }
  32. public function post($header = array(), $body = array()) {
  33. $this->header = array_merge($this->header, $header);
  34. if ( !empty($body) ) {
  35. $this->body = http_build_query($body);
  36. $this->header['Content-Type'] = 'application/x-www-form-urlencoded';
  37. $this->header['Content-Length'] = strlen($this->body);
  38. }
  39. return $this->request('POST');
  40. }
  41. private function request($method) {
  42. $header = "";
  43. $this->requestLine = $method.' '.$this->urlinfo['path'].'?'.$this->urlinfo['query'].' '.$this->protocol;
  44. foreach ( $this->header as $key => $value ) {
  45. $header .= $header == "" ? $key.':'.$value : $this->sp.$key.':'.$value;
  46. }
  47. $this->requestHeader = $header.$this->sp.$this->sp;
  48. $this->requestInfo = $this->requestLine.$this->sp.$this->requestHeader;
  49. if ( $this->body != "" ) {
  50. $this->requestInfo .= $this->body;
  51. }
  52. /*
  53. * 注意:这里的fsockopen中的url参数形式为"www.xxx.com"
  54. * 不能够带"http://"这种
  55. */
  56. $port = isset($this->urlinfo['port']) ? isset($this->urlinfo['port']) : '80';
  57. $this->fp = fsockopen($this->urlinfo['host'], $port, $errno, $errstr);
  58. if ( !$this->fp ) {
  59. echo $errstr.'('.$errno.')';
  60. return false;
  61. }
  62. if ( fwrite($this->fp, $this->requestInfo) ) {
  63. $str = "";
  64. while ( !feof($this->fp) ) {
  65. $str .= fread($this->fp, 1024);
  66. }
  67. $this->responseInfo = $str;
  68. }
  69. fclose($this->fp);
  70. return $this->responseInfo;
  71. }
  72. private function parseurl($url) {
  73. $this->urlinfo = parse_url($url);
  74. }
  75. } // $url = "http://news.163.com/14/1102/01/AA0PFA7Q00014AED.html";
  76. $url = "http://localhost/httppro/post.php"; $http = Http::create()->init($url); /* 发送get请求
  77. echo $http->get(array(
  78. 'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36',
  79. ));
  80. */
  81. /* 发送post请求 */ echo $http->post(array(
  82. 'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36',
  83. ), array('username'=>'发一个中文', 'age'=>22));

php 模拟 http请求

方法一:利用php的socket编程来直接给接口发送数据来模拟post的操作。

建立两个文件post.php,getpost.php
post.php内容如下:

  1. <?php
  2. $flag = 0;
  3. $params = '';
  4. $errno = '';
  5. $errstr = '';
  6. //要post的数据
  7. $argv = array(
  8. 'var1'=>'abc',
  9. 'var2'=>'how are you , my friend??');
  10. //构造要post的字符串
  11. foreach ($argv as $key=>$value) {
  12. if ($flag!=0) {
  13. $params .= "&";
  14. $flag = 1;
  15. }
  16. $params.= $key."="; $params.= urlencode($value);
  17. $flag = 1;
  18. }
  19. $length = strlen($params);
  20. //创建socket连接
  21. $fp = fsockopen("localhost",81,$errno,$errstr,10) or exit($errstr."--->".$errno);
  22. //构造post请求的头
  23. $header = "POST /flandy/getpost.php HTTP/1.1\r\n";
  24. $header .= "Host:127.0.0.1\r\n";
  25. $header .= "Referer:/flandy/post.php\r\n";
  26. $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
  27. $header .= "Content-Length: ".$length."\r\n";
  28. $header .= "Connection: Close\r\n\r\n";
  29. //添加post的字符串
  30. $header .= $params."\r\n";
  31.  
  32. //发送post的数据
  33. fputs($fp,$header);
  34. $inheader = 1;
  35. while (!feof($fp)) {
  36. $line = fgets($fp,1024); //去除请求包的头只显示页面的返回数据
  37. if ($inheader && ($line == "\n" || $line == "\r\n")) {
  38. $inheader = 0;
  39. }
  40. if ($inheader == 0) {
  41. echo $line;
  42. }
  43. }
  44. fclose($fp);
  45. ?>

getpost.php的内容如下

  1. <?php
  2. echo "this is the data posted";
  3. echo "<pre>";
  4. print_r($_REQUEST);
  5. echo "</pre>";
  6. ?>

结果输出:

  1. this is the data postedArray
  2. (
  3. [var1] => abc
  4. [var2] => how are you , my friend??
  5. )

以上代码在本机81端口下已经通过测试。

方法二:

使用PHP的curl扩展或HttpClient.class.php类,这两个非常类似,下面简单的列出curl的实现代码。
两个文件post2.php和getpost2.php
post2.php的内容如下:

  1. <?php
  2. $psecode = 'NDE005';
  3. $website = 'www.baidu.com';
  4. $amt = 1;
  5. $pwd = 123456;
  6. $ch = curl_init();
  7. $curl_url = "http://localhost:81/flandy/getpost2.php?web=" . $website .
  8. "&pwd=" . $pwd . "&action=check&pseid=" . $psecode .
  9. "&amt=" . $amt;
  10. curl_setopt($ch, CURLOPT_URL, $curl_url);
  11. curl_setopt($ch, CURLOPT_POST, 1);
  12. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//不直接输出,返回到变量
  13. $curl_result = curl_exec($ch);
  14. $result = explode(',', $curl_result);
  15. curl_close($ch);
  16. print_r($result);
  17. ?>

getpost2.php的内容如下:

  1. <?php
  2. echo "returndata<br>";
  3. echo "<pre>";
  4. print_r($_REQUEST);
  5. echo "</pre>";
  6. ?>

结果输出:

  1. Array ( [0] => returndataArray
  2. (
  3. [web] => 'wwwbaiducom'
  4. [pwd] => 123456
  5. [action] => check
  6. [pseid] => 'NDE005'
  7. [amt] => 1
  8. )
  9. )

方法三:

这个要借助第三方类库HttpClient可以到这里下载:http://scripts.incutio.com/httpclient/

  1. <?php
  2. require_once 'HttpClient.class.php';
  3. $params = array('web' => 'www.baidu.com',
  4. 'pwd' => '123456',
  5. 'action' => 'check',
  6. 'pseid' => 'NDE005',
  7. 'amt' => 1);
  8. $pageContents = HttpClient::quickPost('http://localhost:81/flandy/getpost3.php', $params);
  9. $result = explode(',', $pageContents);
  10. print_r($result);
  11. ?>

使用PHP Socket 编程模拟Http post和get请求的更多相关文章

  1. socket编程模拟linux下的ssh代码实现

    实现思路: 1.提供输入指令的客户端: 2.提供返回执行指令结果的服务端 3.寻找服务端返回结果一次无法全部接收的解决思路 服务端代码(ssh_server.py) #coding=utf-8 imp ...

  2. HTTP 笔记与总结(5)socket 编程:使用 HTTP 协议模拟登录并发帖

    在 VeryCD 上注册两个帐号,发送和接收站内信,观察 POST 请求时发送的参数(h****2 发送给 d***2).(最好用 FireFox 的 FireBug 工具,发送站内信之前选中 “保持 ...

  3. Socket编程之聊天程序 - 模拟Fins/ModBus协议通信过程

    设备控制软件编程涉及到的基本通信方式主要有TCP/IP与串口,用到的数据通信协议有Fins与ModBus. 更高级别的通信如.net中的Remoting与WCF在进行C/S架构软件开发时会采用. 本篇 ...

  4. python网络编程-socket编程

     一.服务端和客户端 BS架构 (腾讯通软件:server+client) CS架构 (web网站) C/S架构与socket的关系: 我们学习socket就是为了完成C/S架构的开发 二.OSI七层 ...

  5. socket编程基础

    socket编程 什么是socket 定义 socket通常也称作套接字,用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过套接字向网络发出请求或者应答网络请求. socket起源于Unix ...

  6. HTTP 笔记与总结(4 )socket 编程:批量发帖

    浏览器发送 POST 请求: 表单 form.html <!doctype html> <html lang="en"> <head> < ...

  7. HTTP 笔记与总结(3 )socket 编程:发送 GET 请求

    使用 PHP + socket 模拟发送 HTTP GET 请求,过程是: ① 打开连接 ② 构造 GET 请求的数据:写入请求行.请求头信息.请求主体信息(GET 请求没有主体信息) ③ 发送 GE ...

  8. 8.1 Socket编程

    8.1 Socket编程 在很多底层网络应用开发者的眼里一切编程都是Socket,话虽然有点夸张,但却也几乎如此了,现在的网络编程几乎都是用Socket来编程.你想过这些情景么?我们每天打开浏览器浏览 ...

  9. <转>Go语言TCP Socket编程

    授权转载: Tony Bai 原文连接: https://tonybai.com/2015/11/17/tcp-programming-in-golang/ Golang的主要 设计目标之一就是面向大 ...

随机推荐

  1. JavaScript获取浏览器信息的方法

    Window有navigator对象让我们得知浏览器的全部信息.我们可以利用一系列的API函数得知浏览器的信息. JavaScript代码如下: ? 1 2 3 4 5 6 7 8 9 10 11 1 ...

  2. javascript performence

    1.将脚本放在底部 javascript是阻塞式的加载,如果先加载脚本,后面的dom都没有办法进行渲染,页面会是一片空白: 采用无阻塞下载javascript a.使用<script>标签 ...

  3. 如何利用Visual studio 2010创建一个ASP网站?

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="UserLogin.aspx.c ...

  4. java中的静态变量

    大家都知道,我们可以基于一个类创建多个该类的对象,每个对象都拥有自己的成员,互相独立.然而在某些时候,我们更希望该类所有的对象共享同一个成员.此时就是 static 大显身手的时候了!! Java 中 ...

  5. hdu_5676_ztr loves lucky numbers

    题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=5676 在这%一下安神,用了我没见过的黑科技next_permutation,至少我是今天才知道的 #i ...

  6. nefu 519 昨日重现

    昨日重现 Problem : 519 Time Limit : 1000ms Memory Limit : 65536K description 兴安黑熊在高中学习数学时,曾经知道这样一个公式:f(n ...

  7. 【Machine Learning in Action --2】K-最近邻分类

    1.K-近邻算法(KNN)概述 K-近邻算法采用测量不同特征值之间的距离方法进行分类. 工作原理:存在一个样本数据集合(也称作训练样本集),并且样本集中每个数据都存在标签(即我们知道样本集中每一数据与 ...

  8. 遭遇mediumint上限

    Mediumint:The signed range is -8388608 to 8388607. The unsigned range is 0 to 16777215. home_notific ...

  9. angular跨域访问的问题

    CORS跨域资源共享 跨域资源共享(CORS )是一种网络浏览器的技术规范,它为Web服务器定义了一种方式,允许网页从不同的域访问其资源. Form responseHeaders = (Form) ...

  10. 运行出第一个程序Hello World、第二个程序网页浏览器

    很长时间没有发博客记录我的奋斗历程了,原因不外乎遇到了对我而言“巨大的”困难. 经历了长期的找不到合适的教材.找不到Xcode资源.运行不出例程的痛苦以后,近日终于走上正轨. 现在补发一个过去2个月来 ...