Add an initial value to the array

Asked

Viewed 62 times

-1

I wonder if there is any way to add a value at the beginning of each array , I am creating a gallery for a website but I am inserting the images in the database but I need to rename each upload so that it does not have images with the same name .

that is the code

if (!is_dir($diretorio)){ echo "Pasta $diretorio nao existe";} 

    else { echo "A Pasta Existe<br>";
            $arquivo = isset($_FILES['arquivo']) ? $_FILES['arquivo'] : FALSE;
            $nome = 'test';
            for ($k = 0; $k < count($arquivo['name']); $k++)
            {
                $destino = $diretorio."/".$nome.$arquivo['name'][$k];
                 $imgs = $arquivo['name'];
                 $array  = implode(',', $imgs);
                    var_dump($array);
                    $inserir->insert('test', ' img=? ',array($array)); 


                if (move_uploaded_file($arquivo['tmp_name'][$k], $destino))
                 { 
                   echo "foi"; 

                 }

                else 
                {
                    echo "não foi";
                }
            }     


        } // fecha else
}    

at the time it uploads it already goes with the correct name , but in the database it send only the name that was no longer changing to which I chose.

Well I tried using the implode already using the value after the ',test' comma but the index of the array 0 is without the value that was placed.

  • 1

    Simpler than that would be not using the original name when saving. Just save with the bank’s own ID. 000001.jpg, 000002.jpg and so on. If you want shorter names, you can use Base64 or hexa. If you need the original name for something, just keep it in DB.

  • then how do I use the id to send to the bank ? I already tried to use md5 but it goes only to the server and does not go to the bank the new name

  • $imgs = $nome . $arquivo['name'];

  • Asim only serves to change to send to the server , but I need to enter in the bank .

  • You are already sending the data to the database before saving the image, just use the returned ID in the insert as the file name. No need to write the new name in the bank, after all, if it is the ID that came from the bank it is already there.

1 answer

1


The question asks "add initial value in array" but the right one would be "concatenate value in array items". These are different things.

To make it clearer

$arr = array() // isso aqui é um array



// $arr é um array, mas os valores dentro, não são arrays.
$arr = array(
    'foo', // isso aqui não é um array.. é uma string
    'bar' // idem
)

Without further ado, let’s cut to the chase,

        for ($k = 0; $k < count($arquivo['name']); $k++)
        {
            $destino = $diretorio."/".$nome.$arquivo['name'][$k];
             $imgs = $arquivo['name'];
             $array  = implode(',', $imgs);
                var_dump($array);
                $inserir->insert('test', ' img=? ',array($array)); 


            if (move_uploaded_file($arquivo['tmp_name'][$k], $destino))
             { 
               echo "foi"; 

             }

            else 
            {
                echo "não foi";
            }
        }   

In this excerpt, personal opinion, I see a mistake of logic.

You are writing to the database before uploading.

What happens if the move_uploaded_file() fail? Runs the risk of having data in the database unrelated to an existing file.

I suggest you reverse by completing the file migration and then saving the data in the database.

Note the term "migration" as it is different from upload. At this point the upload has already been done and the file is on the server. The function move_uploaded_file() just move the file to another location. But anyway, that’s not the focus here.

    for ($k = 0; $k < count($arquivo['name']); $k++) {
        $destino = $diretorio."/".$nome.$arquivo['name'][$k];
        if (move_uploaded_file($arquivo['tmp_name'][$k], $destino)) { 
            echo "foi"; 
            $movido[] = $arquivo['name'][$k];
        } else {
            echo "não foi";
        }
    } 
    if (isset($movido) && !empty($movido)) {
         var_dump($movido);
         $inserir->insert('test', ' img=? ', $movido));
    }

If you want to set unique names, you could do this

$movido[] = $k.'_'.$arquivo['name'][$k];

But for that it would have to have the same pattern here too:

$destino = $k.'_'.$diretorio."/".$nome.$arquivo['name'][$k];

Otherwise it loses its reference and becomes meaningless.

Just be aware that this does not guarantee unique names.
In a next upload with file of the same name, you will have duplicate names anyway.

Something "ideal" in the sense that you wouldn’t have to worry about it is generating a "unique" string or that it would hardly repeat.

I usually use "date + time" in timestamp format.

Shop like this:

$str = $arquivo['name'][$k];
$extensao = substr($str, strrpos($str, '.')+1); // não confie muito nisso.*

$arquivo_nome = time().'_'.$k.'.'.$extensao;

$movido[] = $arquivo_nome;

$destino = $k.'_'.$diretorio.'/'.$arquivo_nome;

/*
Os nomes dos arquivos será algo como:
2367639897_1.jpg
2367639897_2.jpg
2367639897_3.jpg
*/

 /*
 O motivo de incrementar os números sequenciais ao timestamp é que a execução é tão rápida que o timestamp se repetirá. Por isso, os números sequenciais concatenados dão uma unicidade. 

 Esteja ciente que isso também não garante 100%. Num sistema com múltiplos acessos, pode acontecer de 2 ou mais usuários simultaneamente executando o upload e coincidentemente obter o mesmo timestamp.

 Caso queira garantir ainda mais a unicidade, poderia concatenar com o ID do usuário logado, o ID de sessão, ou qualquer coisa que seja único daquele usuário mesmo que não esteja logado. Nesse caso só teria duplicidade se uma mesma conta estivesse logada em locais diferentes por pessoas diferentes e executando tudo ao mesmo tempo. A probabilidade é muito remota, porém, possível de acontecer. Enfim, você tem que ir pensando nas diversas possibilidades considerando até onde é viável dentro do contexto do modelo de negócios. Nem sempre precisará elaborar com tanta minuciosidade.

Optionally, if you already have a unique ID related to these images, you can use this ID instead of the timestamp or anything else you prefer. It’s your system, do as you please. */

Important: Be aware that I am oblivious to what is executed in the method $inserir::insert(). Therefore, I cannot foresee subsequent errors that may occur.








Obs:

In this example excerpt:

$extensao = substr($str, strrpos($str, '.')+1); // não confie muito nisso.*

The ideal is to determine the extension according to the mime-type information.

A user can send a arquivo.gif even though it is a image/jpg. I mean, the name is .gif but the image is a jpg.

Browsers usually display, but there are browsers that block. So be cautious about how you get or determine the file extension.
Consult: /a/119493/4793

  • Thanks man it worked out I managed to send to the bank as a string with the name generated in the $name , thank you very much :) , I know there is another way but I wanted to insert a string with all the images just separating by "," and it worked :) mt obg.

Browser other questions tagged

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