How do I send a POST request with PHP?

前端 未结 13 1547
暗喜
暗喜 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 06:01

    CURL-less method with PHP5:

    $url = 'http://server.com/path';
    $data = array('key1' => 'value1', 'key2' => 'value2');
    
    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data)
        )
    );
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if ($result === FALSE) { /* Handle error */ }
    
    var_dump($result);
    

    See the PHP manual for more information on the method and how to add headers, for example:

    • stream_context_create: http://php.net/manual/en/function.stream-context-create.php

提交回复
热议问题