How do I send a POST request with PHP?

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

    I recommend you to use the open-source package guzzle that is fully unit tested and uses the latest coding practices.

    Installing Guzzle

    Go to the command line in your project folder and type in the following command (assuming you already have the package manager composer installed). If you need help how to install Composer, you should have a look here.

    php composer.phar require guzzlehttp/guzzle
    

    Using Guzzle to send a POST request

    The usage of Guzzle is very straight forward as it uses a light-weight object-oriented API:

    // Initialize Guzzle client
    $client = new GuzzleHttp\Client();
    
    // Create a POST request
    $response = $client->request(
        'POST',
        'http://example.org/',
        [
            'form_params' => [
                'key1' => 'value1',
                'key2' => 'value2'
            ]
        ]
    );
    
    // Parse the response object, e.g. read the headers, body, etc.
    $headers = $response->getHeaders();
    $body = $response->getBody();
    
    // Output headers and body for debugging purposes
    var_dump($headers, $body);
    

提交回复
热议问题