Can I create a new session with the tag form?

Asked

Viewed 71 times

0

Hello, I’m trying to create a simulation in the assembly of Site, and for that I already got the simulation of image exchange through $_SESSION.

I created this $_SESSION below to load the first banner image, and allow the user to exchange the image, through a form and image upload file.

// Inicio da Sessão de Upload de Imagem.
if(!isset($_SESSION['banner01'])){ // Se a Session não for iniciada
    $img01 = 'img_banner/01.png'; // Carrega essa imagem já pré determinada
}else{ // Se não
if(isset($_SESSION)) { // Se a Session for iniciada
    $img01 = ''.$_SESSION['banner01'].''; // Carrega a imagem selecionada pelo usuario através do formulário de upload de imagem.
}}

The form used is the one below:

<form action="recebe_upload_01.php" method="POST" enctype="multipart/form-data">
<label>Selecione uma nova Imagem:</label><br />
<input type="file" name="img01[]" accept="image/*" ><br /><br />
<input type="submit" name="img01" value="Atualizar">
</form>

And the upload file used is this below:

<?php
@session_start(); // Inicia a session.

if(isset( $_POST['img01'] ) ){
    //INFO IMAGEM   
    $file = $_FILES['img01'];
    $numFile = count( array_filter( $file['name'] ) );
    //PASTA
    $folder = '../img_simulador';
    //REQUiSITOS
    $permite = array( 'image/jpeg', 'image/png', 'image/gif' );
    $maxSize = 1024 * 1024 * 5;
    //MENSAGEM
    $msg = array();
    $errorMsg = array(
        1 => 'O arquivo no upload é maior que o Limite de finido em upload_maxsize',
        2 => 'O arquivo ultrapassa o limite de tamanho em Max_file_size',
        3 => 'O upload do arquivo foi feito parcialmente',
        4 => 'Não foi feito o upload do arquivo',
    );
    if($numFile <= 0){
        echo 'Selecione uma Imagem!!';
    }else{
        for($i = 0; $i < $numFile; $i++){
            $name = $file['name'][$i];
            $type = $file['type'][$i];
            $size = $file['size'][$i];
            $error = $file['error'][$i];
            $tmp = $file['tmp_name'][$i];

            $extensao = @end(explode('.', $name));
            $novoNome = rand().".$extensao";

            //Se você quer várias mensagens não use else.
            if($error!=0){
                $msg[] = "Erro: {$errorMsg[$error]}! Nome do arquivo: {$name}.";
            }if(!in_array($type, $permite)){
                $msg[] = "Tipo do arquivo inválido! Nome do arquivo: {$name}.";
            }if($size > $maxSize){
                $msg[] = "Tamanho do arquivo muito grande! Nome do arquivo: {$name}.";
            }else{
                $destino = $folder."/".$novoNome;
                if(move_uploaded_file($tmp, $destino)){
                    $_SESSION['banner01'] = $destino;

            echo "<meta http-equiv='refresh' content='0; URL= inicial_banner.php'>
            <script language='javascript'>
            window.alert('Imagem atualizada com sucesso!');
            </script>";
            }}}}}
?>

My question is whether I can insert one or more images using a form tag to add them. In other words, perhaps creating new $_SESSION with the names $_SESSION['banner02'], 03, 04 and so on, or even with random names, and the images being stored in the "$Folder = ' folder.. /img_simulator';", as determined in the image upload file.

These $_SESSION would have to be temporary, because when the user logs out, or even closes the browser, they are destroyed, leaving only the image already predetermined in a future page opening.

I do not know if I could express myself in a comprehensive way what I need, but I hope that friends have understood my doubt!

So I ask you how?

And how it could be done?

Big hug to all, and waiting for good tips.

  • The name of these images will stay stored where for a future page opening?

  • What I want is to give the opportunity of the user to add as many images as he wants, since it is an image banner. But as it is a simulation, these images that the user add, will be destroyed at each logout or browser shutdown. leaving only the pre-determined initial image. That is, these new images added by the user, did not exist in a future page opening, and the folder where will store them (../img_simulator), is programmed to delete all files every 24 hours.

1 answer

0

I don’t quite understand your ultimate goal, but regarding $_SESSION, there is only one for each SESSION. What happens is that you can destroy it unset ($_SESSION) and reboot again with other values. But I think you don’t want this, after all you will lose all information relating to the session. A likely solution would be to ensure SESSIONS within SESSIONS and you can access them whenever you want. Do so:

$_SESSION["session01"]=Grave aqui o que quiser gravar, (uma array ou qualquer coisa),
$_SESSION["session02"] =Grave aqui o que quiser gravar, (Outra array ou qualquer outra coisa).

When you no longer need each of them, simply delete them:

unset ($_SESSION["session01"])//Delete session information "session01".

So you record different information and later destroy what needs to be destroyed, and keep the Main Session until the user logs out.

I hope it fits.

  • My goal, is to give the opportunity to the user to add as many images as he wants, since it is an image banner but as it is a simulation, these images that the user add, will be destroyed at each logout or closure of the browser. leaving only the pre-determined initial image.

  • but during the session the images can be seen in the browser?

  • That’s right, that’s right.

  • So the solution you are looking for is the same one I posted. Use $_SESSION["banner01"]="path/banner01.jpg", $_SESSION["banner02"]="path/banner02.jpg". And so on.. When you no longer need you can destroy SESSION["banner01"], but $_SESSION is not destroyed.

  • Right @zwitterion, but I have no idea how to build the code or even the form so I can add the new images. That’s my problem... The friend has how to show me how to create the code with the working form?

  • Check this page out. http://php.net/manual/en/features.file-upload.multiple.php .... I think you can create from codio. Just remember that the $_FILES array can store any and all upload inputs from a page.... I think q vc is confusing $_SESSION and $_FILES. Files is an array that keeps information about upload files and $_SESSION information about the session. Try to do this... epois t mando um codigo funcional...http://www.w3bees.com/2013/02/multiple-file-upload-with-php.html

Show 1 more comment

Browser other questions tagged

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