Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Alejandro Celaya:
Managing PUT requests with file uploads in psr-7 and middleware PHP applications
Mar 07, 2017 @ 19:17:01

Alejandro Celaya has posted a new tutorial to his site covering the handling of PUT requests in PSR-7 applications for file uploads via middleware.

It has been a long time since I first realized that handling file uploads in non-POST requests (like PUT) wasn't an easy task. One could assume the $_FILES array should be populated regardless the HTTP verb, but actually, PHP doesn't do it on its own.

After a long time wanting to find a solution to this problem, I've finally dedicated the time to get something functional, that allows file uploads to be transparently handled regardless the HTTP verb (it works the same way in POST, PUT and PATCH requests).

Since nowadays I try to work with psr-7/middleware based applications, I have created a Zend Expressive app that registers a middleware capable of parsing a multipart/form-data request body, populating the request's uploaded files array and parsed body array. This way, you can call $request->getUploadedFiles() or $request->getParsedBody() in any PUT or PATCH action, the same way you would do in a POST action.

His example application shows a simple HTML form that, when submitted, changes the HTTP request type based on a radio option selected at the bottom. He walks through the steps that the application takes to handle the upload via this middleware that makes it possible to work with the body of the PUT the same way as other requests. He goes through each part of the code that's required to make the middleware flow work and finishes up the post looking at a few other things to consider (like opting for POST over PUT for file uploads).

tagged: zendexpressive application tutorial psr7 middleware put request fileupload upload

Link: https://blog.alejandrocelaya.com/2017/03/06/managing-put-requests-with-file-uploads-in-psr-7-and-middleware-php-applications/


Trending Topics: