tkrn
tkrn

Reputation: 606

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)
        }
    }
);

Upvotes: 1

Views: 171

Answers (2)

AmericanUmlaut
AmericanUmlaut

Reputation: 2837

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.

Upvotes: 2

Kisaragi
Kisaragi

Reputation: 2218

PHP variable scope

Since the variable $uuid isn't defined, it's probably out of scope.

You need to pass the variable to your function, declare as global, or set a class property (if this is withing a class). If its set in your session, you can call it directly without assigning it to a variable anywhere your session's loaded.

Upvotes: 0

Related Questions