'CakePHP 4 - access private property to determine whether a file has successfully uploaded
In CakePHP 4.x the docs show how you can move an uploaded file as follows:
$files = $request->getUploadedFiles();
// Move the file.
$files[0]->moveTo($targetPath);
This works in terms of moving the uploaded file to wherever $targetPath
is specified as.
But - how do you determine whether this was actually successful? After looking at the framework code this uses Laminas\Diactoros\UploadedFile
which contains the moveTo()
(https://github.com/laminas/laminas-diactoros/blob/2.10.x/src/UploadedFile.php#L162) function. That function can throw errors, e.g.
throw Exception\UploadedFileErrorException::dueToStreamUploadError(
self::ERROR_MESSAGES[$this->error]
);
The end of the function (if no errors get thrown) contains:
$this->moved = true;
The function's return type is void
.
$moved
is a private property of this class and there doesn't seem to be any function that allows you to "get" the value of $moved
outside that class.
So how do you determine whether or not this actually succeed? Or do you just assume if it doesn't thrown an error it has succeeded?
It seems strange because PHP's native move_uploaded_file
(https://www.php.net/manual/en/function.move-uploaded-file.php) returns boolean, which is what you'd expect since you'd probably want to know whether uploading a file has actually worked successfully or otherwise.
What's stranger is that when I debug $files
in the CakePHP application:
$files[0]->moveTo($destinationFile);
debug($files);
die;
It shows a private property for "moved" which is true
:
object(Laminas\Diactoros\UploadedFile) id:0 {
// ...
private moved => true
private size => (int) 45578
private stream => object(Laminas\Diactoros\Stream) id:1 { }
}
But because that's a private property I can't access it in my application, e.g.
debug($files[0]->moved);
results in:
Cannot access private property Laminas\Diactoros\UploadedFile::$moved
In the above case I have manually checked that the file got moved to the correct location on my filesystem. But I can't determine that via my code, it seems.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|