tmp_name usage - does it preserves or perish?

Hello all,

I’m trying to create two separate methods on a validation class.

One will validate the upload:
file_size + upload error status + is_uploaded;

Another method will validate an image:
file extension;

The intended is to have something like this:

validateUpload($myFileFormField);
validateImage($myFileFormField);

resizeImage($IdontKnowYet);

insertRecord();

Were insert record will insert the data, and the resized image into the database.

Questions about if we should or shouldn’t not store images on a database aside, since I will do it, I wish to NOT store the files in a folder and into the database, but doing only into the database.

Question:
When we pass from the Upload method, to the validateImage method, will the value of tmp_name be lost ?

Thanks a lot in advance,
Márcio

Ok. I’m kinda nervous will all this variable travels and objects and classes working from one file to another… understanding the work-flow here is so capital in order to not loose what we are doing.

I was already thinking: “Should I drop all this thing off? Have I arrived on a dead end?”

This is what you get when you don’t know were you are putting yourself into but, as other have stated as well: That is what makes you progress. Or die. :slight_smile:

Oh well… :slight_smile:

I will go on with the code executing and cross my fingers that all this works at the end. More confident now. :slight_smile:

Thanks a lot for your time,
Márcio

What you’re doing is fine, $_FILES is a superglobal and so can be accessed in any scope.

‘end of script excecution’ means when all files have finished running.

Ok.

Different objects need to manipulate this $_FILE data. So, it’s not only a question of preserving is existence cross method but, across all classes that can use it, until, it’s ready to be inserted into the database.

So, validate object needs to use it.
Then, resize object needs to use it.
Finally, dao object needs to use it, so that the data can be stored into the database.

Here are the examples of two methods:
Those two methods are inside my validation class:

  /**
     *
     * @param <array> $campoForm
     * @param <int> $limiteKb
     * @return <boolean>
     */
    public function validaUpload($campoForm, $limiteKb = null)
    {
        $nomeTemporario = $campoForm['tmp_name'];
        $codigoErro = $campoForm['error'];

        //se o upload NÃO foi OK - corre o switch
        if ($codigoErro != UPLOAD_ERR_OK)
        {
            switch ($codigoErro)
            {
                //valida o tamanho no php-ini e no MAX_FILE_SIZE no formulário - contudo, este último não é fiável pois, depende do user agent e do seu suporte para isso.
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    $this->_msgErro[$campoForm] = 'Erro no upload: O tamanho do ficheiro é demasiadamente grande. Reduza as dimensões e tente novamente.';
                    break;

                case UPLOAD_ERR_PARTIAL:
                    $this->_msgErro[$campoForm] = 'Erro no upload: O ficheiro não foi enviado na totalidade. Tente novamente.';
                    break;

                case UPLOAD_ERR_NO_FILE:
                    $this->_msgErro[$campoForm] = 'Erro no upload: Nenhum ficheiro foi enviado.';
                    break;

                case UPLOAD_ERR_NO_TMP_DIR:
                    $this->_msgErro[$campoForm] = 'Erro no upload: A directoria de upload não foi encontrada.';
                    break;

                case UPLOAD_ERR_CANT_WRITE:
                    $this->_msgErro[$campoForm] = 'Erro no upload: Não foi possível escrever no ficheiro de envio.';
                    break;

                case UPLOAD_ERR_EXTENSION:
                    $this->_msgErro[$campoForm] = 'Erro no upload: A extensão não é suportada.';
                    break;

               default:
                   $this->_msgErro[$campoForm] = 'Erro no upload: Erro desconhecido.';
            }
        }

        //se o Upload foi OK mas, se o size for maior que o limite definido (independente do user agent), em KB:
        elseif (isset($limiteKb) && ($campoForm['size'] / 1024 > $limiteKb))
        {
            $this->_msgErro[$campoForm] = 'Erro no upload: O tamanho do ficheiro é maior que o limite especificado.';
        }
        //se o upload foi OK, se o filesize foi OK mas, se o ficheiro não veio do upload:
        elseif (!is_uploaded_file($nomeTemporario))
        {
            $this->_msgErro[$campoForm] = 'Erro no upload: Ficheiro não corresponde ao ficheiro enviado.';
        }
        else
        {
            //se tudo está ok, devolve true.
            return true;
        }
    }


    /**
     *
     * @param <array> $campoForm
     * @return <boolean>
     */
    public function validaImagem($campoForm)
    {
        $nomeTemporario = $campoForm['tmp_name'];

        //se for imagem:
        if (getimagesize($nomeTemporario))
        {
            $permitidas = array('jpeg', 'jpg', 'gif', 'png');
            $extensoes = strtolower(pathinfo($nomeTemporario, PATHINFO_EXTENSION));

            if (in_array($extensoes, $permitidas))
            {
                return true;
            }
            else
            {
                $this->_msgErro[$campoForm] = 'Erro na imagem: A extensão não é permitida. Apenas jpg, gif ou png são suportados.';
                return false;
            }
        }
        else //se a getimagesize devolver falso, é porque não se trata de uma imagem:
        {
            return false;
        }
    }

I’ve not yet write the resize class, but I believe it will use a specific $_FILE as well, and the same will go for the insert method that will insert the image.

I really don’t know what “execution script time means” on php manual, that’s why I’m having this doubts. You reply - well, test it. But, I’m not that experienced into php in order to user proper methods for doing so, and I will probably have so many errors down the path when I first test it, that I would prefer to know the answer if someone has already done something similar.

Thanks again,
Márcio

No. It is destroyed at the end of the script execution I think.

validateUpload is not a standard function. Without seeing the code for this function, this question cant be answered.

Assuming validateUpload doesn’t unset the variable, any variable defined in a context greater than the current will exist when the current context expires, until garbage collection at the end of script execution.