PHP Simulation HTTP Request(undone)

目录

0. 引言
1. file_get_contents版本
2. Socket版本
3. Curl版本
4. Curl版本(2)

0. 引言

本文总结了通过PHP代码方式模拟各种HTTP请求

1. file_get_contents版本

<?php
/**
 * 发送post请求
 * @param string $url 请求地址
 * @param array $post_data post键值对数据
 * @return string
 */
function send_post($url, $post_data)
{
    //使用给出的关联(或下标)数组生成一个经过 URL-encode 的请求字符串
    $postdata = http_build_query($post_data);
    $options = array(
        ‘http‘ => array(
            ‘method‘ => ‘POST‘,
            ‘header‘ => ‘Content-type:application/x-www-form-urlencoded‘,
            ‘content‘ => $postdata,
            ‘timeout‘ => 15 * 60 // 超时时间(单位:s)
        )
    );
    //创建并返回一个资源流上下文,该资源流中包含了 options 中提前设定的所有参数的值
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    return $result;
}

$post_data = array(
    ‘username‘ => ‘zhenghan‘,
    ‘password‘ => ‘111‘
);
$result = send_post(‘http://localhost/test/index.php‘, $post_data);
echo $result;

?>

Relevant Link:

http://php.net/manual/zh/function.http-build-query.php
http://php.net/manual/zh/function.stream-context-create.php

2. Socket版本

<?php
/**
 * Socket版本
 */
function request_by_socket($remote_server, $remote_path, $post_string, $port = 80, $timeout = 30)
{
    $socket = fsockopen($remote_server, $port, $errno, $errstr, $timeout);
    if (!$socket)
    {
        die("$errstr($errno)");
    }
    fwrite($socket, "POST $remote_path HTTP/1.0");
    fwrite($socket, "User-Agent: Socket Example");
    fwrite($socket, "HOST: $remote_server");
    fwrite($socket, "Content-type: application/x-www-form-urlencoded");
    fwrite($socket, "Content-length: " . (strlen($post_string) + 8) . "");
    fwrite($socket, "Accept:*/*");
    fwrite($socket, "");
    fwrite($socket, "mypost=$post_string");
    fwrite($socket, "");
    $header = "";
    while ($str = trim(fgets($socket, 4096)))
    {
        $header .= $str;
    }

    $data = "";
    while (!feof($socket))
    {
        $data .= fgets($socket, 4096);
    }

    return $data;
}

$post_string = "app=socket&amp;version=beta";
$result = request_by_socket(‘localhost‘, ‘/test.php‘, $post_string);

echo $result;

?>

Relevant Link:

http://php.net/manual/zh/function.fsockopen.php

3. Curl版本

<?php
/**
 * Curl版本
 */
function request_by_curl($remote_server, $post_string)
{
    //初始化一个新的会话,返回一个cURL句柄,供curl_setopt(), curl_exec()和curl_close() 函数使用。
    $ch = curl_init();
    //curl_setopt — 设置一个cURL传输选项
    curl_setopt($ch, CURLOPT_URL, $remote_server);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "http://littlehann.cnblogs.com CURL Example beta");
    //curl_exec — 执行一个cURL会话,这个函数应该在初始化一个cURL会话并且全部的选项都被设置后被调用。
    $data = curl_exec($ch);
    //关闭一个cURL会话并且释放所有资源。cURL句柄ch 也会被释放。
    curl_close($ch);

    return $data;
}

$post_string = "app=request&version=beta";
$result = request_by_curl(‘http://localhost/test.php‘, $post_string);
echo $result;

?>

Relevant Link:

http://php.net/manual/zh/function.curl-init.php
http://php.net/manual/zh/function.curl-setopt.php
http://php.net/manual/zh/function.curl-exec.php
http://blog.51yip.com/php/1039.html

4. Curl版本(2)

<?php
/**
 * 发送HTTP请求
 *
 * @param string $url 请求地址
 * @param string $method 请求方式 GET/POST
 * @param string $refererUrl 请求来源地址
 * @param array $data 发送数据
 * @param string $contentType
 * @param string $timeout
 * @param string $proxy
 */
function send_request($url, $data, $refererUrl = ‘‘, $method = ‘GET‘, $contentType = ‘application/json‘, $timeout = 30, $proxy = false)
{
    $ch = null;
    if(‘POST‘ === strtoupper($method))
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER,0 );
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        if ($refererUrl)
        {
            curl_setopt($ch, CURLOPT_REFERER, $refererUrl);
        }
        if($contentType)
        {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(‘Content-Type:‘.$contentType));
        }
        if(is_string($data))
        {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        else
        {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
    }
    else if(‘GET‘ === strtoupper($method))
    {
        if(is_string($data))
        {
            $real_url = $url. (strpos($url, ‘?‘) === false ? ‘?‘ : ‘‘). $data;
        }
        else
        {
            $real_url = $url. (strpos($url, ‘?‘) === false ? ‘?‘ : ‘‘). http_build_query($data);
        }

        $ch = curl_init($real_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(‘Content-Type:‘.$contentType));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        if ($refererUrl)
        {
            curl_setopt($ch, CURLOPT_REFERER, $refererUrl);
        }
    }
    else
    {
        //返回一个数组,其中每个元素都是目前用户自定义函数的参数列表的相应元素的副本
        $args = func_get_args();
        return false;
    }

    if($proxy)
    {
        curl_setopt($ch, CURLOPT_PROXY, $proxy);
    }
    $ret = curl_exec($ch);
    //获取最后一次传输的相关信息。
    $info = curl_getinfo($ch);
    $contents = array(
            ‘httpInfo‘ => array(
                    ‘send‘ => $data,
                    ‘url‘ => $url,
                    ‘ret‘ => $ret,
                    ‘http‘ => $info
            )
    );

    curl_close($ch);
    return $contents;
}

