Reputation: 39
This is most likely due to me not being very knowledgeable with PHP, but here goes: I'm using Fat-Free Framework to create a project and I've now bumped into an issue I'm having a though time to solve/understand.
This is happening inside the callback method for a file upload, which I'm handling with Fat-Free's Web extension, using the receive($func=NULL,$overwrite=FALSE,$slug=TRUE)
method (both $func
and $slug
can be functions, which I'm using in the example below). With this extension I can use a function as an argument to validate the file in some way and another one to change the filename.
The issue is that I can't use any of the global $f3 variables inside those methods. E.g. In the code below you can see I want to get a maxFileSizeMb
variable to check which is the maximum file size allowed, but when I call $this->f3->get('maxFileSizeMb')
, either directly or by assigning it to a variable earlier in the function, it will break the code.
$this->f3->set('UPLOADS','uploads/'.$this->f3->get('tmpMediaPath').'/');
$this->f3->set('maxFileSizeMb', 2);
$this->f3->set('fileNameLenght', 30);
// Using f3 \Web extension
$overwrite = false; // set to true, to overwrite an existing file; Default: false
// $slug = true; // we'll generate a new filename
$web = \Web::instance();
$files = $web->receive(function($file,$formFieldName) {
// Check against the maximum allowed file size
if($file['size'] > ( 2 * 1024 * 1024 )) // if bigger than 2 MB
// >>> ^ <<< using $this->f3->get('maxFileSizeMb'); breaks the code
return false; // this file is not valid, return false will skip moving it
return true; // allows the file to be moved from php tmp dir to your defined upload dir
},
$overwrite,
function($fileBaseName, $formFieldName){
$fileExtension = ".tmp"; // Determine the true image type and rename it later on
// ##TODO## check if value is truly unique against the database. Here or elsewhere?
$randomName = bin2hex(openssl_random_pseudo_bytes( 30 ));
// >>> ^^ <<< using $this->f3->get('fileNameLenght'); breaks the code
return $randomName.$fileExtension;
}
);
Thanks in advance for any input on this.
Upvotes: 1
Views: 827
Reputation: 39
Yeah, I knew this was lack of PHP knowledge. It's necessary to call the Base instance so that the variables are accessible. This means that we can call this within those functions and it will retrieve the value:
$f3=Base::instance();
$maxFileSizeMb = $f3->get('maxFileSizeMb');
(solution from a similar question, thought the solution isn't entirely applicable - at least I couldn't make all the alternatives work: Fat-Free-Framework global variables and functions)
Upvotes: 1