How do I send a POST request with PHP?

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 take any action with GET method...

I have to read all contents with the help of domdocument or file_get_contents() . Is there any method that will let me send parameters with POST method and then read the contents via PHP ?


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-urlencodedrn",
        '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

  • 我确实尝试过这个,它工作的很好......正如我所知道的那样..

    <?php
    $url = $file_name;
    $fields = array(
                '__VIEWSTATE'=>urlencode($state),
                '__EVENTVALIDATION'=>urlencode($valid),
                'btnSubmit'=>urlencode('Submit')
            );
    
    //url-ify the data for the POST
    foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    $fields_string = rtrim($fields_string,'&');
    
    //open connection
    $ch = curl_init();
    
    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    
    //execute post
    $result = curl_exec($ch);
    print $result;
    ?>
    

    I use the following function to post data using curl. $data is an array of fields to post (will be correctly encoded using http_build_query). The data is encoded using application/x-www-form-urlencoded.

    function httpPost($url, $data)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
    

    @Edward mentions that http_build_query may be omitted since curl will correctly encode array passed to CURLOPT_POSTFIELDS parameter, but be advised that in this case the data will be encoded using multipart/form-data.

    I use this function with APIs that expect data to be encoded using application/x-www-form-urlencoded. That's why I use http_build_query().

    链接地址: http://www.djcxy.com/p/7034.html

    上一篇: 如何在node.js中创建HTTP POST请求?

    下一篇: 如何使用PHP发送POST请求?