$data = array(1 => "hello world!");
$r_url = "http://localhost/test.php";
$result = send_request($r_url, json_encode($data), NULL, ‘POST‘);
echo $result;

?>

Relevant Link:

http://php.net/manual/zh/function.curl-getinfo.php
http://blog.snsgou.com/post-161.html
http://www.cnblogs.com/simpman/p/3549816.html

Copyright (c) 2014 LittleHann All rights reserved

时间: 2024-08-04 01:49:31

PHP Simulation HTTP Request(undone)的相关文章

IIS FTP Server Anonymous Writeable Reinforcement, WEBDAV Anonymous Writeable Reinforcement(undone)

目录 0. 引言 1. IIS 6.0 FTP匿名登录.匿名可写加固 2. IIS 7.0 FTP匿名登录.匿名可写加固 3. IIS 6.0 Anonymous PUT(WEBDAV匿名可写)加固 4. IIS 7.0 Anonymous PUT(WEBDAV匿名可写)加固 5. IIS ISAPI Filter(isapiFilters) 6. IIS Extension 7. IIS FTP匿名登录的自动化修复 8. IIS WEBDAV匿名访问的自动化修复 9. IIS 恶意Filter

Linux Communication Mechanism Summarize(undone)

目录 1. Linux通信机制分类简介 2. Inter-Process Communication (IPC) mechanisms: 进程间通信机制 3. 多线程并行中的阻塞和同步 4. Ring3和Ring0的通信机制 5. 远程网络通信 1. Linux通信机制简介 在开始学习Linux下的通信机制之前,我们先来给通信机制下一个定义,即明白什么是通信机制?为什么要存在通信机制? 0x1: Linux通信目的 1. 数据传输: 一个进程需要将它的数据发送给另一个进程,发送的数据量在一个字节

HTTP 400 错误 - 请求无效 (Bad request)

在ajax请求后台数据时有时会报 HTTP 400 错误 - 请求无效 (Bad request);出现这个请求无效报错说明请求没有进入到后台服务里: 原因:1)前端提交数据的字段名称或者是字段类型和后台的实体类不一致,导致无法封装: 2)前端提交的到后台的数据应该是json字符串类型,而前端没有将对象转化为字符串类型: 解决方案: 1)对照字段名称,类型保证一致性 2)使用stringify将前端传递的对象转化为字符串    data: JSON.stringify(param)  ;

Spring Cloud ZooKeeper集成Feign的坑2,服务调用了一次后第二次调用就变成了500,错误:Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is com.n

错误如下: 2017-09-19 15:05:24.659 INFO 9986 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]56528192: startup date [Tue Sep 19 15:05:24 CST 2017]; root of context hierarchy 2017-09-19 15:05:24.858 INFO 9986 --

ASP.NET取得Request URL的各个部分

ASP.NET取得Request URL的各个部分  网址:http://localhost:1897/News/Press/Content.aspx/123?id=1#toc Request.ApplicationPath / Request.PhysicalPath D:\Projects\Solution\web\News\Press\Content.aspx System.IO.Path.GetDirectoryName(Request.PhysicalPath) D:\Projects

Webform 内置对象 Response对象、Request对象,QueryString

Request对象:获取请求Request["key"]来获取传递过来的值 QueryString:地址栏数据传递 ?key=value&key=value注意事项:不需要保密的东西可以传不要传过长东西,因为长度有限,过长会造成数据丢失 Response对象:响应请求Response.Write("<script>alert('添加成功!')</script>");Response.Redirect("Default.asp

译-BMC Remedy Action Request System权限控制概述

原文链接:Access control overview 说明: BMC Remedy Action Request System是BMC ITSM产品平台,简称AR 或者Remedy,可实现基于ITIL标准的整个IT管理流程的实施定制.该平台可实现多种权限级别的管理,包括人员.组.角色,以及表.字段.行级别等.本文可以用作其他对权限要求比较精细的系统参考. 为了便于理解,部分名词翻译如下: Server:服务器Form (or table):表单Field (or column):字段Acti

request.setAttribute(&quot;username&quot;, username);//一定要保存,OGNL才能获取${username}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String username= request.getParameter("username"); request.setAttribute("use

AWS CloudFront CDN直接全站加速折腾记The request could not be satisfied. Bad request

ERROR The request could not be satisfied. Bad request. Generated by cloudfront (CloudFront) Request ID: JC3i8piJpjRbuP81MNhSKPxt5KWirIInynZgwFJ9EYKuysjS5A_AnQ== 上面这个问题害我着急的很啊.在这里谢谢远在东京的小伙伴在百忙之中帮我分析解决这个问题. 使用AWS也有段时间了,基本常用的服务都用了,还有很多服务没用上,正在慢慢摸索中..说实话