【问题标题】:PHP Fire and Forget POST - with HTTPS supportPHP Fire and Forget POST - 支持 HTTPS
【发布时间】:2023-02-25 17:37:07
【问题描述】:

我想将 PHP 脚本中的 POST 请求发送到另一台服务器,而不是以任何方式等待响应。

我相信这不适用于 curl(有异步模式,但 PHP 脚本不会直接返回并仍在等待响应)而且我也不想引入 curl 依赖项。

This answer 工作得很好,但只适用于 HTTP 连接。

我创建了一个测试脚本,我可以使用 HTTP(用于测试)和 HTTPS 访问它:

file_put_contents('/tmp/log', date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);

$entityBody = file_get_contents('php://input');

file_put_contents('/tmp/log', var_export($_POST,true) . PHP_EOL, FILE_APPEND);
file_put_contents('/tmp/log', $entityBody . PHP_EOL, FILE_APPEND);
sleep(5000);

睡眠是为了测试调用脚本是否真的不等待响应。

并通过插入以下内容修改上述答案中的代码以使用端口 443:

if ($parts['scheme'] === 'https') {
    $port = $parts['port'] ?? 443;
} else {
    $port = $parts['port'] ?? 80;
}

所以完整的代码是:

private function sendRequestAndForget(string $method, string $url, array $params = []): void
{
    $parts = parse_url($url);
    if ($parts === false)
        throw new Exception('Unable to parse URL');
    $host = $parts['host'] ?? null;


    if ($parts['scheme'] === 'https') {
        $port = $parts['port'] ?? 443;
    } else {
        $port = $parts['port'] ?? 80;
    }

    $path = $parts['path'] ?? '/';
    $query = $parts['query'] ?? '';
    parse_str($query, $queryParts);

    if ($host === null)
        throw new Exception('Unknown host');
    $connection = fsockopen($host, $port, $errno, $errstr, 30);
    if ($connection === false)
        throw new Exception('Unable to connect to ' . $host);
    $method = strtoupper($method);

    if (!in_array($method, ['POST', 'PUT', 'PATCH'], true)) {
        $queryParts = $params + $queryParts;
        $params = [];
    }

    // Build request
    $request = $method . ' ' . $path;
    if ($queryParts) {
        $request .= '?' . http_build_query($queryParts);
    }
    $request .= ' HTTP/1.1' . "\r\n";
    $request .= 'Host: ' . $host . "\r\n";

    $body = json_encode($params);
    if ($body) {
        $request .= 'Content-Type: application/json' . "\r\n";
        $request .= 'Content-Length: ' . strlen($body) . "\r\n";
    }
    $request .= 'Connection: Close' . "\r\n\r\n";
    $request .= $body;

    // Send request to server
    fwrite($connection, $request);
    fclose($connection);
}

使用 http 时它工作正常,当使用 https URL 时它不工作。

【问题讨论】:

    标签: php https


    【解决方案1】:

    这很简单——我只需要在连接部分添加ssl://

    $connection = fsockopen((($parts['scheme'] === 'https') ? 'ssl://' : '') . $host, $port, $errno, $errstr, 30);
    

    【讨论】:

      猜你喜欢
      • 2013-01-13
      • 2014-05-16
      • 2021-10-12
      • 2017-02-19
      • 1970-01-01
      • 2013-11-08
      • 2020-03-05
      • 2020-03-21
      • 1970-01-01
      相关资源
      最近更新 更多