W3docs

PHP cURL HTTP PUT

To make an HTTP PUT request using PHP's cURL functions, you can use the following snippet:

To make an HTTP PUT request using PHP's cURL functions, you can use the following snippet:

Example of PHP cURL HTTP PUT request

<?php

// Initialize cURL session
$ch = curl_init();

// Set the URL, request method (PUT), and other options
curl_setopt($ch, CURLOPT_URL, "http://example.com/api/resource/123");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(["field1" => "value1", "field2" => "value2"]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/x-www-form-urlencoded'
]);

// Execute the request and get the response
$response = curl_exec($ch);

// Check for errors
if ($response === false) {
    echo 'cURL Error (' . curl_errno($ch) . '): ' . curl_error($ch);
}

// Close the cURL session
curl_close($ch);

?>

This will make a PUT request to the specified URL with the specified data. The snippet includes CURLOPT_RETURNTRANSFER to capture the response body and sets the appropriate Content-Type header. You can add additional options to customize the request, such as enabling SSL or setting custom headers. For modern REST APIs, consider using json_encode instead of http_build_query.

For more information about cURL and the available options, you can refer to the PHP documentation: http://php.net/manual/en/book.curl.php