How to process PUT requests with PHP

Josh Sherman
1 min read
Software Development 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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

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

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles