How do I send a POST request with PHP?

前端 未结 13 1555
暗喜
暗喜 2020-11-21 05:40

Actually I want to read the contents that come after the search query, when it is done. The problem is that the URL only accepts POST methods, and it does not t

13条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 05:59

    Another alternative of the curl-less method above is to use the native stream functions:

    • stream_context_create():

      Creates and returns a stream context with any options supplied in options preset.

    • stream_get_contents():

      Identical to file_get_contents(), except that stream_get_contents() operates on an already open stream resource and returns the remaining contents in a string, up to maxlength bytes and starting at the specified offset.

    A POST function with these can simply be like this:

     [
          'header'  => [ // header array does not need '\r\n'
            'Content-type: application/x-www-form-urlencoded',
            'Content-Length: ' . strlen($query_content)
          ],
          'method'  => 'POST',
          'content' => $query_content
        ]
      ]));
      if ($fp === FALSE) {
        return json_encode(['error' => 'Failed to get contents...']);
      }
      $result = stream_get_contents($fp); // no maxlength/offset
      fclose($fp);
      return $result;
    }
    

提交回复
热议问题