Search code examples
phpfat-free-framework

Variable not accessible within a particular function? Fat-Free-Framework


I write the session variable successfully. I get the session variable successfully. I can even manually define it but it is never passed to the file name portion of the function($fileBaseName, $formFieldName) below.

Any help is greatly appreciated. Thanks!

$uuid = $f3->get('SESSION.uuid'); // get session uuid

$f3->set('UPLOADS', $f3->UPLOAD_IMAGES); // set upload dir

$files = $web->receive(
    function($file,$formFieldName) {

        if($file['size'] > (5 * 1024 * 1024)) // if bigger than 5 MB
            return false; // this file is not valid, return false will skip moving it

        $allowedFile = false; // do not trust mime type until proven trust worthy
        for ($i=0; $i < count($allowedTypes); $i++) {
            if ($file['type'] == $allowedTypes[$i]) {
                $allowedFile = true; // trusted type found!
            }
        }

        // return true if it the file meets requirements
        ($allowedFile ? true : false);
    },

    true, //overwrite

    function($fileBaseName, $formFieldName) {

        $pathparts = pathinfo($fileBaseName);

        if ($pathparts['extension']) {

            // custom file name (uuid) + ext
            return ($uuid . '.' . strtolower($pathparts['extension']));

        } else {
            return $uuid; // custom file name (md5)
        }
    }
);

Solution

  • The two functions you pass to $web->receive() are closures. In PHP, closures cannot see variables declared in the scope from which they are declared. To make such variables visible, you can use the use keyword:

    $uuid = $f3->get('SESSION.uuid'); // get session uuid
    
    $f3->set('UPLOADS', $f3->UPLOAD_IMAGES); // set upload dir
    
    $files = $web->receive(
        function($file,$formFieldName) {
            //...
        },
    
        true, //overwrite
    
        function($fileBaseName, $formFieldName) use ($uuid) {
            //...
        }
    );
    

    This should make $uuid visible inside that second function.