How to perform a Guzzle PUT request in PHP?

To perform a PUT request using Guzzle in PHP, you need to follow these steps:

  1. Install Guzzle using Composer if you haven't already. You can run the following command in your project's root directory where composer.json resides:

    composer require guzzlehttp/guzzle
  2. Once Guzzle is installed, you need to include the autoloader in your PHP script:

    require 'vendor/autoload.php';
  3. Create a new instance of the GuzzleHttp\Client class:

    $client = new GuzzleHttp\Client();
  4. Build the PUT request by providing the necessary options, such as the URL, request headers, body, etc. For example:

    $url = 'http://example.com/api/resource'; $headers = [ 'Authorization' => 'Bearer your-access-token', 'Content-Type' => 'application/json', ]; $body = json_encode(['key' => 'value']); $options = [ 'headers' => $headers, 'body' => $body, ]; $response = $client->put($url, $options);

    In this example, we're sending a PUT request to http://example.com/api/resource with a JSON payload encoded as a string in $body. Additionally, we set the request headers, including an authorization token.

  5. Handle the response from the server:

    $statusCode = $response->getStatusCode(); $content = $response->getBody()->getContents();

    Here, $statusCode will contain the response status code (e.g., 200 for success), and $content will hold the response body as a string.

That's it! You have successfully performed a PUT request using Guzzle in PHP.