Send a PUT request with PHP.

This is a short tutorial on how to send a PUT request using PHP. Generally speaking, the PUT method is used to update a given resource (I will presume that you already know this).

Here is a simple example of a PUT request being carried out with cURL & PHP:

<?php

//The URL that we want to send a PUT request to.
$url = 'http://localhost/tester/log.php';

//Initiate cURL
$ch = curl_init($url);

//Use the CURLOPT_PUT option to tell cURL that
//this is a PUT request.
curl_setopt($ch, CURLOPT_PUT, true);

//We want the result / output returned.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//Our fields.
$fields = array("id" => 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));

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

echo $response;

In the code above, we used theĀ CURLOPT_PUT option to send a PUT request.

In my log.php file, which I sent the request to, I logged the REQUEST_METHOD variable from the $_SERVER array. The result:

//The request method.

'REQUEST_METHOD' => 'PUT'

But what if we want to PUT a file onto the server?

<?php

//The URL that we want to send a PUT request to.
$url = 'http://localhost/tester/log.php';

//Initiate cURL
$ch = curl_init($url);

//Use the CURLOPT_PUT option to tell cURL that
//this is a PUT request.
curl_setopt($ch, CURLOPT_PUT, true);

//We want the result / output returned.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//Our fields.
$fields = array("id" => 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));

//The path of the file that we want to PUT
$filepath = 'example_file.txt';

//Open the file using fopen.
$fileHandle = fopen($filepath, 'r');

//Pass the file handle resorce to CURLOPT_INFILE
curl_setopt($ch, CURLOPT_INFILE, $fileHandle);

//Set the CURLOPT_INFILESIZE option.
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($filepath));

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

echo $response;

If you look at the PHP code above, you’ll see that I opened the given file before passing its file handle to cURL using the CURLOPT_INFILE option. I also specified the file size in bytes by using the CURLOPT_INFILESIZE option.