php socket 发送http请求

<?php
/**
 * Created by PhpStorm.
 * User: Mch
 * Date: 7/8/18
 * Time: 21:39

@func: parse_url
http://www.tfjyzx.com/model-school.jsp?area=%E5%BC%80%E5%B0%81&school=%E5%BC%80%E5%B0%81%E5%B8%82%E7%AC%AC%E4%BA%94%E4%B8%AD%E5%AD%A6#%E5%AD%A6%E6%A0%A1%E7%AE%80%E4%BB%8B

array(5) {
["scheme"]=>
string(4) "http"
["host"]=>
string(14) "www.tfjyzx.com"
["path"]=>
string(17) "/model-school.jsp"
["query"]=>
string(94) "area=%E5%BC%80%E5%B0%81&school=%E5%BC%80%E5%B0%81%E5%B8%82%E7%AC%AC%E4%BA%94%E4%B8%AD%E5%AD%A6"
["fragment"]=>
string(36) "%E5%AD%A6%E6%A0%A1%E7%AE%80%E4%BB%8B"
}
*/

interface Proto {
    // 连接url
    public function conn($url);
    //发送get查询
    public function get();
    // 发送post查询
    public function post();
    // 关闭连接
    public function close();
}

class Http implements Proto {

    const CRLF  = "\r\n";
    const BUFFSIZE = 1024;

    protected $errno = -1;
    protected $errstr = ‘‘;
    protected $response = ‘‘;

    protected $url = [];
    protected $version = ‘HTTP/1.1‘;
    protected $fh = null;

    protected $line = [];
    protected $header = [];
    protected $body = [];

    public function __construct($url) {
        $this->conn($url);
        $this->setHeader(‘Host: ‘ . $this->url[‘host‘]);
    }

    // POST /student/login HTTP/1.1
    protected function setLine($method) {
        $query = $this->url[‘query‘];
        $this->line[0] = implode(‘ ‘, [
            $method,
            $this->url[‘path‘].(strlen($query)>0 ? ‘?‘.$query : ‘‘),
            $this->version
        ]);
    }

    public function setHeader($headerline) {
        $this->header[] = $headerline;
    }

    public function setBody($body) {
        $this->body[] = http_build_query($body);
    }

    // 连接url
    public function conn($url) {
        $this->url = parse_url($url);

        if(!isset($this->url[‘port‘])) {
            $this->url[‘port‘] = 80;
        }
        if(!isset($this->url[‘query‘])) {
            $this->url[‘query‘] = ‘‘;
        }
        $this->fh = fsockopen($this->url[‘host‘],
            $this->url[‘port‘],
            $this->errno,
            $this->errstr,
            3   /* timeout 3s */
        );
        if (!$this->fh) {
            echo "$this->errstr ($this->errno)";
            return NULL;
        }
        return $this->fh;
    }

    //构造get请求的数据
    public function get() {
        $this->setLine(‘GET‘);
        $this->request();
        return $this->response;
    }

    // 构造post查询的数据
    public function post($body = [], $enctype = ‘application/x-www-form-urlencoded‘) {
        $this->setLine(‘POST‘);
        // content-type ‘multipart/form-data‘ or ...
        $this->setHeader(‘Content-type: ‘ . $enctype . ‘; charset=UTF-8‘);

        $this->setBody($body);
        $this->setHeader(‘Content-length: ‘ . strlen($this->body[0]));

        $this->request();
        return $this->response;
    }

    // 关闭连接
    public function close() {
        $this->fh && fclose($this->fh);
    }

    // 真正请求
    private function request() {
        // 把请求行,头信息,实体信息 放在一个数组里,便于拼接
        fwrite($this->fh, implode(self::CRLF, array_merge(
            $this->line,
            $this->header,
            [‘‘],
            $this->body,
            [‘‘]
        )));

        // 为什么循环第2次时候很慢(假设响应长度<BUFFSIZE, 即1次读取完了)?
        while(!feof($this->fh)) {
            $content = fread($this->fh, self::BUFFSIZE);
            if (strlen($content)<=0) {
                break;
            }
            $this->response .= $content;
            // echo $this->response;
        }
    }

}

// $url = "http://www.tfjyzx.com/news/listTVProgram?area=%E8%AE%B8%E6%98%8C";
$url = "http://www.tfjyzx.com/student/login";
$http = new Http($url);

