John Davidson

php - 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.

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() ( function. That function can throw errors, e.g.

throw Exception\UploadedFileErrorException::dueToStreamUploadError(

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 ( 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:


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.


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.

My Answer:
$file = $files['file'];
$targetPath = WWW_ROOT . 'uploads' . DS . $file->getClientFilename();

If you want to determine whether the file has successfully uploaded, you can check the return value of the `moveTo` method. If the file was successfully moved, the method will return true. You can then use this information to determine whether the file has been uploaded successfully.

Here's an example of how you can do this:

$files = $request->getData('files');
$file = $files['file'];
$targetPath = WWW_ROOT . 'uploads' . DS . $file->getClientFilename();

if ($file->moveTo($targetPath)) {
// File uploaded successfully
echo 'File uploaded successfully';
} else {
// File upload failed
echo 'File upload failed';

This way, you can access the private property `$_moved` of the uploaded file object indirectly by checking the return value of the `moveTo` method.

Rate this post

3 of 5 based on 4303 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us