Passing $_FILES in a registration function

Asked

Viewed 503 times

-1

Well, I’m thinking about a way to register items in a database, but I thought:

"and if the item has an image ?"

So I wrote a script to send this image, however, I don’t know if it’s correct or not to pass the $_FILES as a parameter of a function that will be called in another script. If so, could you help me by telling me if there are any mistakes, or if there is another way to upload 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!';
    }
}
  • Your question is how to manage the image save and relate the information of the saved letter in bank?

  • @Dnick, my question is whether, when executing the function, I should pass $_Files as parameter, or if only within the function it already runs smoothly, and if I need to pass it as parameter, as I do ?

2 answers

1


The $_FILES nothing more than a array. And in accordance with documentation of PHP, he 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 question of definition, what is the $_FILES? Based on the documentation

The variable global $_FILES will contain all the information of the file sent. And it assumes the name of the file sent in the input, for example name="file", but that doesn’t stop it being any name.

a global variable or superglobal

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 that it was created.

The variable $_FILES is only 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 method parameter. What is advisable is to make a check if it exists and if it has been filled in correctly on <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);
}

So about your doubts:

Should I pass $_Files as a parameter or if only within the function it already runs 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)){}, besides, one should take care not to overwrite it at another point in the file.

I recently posted a reply on how to manipulate $_FILES with multiple files. In this actual example I did manipulate and pass it by parameters in the method.

  • but as I pass it by parameters ?

  • 1

    updated and put an example in practice at the end of the reply for you to take a look at

  • you need to pass $_FILES as a parameter to use it in the function ?

  • 1

    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)){}, besides, one should take care not to overwrite it at another point in the file.

1

There are a few things I wouldn’t advise in your role like using @ to cover up, pass the connection and query by parameter, use strstr function, advised 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.';
        }
    }
}
  • but in this case, I must pass $_FILES as a parameter in the function or within the function only, without parameter it already works ?

  • if yes, how do I pass $_Files as parameter?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.