-
Notifications
You must be signed in to change notification settings - Fork 2
How to create a multipart form
Creating a multipart form isn’t as straight forward in MovLib as in many other softwares, there are multiple reasons for that. Nginx is handling our file uploads and routes, if a client tries to send an entity that is too large, nginx will directly drop the request and answer with a 413 error. While this is good for the client because there’s no waiting time, it’s bad for your application because we don’t know anything about it. Therefor I came up with a solution that will let the form know about this problem. But in order to enable this for a new multipart form you want to create you have to set up a very special route. Open your routes.php
file, because that is the place where all the magic goes.
First you have to set up your route as usual, e.g.:
location ^~ <?= $r("/multipart") ?> {
location = <?= $r("/multipart/form") ?> {
set $movlib_presenter "Multipart\\Form";
try_files $movlib_cache @php;
}
return 404;
}
We have to set the nginx multipart variable in order to let our form know that this location is multipart enabled. Always set this variables value to 0
(zero)!
location ^~ <?= $r("/multipart") ?> {
location = <?= $r("/multipart/form") ?> {
set $movlib_presenter "Multipart\\Form";
set $movlib_multipart 0;
try_files $movlib_cache @php;
}
return 404;
}
But now we also want to catch those 413 errors from nginx. To do this we have to create a named location block, this results in some duplicated code, but it's very hard to suppress this in such an easy configuration file. We are just glad it's only compiled once and extremely efficient, rather than coding hundreds of lines in PHP.
location @multipart_form_entity_too_large {
set $movlib_presenter "Multipart\\Form";
set $movlib_multipart 1;
include sites/conf/fastcgi.conf;
}
location ^~ <?= $r("/multipart") ?> {
location = <?= $r("/multipart/form") ?> {
error_page 413 @multipart_form_entity_too_large;
set $movlib_presenter "Multipart\\Form";
set $movlib_multipart 0;
try_files $movlib_cache @php;
}
return 404;
}
It’s very important that you set the value of $movlib_multipart
to 1
(one), this informs the form instance of your presentation class that the user tried to upload a file that was too big.
That’s it, your form is now multipart enabled and handles everything by itself.