How to process PUT requests with PHP

You are probably already familiar with $_GET, $_POST and $_REQUEST but what about $_PUT? Trick question, $_PUT (as well as as $_HEAD and $_DELETE) doesn’t exist in PHP at this time. Never fear! We can create a $_PUT array with the following code:

if ($_SERVER['REQUEST_METHOD'] == 'PUT')
{
	parse_str(file_get_contents("php://input"), $_PUT

	foreach ($_PUT as $key => $value)
	{
		unset($_PUT[$key

		$_PUT[str_replace('amp;', '', $key)] = $value
	}

	$_REQUEST = array_merge($_REQUEST, $_PUT
}

Fortunately, PHP does understand PUT as a request method, so first we check to see if we should be expecting a PUT request. The next line gets the contents of the php://input stream, and parses it into an array (stored as $_PUT).

The foreach does some cleanup as parse_str splits on the literal ampersand. This is actually some code that I’ve implemented on a site of mine without any issues, but as I look at this, I wonder if there’s any repercussions to this method. Let me know if you run into any issues!

Once we’re done cleaning up the data, we merge it back into $_REQUEST to give it the same interfacing as $_GET and $_POST.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.