Passing $ _FILES in a registration function

-1

Well, I'm thinking of a way to register items in a database, though, I thought:

  

"What if the item has an image?"

So I wrote a script to send this image, however, I do not know if it is correct or not to pass $_FILES as a parameter of a function that will be called in another script. So, could you help me by saying if there are any errors, or if there is another way to send the image?

function adicionaCarta($cardName, $cardQuantity, $cardEditionID, $cardTypeID, $cardAttibuteID, $cardMonsterTypeID, $cardLRL, $cardATK, $cardDEF, $cardDesc, $cardStatusID, $query, $conexao){

    if(isset($_FILES['imagem-card']['name']) && $_FILES['imagem-card']['error'] == 0){
        $arquivo_tmp = $_FILES['imagem-card']['tmp_name'];
        $nomeCard = $_FILES['imagem-card']['name'];
        // Pega a extensão
        $extensao = pathinfo($nomeCard, PATHINFO_EXTENSION);
        // Converte a extensão para minúsculo
        $extensao = strtolower($extensao);
        // Somente imagens, .jpg;.jpeg;.gif;.png
        if(strstr('.jpg;.jpeg;.gif;.png', $extensao)){
            // Cria um nome único para esta imagem
            // Evita que duplique as imagens no servidor.
            // Evita nomes com acentos, espaços e caracteres não alfanuméricos
            $novoNomeCard = uniqid(time()) . '.' . $extensao;
            // Concatena a pasta com o nome
            $destino = '../img/cards/' . $novoNomeCard;
            // tenta mover o arquivo para o destino
            if(@move_uploaded_file($arquivo_tmp, $destino)){
                mysqli_query($conexao, $query);
            }else{
                echo 'Erro ao salvar o arquivo. Aparentemente você não tem permissão de escrita.<br />';
            }
        }else{
            echo 'Você poderá enviar apenas arquivos "*.jpg;*.jpeg;*.gif;*.png"<br />';
        }
    }else{
        echo 'Você não enviou nenhum arquivo!';
    }
}
    
asked by anonymous 03.08.2017 / 14:27

2 answers

1

The $_FILES is nothing more than an array . And according to PHP documentation , it says:

  

An associative array of items sent through the current script by   HTTP POST method. The structure of this array is detailed in the Uploads section   with the POST method.

In definition, what is $_FILES ? Based on documentation

The global $_FILES variable will contain all the information in the uploaded file. And it takes the name of the file sent in the input, for example name="file" , but that does not prevent it from being any name.

A global variable or superglobals

  

are native variables that are always available in all scopes. Unlike the local variables that we declare to have the inverse behavior, that is, it is only available in the scope it was created.

The variable $_FILES is just one of the global variables, there are also:

  • $ GLOBALS
  • $ _ SERVER
  • $ _GET
  • $ _ POST
  • $ _ FILES
  • $ _ COOKIE
  • $ _ SESSION
  • $ _ REQUEST
  • $ _ ENV

The fact that the variable is global and an array, nothing prevents you from passing as a parameter of a method. What is advisable is to make a check if it exists and has been correctly filled in <form> , for example:

if (isset($_FILES)) {
    metodoQualquer($_FILES);
}

You can also assign a variable to make your code more readable

if (isset($_FILES)) {
    $imagem = $_FILES;
    //ou
    $arquivo = $_FILES;
    //ou
    $pdf = $_FILES;
    metodoQualquer($pdf);
}

Then about your doubts:

Should I pass $ _Files as a parameter, or if just inside the function does it run smoothly? A: Because it is a global variable you are not required to pass it as a parameter to access it within a method. But try to validate if the variable has been defined if (isset($_FILES)){} , in addition, care must be taken not to overwrite it at another point in the file.

Recently I posted a answer about manipulating $ _FILES with multiple files. In this real example I did I manipulate and pass it by parameters in the method.

    
03.08.2017 / 20:33
1

There are some things you would not advise in your function like using @ to 'cover up', pass the connection and query by parameter, use strstr function, I would recommend an array to check extensions, here is an example:

if (isset($_POST['submit'])) {
    $j = 0; //Começamos pelo indice 0

    $caminho = "uploads/"; //Definir o caminho para salvar o arquivo
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) { // loop a cada elemento selecionado

        $extensoesValidas = array("jpeg", "jpg", "png"); //extensoes que são permitidas
        $ext = explode('.', basename($_FILES['file']['name'][$i])); //achar a extensao
        $extensaoFicheiro = end($ext); //guardar as extensões

        $caminho = $caminho.md5(uniqid()) . "." . $ext[count($ext) - 1]; //setar o caminho com o novo nome da imagem 
        $j += 1; //incrementamos o nº de uploads  

        if (($_FILES['file']['size'][$i] < 100000) //aproximadamente 100kb
            && in_array($extensaoFicheiro, $extensoesValidas)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $caminho)) {
                echo $j.
                ') Imagem enviada com sucesso';
            } else { //se a imagem nao foi movida
                echo $j.') Aconteçeu um erro por favor tente novamente.';
            }
        } else { //se o tipo ou tamanho nao é conrespondente 
            echo $j.') extensão ou tamanho invalido, tente novamente.';
        }
    }
}
    
03.08.2017 / 15:38