jonathrg/send

一个名为 send() 的单一功能,执行一次 HTTP 请求。

v1.0.1 2017-06-19 18:34 UTC

This package is not auto-updated.

Last update: 2024-09-29 02:39:23 UTC


README

Send 提供了一个名为 send() 的单一功能,该功能执行一次 HTTP 请求。

安装

composer require jonathrg/send

用法

send() 与一个定义您请求的数组一起提供,以执行该请求。结果以字符串形式返回。

以下是最简单的使用案例,它检索 example.org 的首页并打印它。您可以通过在本地主机上运行此 repo 并访问 Send/examples/example.php 来测试它。

<?php
require_once __DIR__.'path/to/vendor/autoload.php';

use function Send\send;

echo(send(['url' => 'http://example.org']));

获取东西

// Get the webpage for example.org and send some headers

$response = send([
    'url' => 'http://example.org',
    'headers' => $headers
]);

发布东西

// Post something to the webpage for example.org

$response = send([
    'url' => 'http://example.org',
    'method' => 'POST',
    'data' => $data
]);

放置和删除东西

当然,您也可以通过将 'method' 设置为 'DELETE' 或 'PUT' 来放置和删除东西。

定义请求

send() 接受一个参数,其中包含有关您请求的数据。此参数的必需字段是 'url'(应为有效 URL)。'method' 必须是 'GET'、'POST'、'PUT' 和 'DELETE' 之一,默认为 'GET'。如果您正在发送 POST 请求,您还应该使用 POST 字段填充 'data' 字段。

如果您想,您可以使用 curl_setopt 接受的选项。为了方便起见,数组键也可以是这些 "翻译" 之一,并将产生相同的效果

$CURL_TRANSLATION = [
    'url'                => CURLOPT_URL,
    'data'               => CURLOPT_POSTFIELDS,
    'post'               => CURLOPT_POST,
    'get'                => CURLOPT_HTTPGET,
    'put'                => CURLOPT_PUT,
    'method'             => CURLOPT_CUSTOMREQUEST,
    'timeout'            => CURLOPT_TIMEOUT,
    'timeout_ms'         => CURLOPT_TIMEOUT_MS,
    'connect_timeout'    => CURLOPT_CONNECTTIMEOUT,
    'connect_timeout_ms' => CURLOPT_CONNECTTIMEOUT_MS,
    'headers'            => CURLOPT_HTTPHEADER,
    'user_agent'         => CURLOPT_USERAGENT,
    'file'               => CURLOPT_INFILE,
    'file_size'          => CURLOPT_INFILESIZE,
    'no_body'            => CURLOPT_NOBODY,
    'fetch_headers'      => CURLOPT_HEADER
];

可选的错误处理

如果您想,您可以提供一个第二个参数,其中将包含 cURL 返回的错误消息的字符串。

$error = "";
$response = send($request, $error);
if ($error) {
    echo ($error);
}