How can i validate file upload using Respect\Validation library?


On my project, i have a form with 3 inputs : 'file', 'name', 'fname'.

Assuming that $request has the data inputs of my form, to get the uploaded file, i use this code

$files = $request->getUploadedFiles();
    if (empty($files['file'])) {
        throw new Exception('Invalid image');
$newfile = $files['file'];

Then, to validate my input forms, i use the Respect\Validation Library

$validation = $this->validator->validate($request, [
        'file' => v::file()->mimetype('application/pdf'),
        'name' => v::stringType()->notEmpty()->length(2, 50)->alpha(),
        'fname' => v::stringType()->notEmpty()->length(2, 50)->alpha()

if($validation->failed() {

The fact is the file validation always fails :

var_dump($request->getParam('file')); //return NULL
var_dump($newfile); //return the following

$newfile content

object(Slim\Http\UploadedFile)#59 (8) { 
    ["file"]=> string(14) "/tmp/php409Uje" 
    ["name":protected]=> string(47) "Myfile.pdf" 
    ["type":protected]=> string(15) "application/pdf" 
    ["size":protected]=> int(1404476) ["error":protected]=> int(0) 
    ["sapi":protected]=> bool(true) ["stream":protected]=> NULL 
    ["moved":protected]=> bool(false) 

So now I’m stuck. I really can’t figure out how can i tell the validator to validate $newfile MIMETYPE for the ‘file’ input.


Are you sure you can call the validate() method this way ?
I didn’t know this library, i just browsed their documentation and i couldn’t find any examples calling validate() the same way you do.The thing is you are creating a $newfile variable but you are not using it + validate() seems to take only 1 argument, a value to verify or a string file path in case of mimetype validation.
It means you have to move $newfile before working on it :

//untested code.
//from here, we already have $newfile containing the uploaded file

$filepath = "/a/path/to/receive/uploaded/files/MyFile.pdf";


$check_file    = v::mimetype('application/pdf')->validate($filepath);
$check_name    = v::stringType()->notEmpty()->length(2, 50)->alpha()->validate($request->getParam('name'));
$check_fname   = v::stringType()->notEmpty()->length(2, 50)->alpha()->validate($request->getParam('fname'));

return ($check_file && $check_name && check_fname);