How do I send a POST request with PHP?

前端 未结 13 1551
暗喜
暗喜 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:44

    I'd like to add some thoughts about the curl-based answer of Fred Tanrikut. I know most of them are already written in the answers above, but I think it is a good idea to show an answer that includes all of them together.

    Here is the class I wrote to make HTTP-GET/POST/PUT/DELETE requests based on curl, concerning just about the response body:

    class HTTPRequester {
        /**
         * @description Make HTTP-GET call
         * @param       $url
         * @param       array $params
         * @return      HTTP-Response body or an empty string if the request fails or is empty
         */
        public static function HTTPGet($url, array $params) {
            $query = http_build_query($params); 
            $ch    = curl_init($url.'?'.$query);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            $response = curl_exec($ch);
            curl_close($ch);
            return $response;
        }
        /**
         * @description Make HTTP-POST call
         * @param       $url
         * @param       array $params
         * @return      HTTP-Response body or an empty string if the request fails or is empty
         */
        public static function HTTPPost($url, array $params) {
            $query = http_build_query($params);
            $ch    = curl_init();
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
            $response = curl_exec($ch);
            curl_close($ch);
            return $response;
        }
        /**
         * @description Make HTTP-PUT call
         * @param       $url
         * @param       array $params
         * @return      HTTP-Response body or an empty string if the request fails or is empty
         */
        public static function HTTPPut($url, array $params) {
            $query = \http_build_query($params);
            $ch    = \curl_init();
            \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
            \curl_setopt($ch, \CURLOPT_HEADER, false);
            \curl_setopt($ch, \CURLOPT_URL, $url);
            \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'PUT');
            \curl_setopt($ch, \CURLOPT_POSTFIELDS, $query);
            $response = \curl_exec($ch);
            \curl_close($ch);
            return $response;
        }
        /**
         * @category Make HTTP-DELETE call
         * @param    $url
         * @param    array $params
         * @return   HTTP-Response body or an empty string if the request fails or is empty
         */
        public static function HTTPDelete($url, array $params) {
            $query = \http_build_query($params);
            $ch    = \curl_init();
            \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
            \curl_setopt($ch, \CURLOPT_HEADER, false);
            \curl_setopt($ch, \CURLOPT_URL, $url);
            \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'DELETE');
            \curl_setopt($ch, \CURLOPT_POSTFIELDS, $query);
            $response = \curl_exec($ch);
            \curl_close($ch);
            return $response;
        }
    }
    

    Improvements

    • Using http_build_query to get the query-string out of an request-array.(you could also use the array itself, therefore see: http://php.net/manual/en/function.curl-setopt.php)
    • Returning the response instead of echoing it. Btw you can avoid the returning by removing the line curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);. After that the return value is a boolean(true = request was successful otherwise an error occured) and the response is echoed. See: http://php.net/en/manual/function.curl-exec.php
    • Clean session closing and deletion of the curl-handler by using curl_close. See: http://php.net/manual/en/function.curl-close.php
    • Using boolean values for the curl_setopt function instead of using any number.(I know that any number not equal zero is also considered as true, but the usage of true generates a more readable code, but that's just my opinion)
    • Ability to make HTTP-PUT/DELETE calls(useful for RESTful service testing)

    Example of usage

    GET

    $response = HTTPRequester::HTTPGet("http://localhost/service/foobar.php", array("getParam" => "foobar"));
    

    POST

    $response = HTTPRequester::HTTPPost("http://localhost/service/foobar.php", array("postParam" => "foobar"));
    

    PUT

    $response = HTTPRequester::HTTPPut("http://localhost/service/foobar.php", array("putParam" => "foobar"));
    

    DELETE

    $response = HTTPRequester::HTTPDelete("http://localhost/service/foobar.php", array("deleteParam" => "foobar"));
    

    Testing

    You can also make some cool service tests by using this simple class.

    class HTTPRequesterCase extends TestCase {
        /**
         * @description test static method HTTPGet
         */
        public function testHTTPGet() {
            $requestArr = array("getLicenses" => 1);
            $url        = "http://localhost/project/req/licenseService.php";
            $this->assertEquals(HTTPRequester::HTTPGet($url, $requestArr), '[{"error":false,"val":["NONE","AGPL","GPLv3"]}]');
        }
        /**
         * @description test static method HTTPPost
         */
        public function testHTTPPost() {
            $requestArr = array("addPerson" => array("foo", "bar"));
            $url        = "http://localhost/project/req/personService.php";
            $this->assertEquals(HTTPRequester::HTTPPost($url, $requestArr), '[{"error":false}]');
        }
        /**
         * @description test static method HTTPPut
         */
        public function testHTTPPut() {
            $requestArr = array("updatePerson" => array("foo", "bar"));
            $url        = "http://localhost/project/req/personService.php";
            $this->assertEquals(HTTPRequester::HTTPPut($url, $requestArr), '[{"error":false}]');
        }
        /**
         * @description test static method HTTPDelete
         */
        public function testHTTPDelete() {
            $requestArr = array("deletePerson" => array("foo", "bar"));
            $url        = "http://localhost/project/req/personService.php";
            $this->assertEquals(HTTPRequester::HTTPDelete($url, $requestArr), '[{"error":false}]');
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:45

    Here is using just one command without cURL. Super simple.

    echo file_get_contents('https://www.server.com', false, stream_context_create([
        'http' => [
            'method' => 'POST',
            'header'  => "Content-type: application/x-www-form-urlencoded",
            'content' => http_build_query([
                'key1' => 'Hello world!', 'key2' => 'second value'
            ])
        ]
    ]));
    
    0 讨论(0)
  • 2020-11-21 05:47

    The better way of sending GET or POST requests with PHP is as below:

    <?php
        $r = new HttpRequest('http://example.com/form.php', HttpRequest::METH_POST);
        $r->setOptions(array('cookies' => array('lang' => 'de')));
        $r->addPostFields(array('user' => 'mike', 'pass' => 's3c|r3t'));
    
        try {
            echo $r->send()->getBody();
        } catch (HttpException $ex) {
            echo $ex;
        }
    ?>
    

    The code is taken from official documentation here http://docs.php.net/manual/da/httprequest.send.php

    0 讨论(0)
  • 2020-11-21 05:50

    You could use cURL:

    <?php
    //The url you wish to send the POST request to
    $url = $file_name;
    
    //The data you want to send via POST
    $fields = [
        '__VIEWSTATE '      => $state,
        '__EVENTVALIDATION' => $valid,
        'btnSubmit'         => 'Submit'
    ];
    
    //url-ify the data for the POST
    $fields_string = http_build_query($fields);
    
    //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, true);
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    
    //So that curl_exec returns the contents of the cURL; rather than echoing it
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 
    
    //execute post
    $result = curl_exec($ch);
    echo $result;
    ?>
    
    0 讨论(0)
  • 2020-11-21 05:53

    There's another CURL method if you are going that way.

    This is pretty straightforward once you get your head around the way the PHP curl extension works, combining various flags with setopt() calls. In this example I've got a variable $xml which holds the XML I have prepared to send - I'm going to post the contents of that to example's test method.

    $url = 'http://api.example.com/services/xmlrpc/';
    $ch = curl_init($url);
    
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    curl_close($ch);
    //process $response
    

    First we initialised the connection, then we set some options using setopt(). These tell PHP that we are making a post request, and that we are sending some data with it, supplying the data. The CURLOPT_RETURNTRANSFER flag tells curl to give us the output as the return value of curl_exec rather than outputting it. Then we make the call and close the connection - the result is in $response.

    0 讨论(0)
  • 2020-11-21 05:53

    Try PEAR's HTTP_Request2 package to easily send POST requests. Alternatively, you can use PHP's curl functions or use a PHP stream context.

    HTTP_Request2 also makes it possible to mock out the server, so you can unit-test your code easily

    0 讨论(0)
提交回复
热议问题