【问题标题】:Making http request using pure PHP使用纯 PHP 发出 http 请求
【发布时间】:2020-08-21 08:03:22
【问题描述】:

我试图让我的 php 代码自己发送 http 请求(我现在不想使用像 CURL 这样的外部库),但我找不到正确的标签或者我不知道如何为此目的使用$_POST。请帮忙

【问题讨论】:

  • 这能回答你的问题吗? How do I send a POST request with PHP?
  • 不,这个问题给出的建议包括外部库。
  • 这能回答你的问题吗? How to make a post request without curl?
  • 您看到投票最多的答案了吗? 1238 票。它不使用外部库。
  • 我明白了,我没有注意到“少”部分......但它仍然没有回答我的问题......我正在尝试发布,我认为这个建议[file_get_contents() ] 是 GET 请求。

标签: php


【解决方案1】:

如果是 GET 请求,使用 file_get_contents,也许你可以试试这样:

    <?php
        $test = file_get_contents("http://example.com/");
        var_dump($test);
    ?>

如果是 POST 请求,使用 fsock,也许你可以试试这样:

    <?php
        $domain = 'dummy.restapiexample.com';
        $fp = fsockopen($domain, 80);

        $vars = array(
            'name' => 'test',
            'salary' => '123',
            'age' => '23' 
        );
        $content = http_build_query($vars);

        fwrite($fp, "POST /api/v1/create HTTP/1.1\r\n");
        fwrite($fp, "Host: $domain\r\n");
        fwrite($fp, "Content-Type: application/json\r\n");
        fwrite($fp, "Content-Length: ".strlen($content)."\r\n");
        fwrite($fp, "Connection: close\r\n");
        fwrite($fp, "\r\n");

        fwrite($fp, $content);

        header('Content-type: text/plain');
        while (!feof($fp)) {
            echo fgets($fp, 1024);
        }
    ?>

【讨论】:

  • 谢谢。它帮助很大。
猜你喜欢
  • 2016-09-05
  • 2011-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
  • 2019-10-20
相关资源
最近更新 更多