源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

浅谈PHP发送HTTP请求的几种方式

  • 时间:2022-07-09 23:26 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:浅谈PHP发送HTTP请求的几种方式
PHP 开发中我们常用 cURL 方式封装 HTTP 请求,什么是 cURL? cURL 是一个用来传输数据的工具,支持多种协议,如在 Linux 下用 curl 命令行可以发送各种 HTTP 请求。PHP 的 cURL 是一个底层的库,它能根据不同协议跟各种服务器通讯,HTTP 协议是其中一种。 现代化的 PHP 开发框架中经常会用到一个包,叫做 GuzzleHttp,它是一个 HTTP 客户端,也可以用来发送各种 HTTP 请求,那么它的实现原理是什么,与 cURL 有何不同呢? [b]Does Guzzle require cURL?[/b] No. Guzzle can use any HTTP handler to send requests. This means that Guzzle can be used with cURL, PHP's stream wrapper, sockets, and non-blocking libraries like React. You just need to configure an HTTP handler to use a different method of sending requests. 这是 GuzzleHttp 文档 FAQ 中的一个 Question,可见 GuzzleHttp 并不依赖 cURL 库,而支持多种发送 HTTP 请求的方式。 [b]PHP 发送 HTTP 请求的方式[/b] 那么这里整理一下除了使用 cURL 外 PHP 发送 HTTP 请求的方式。 [b]1.cURL[/b] 详细方法:[url=http://www.1sucai.cn/article/56492.htm]http://www.1sucai.cn/article/56492.htm[/url] [b]2.stream流的方式[/b] stream_context_create 作用:创建并返回一个文本数据流并应用各种选项,可用于 fopen(), file_get_contents() 等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。 [b]以一个 POST 请求为例:[/b] PHP
<?php
/**
 * Created by PhpStorm.
 * User: tanteng
 * Date: 2017/7/22
 * Time: 13:48
 */
function post($url, $data)
{
  $postdata = http_build_query(
    $data
  );

  $opts = array('http' =>
           array(
             'method' => 'POST',
             'header' => 'Content-type: application/x-www-form-urlencoded',
             'content' => $postdata
           )
  );
  $context = stream_context_create($opts);
  $result = file_get_contents($url, false, $context);
  return $result;
}

关于 PHP stream 的介绍文章:[url=http://www.1sucai.cn/article/68891.htm]http://www.1sucai.cn/article/68891.htm[/url] [b]3.socket方式[/b] 使用套接字建立连接,拼接 HTTP 报文发送数据进行 HTTP 请求。 [b]一个 GET 方式的例子:[/b] PHP
<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
  echo "$errstr ($errno)<br />\n";
} else {
  $out = "GET / HTTP/1.1\r\n";
  $out .= "Host: www.example.com\r\n";
  $out .= "Connection: Close\r\n\r\n";
  fwrite($fp, $out);
  while (!feof($fp)) {
    echo fgets($fp, 128);
  }
  fclose($fp);
}
?>
本文介绍了发送 HTTP 请求的几种不同的方式。 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部