// $resp = $http->get();
$http->setHeader(‘X-Requested-With: XMLHttpRequest‘);
$http->setHeader(‘User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36‘);
// !important $.ajax() contentType: ‘application/json‘
$http->setHeader(‘Accept: application/json, text/javascript, */*; q=0.01‘);

// ‘username=mingzhanghui&pwd=123456&captcha=&count=1‘
$resp = $http->post([
    ‘username‘ => ‘mingzhanghui‘,
    ‘pwd‘ => ‘123456‘,
    ‘captcha‘ => ‘‘,
    ‘count‘ => 1
]);
var_dump($http);
$http->close();

echo $resp;

  

原文地址:https://www.cnblogs.com/mingzhanghui/p/9281794.html

时间: 2024-10-11 18:22:27

php socket 发送http请求的相关文章

socket发送http请求

转自:思齐-socket发送http请求 socket方式: $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); //socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec"=>20, "usec"=>0)); socket_connect($socket, 'www.baidu.com', 80); //里面的换行代表 \r

使用socket发送http请求(GET/POST)

使用socket发送http请求(GET/POST) 下载LOFTER客户端 1.socket的原理 在相关文章中已经提及,不再赘述. 2.http头的格式 (1)请求行请求行由请求方法字段.URL字段和HTTP协议版本字段3个字段组成,它们用空格分隔.例如,GET /index.html HTTP/1.1.HTTP协议的请求方法有GET.POST.HEAD.PUT.DELETE.OPTIONS.TRACE.CONNECT.这里介绍最常用的GET方法和POST方法.GET:当客户端要从服务器中读

c/c++ socket发送http请求访问网站

这几天课比较少,校园网上网要认证才能上网,每次必须输入学号密码,为了方便,写了一个自动登录以及如果在线,登录自服务系统强制下线的小工具. 强制下线思路:获取sessionID---------->获取验证码图片------------>AspriseOCRLib识别验证码--------------->MD5加密.url Encode---------------->登录自服务系统---------------->强制下线--------------------->退出

PHP + Socket 发送http请求进而实现网站灌水

本质上实现组装http信息的请求行,头信息,主题信息,参考it自学网 cookie信息和http请求头有很大关系,注意把http请求头信息传递到函数里面 01-msg.php <?php require('./http.class.php'); $http = new Http('http://home.verycd.com/cp.php?ac=pm&op=send&touid=0&pmid=0'); $http->setHeader('Accept: text/htm

如果使用socket发送http请求(并且编译成可以被lr调用的压力测试脚本)

#include  <unistd.h> #include  <sys/types.h>       /* basic system data types */ #include  <sys/socket.h>      /* basic socket definitions */ #include  <netinet/in.h>      /* sockaddr_in{} and other Internet defns */ #include  <

perl6 Socket: 发送HTTP请求

sub MAIN(Str $host,Str $path, Int $port) { my $send = "GET $path HTTP/1.1\r\nHost: $host\r\n\r\n"; my $c = IO::Socket::INET.new(:host($host), :port($port)); $c.print: $send; while (my $buff = $c.recv(1024)) { say $buff.print; } $c.close; }

php 利用socket发送GET,POST请求

作为php程序员一定会接触http协议,也只有深入了解http协议,编程水平才会更进一步.最近我一直在学习php的关于http的编程,许多东西恍然大悟,受益匪浅.希望分享给大家.本文需要有一定http基础的开发者阅读. 今天给大家带来的是如何利用socket发送GET,POST请求.我借用燕十八老师封装好的一个Http类给进行说明. 在日常编程中相信很多人和我一样大部分时间是利用浏览器向服务器提出GET,POST请求,那么可否利用其它方式提出GET,POST请求呢?答案必然是肯定的.了解过HTT

java 常见几种发送http请求案例

1 import java.io.FileOutputStream; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.io.InputStreamReader; 5 import java.io.OutputStreamWriter; 6 import java.io.UnsupportedEncodingException; 7 import java.net.HttpURLConnection

Nodejs发送Post请求时出现socket hang up错误的解决办法

参考nodejs官网发送http post请求的方法,实现了一个模拟post提交的功能.实际使用时报socket hang up错误. 后来发现是请求头设置的问题,发送选项中需要加上headers字段信息(这个估计也和对方的服务器有关,对于不完成的post请求头,可能被丢弃了). 完整的代码如下(遇到类型问题的同学可以做个参考): var querystring = require('querystring') , http = require('http'); var data = query