Take external variable value and play in an input

Asked

Viewed 473 times

0

I have an image upload, which has a variable called $nome_atual, where the file path is stored.

I need to take that amount and play in one input, on another page. It is possible?

PART OF UPLOAD.PHP FILE

 /* se enviar a foto, insere o nome da foto no banco de dados */
            if(move_uploaded_file($tmp,$pasta.$nome_atual)){
                mysql_query("INSERT INTO fotos (foto) VALUES (".$nome_atual.")");
                echo "<img src='fotos/".$nome_atual."' id='previsualizar' class='img-responsive'>"; //imprime a foto na tela
                echo "'http://audiosonic.com.br/novo/fotos/".$nome_atual."'";
            }else{
                echo "Falha ao enviar";
            }
        }else{
            echo "A imagem deve ser de no máximo 1MB";
        }
    }else{
        echo "Somente são aceitos arquivos do tipo Imagem";
    }
}else{
    echo "Selecione uma imagem";
    exit;
}
  • You can get this value on the other page in several ways. The simplest, is using get, but you can also use post, Sessions, cookies and whatever else your creativity allow.

  • Any practical examples? I’m a beginner, I’m having trouble doing.

  • You just need to take the value, or also send the file from that other page?

  • The other page in the case would be this? /novo/fotos/

  • This upload uploads the image and already displays it. The other page, I say main, is a registration form. The person who registers has to send a document proving it, so upload it. It was the most interesting way I could do it. The file in question is upload.php, and there is another, matricula.php, which has a field that needs to be filled with the image path, before saving in the database.

  • But how is this upload.php page being called? Depending on how you’re calling it, the methods to get the value can change. Session is not the most "beautiful" way to do it. If you still want to, just give a session_start() at the beginning of the pages that will use the sessions, and then set a session variable as you do with other variables. $_SESSION['imageurl'] = 'blábláblá' and then call it on the matricula.php page, since it is like a super global variable, with some important differences. Worth searching about.

  • <form id="formulario" method="post" enctype="multipart/form-data" action="3-upload.php">&#xA; <input type="file" id="imagem" name="imagem" /> <br>&#xA; </form>&#xA; <div id="visualizar"></div>

  • @Claydersonferreira, I’m not really worried about beauty, because I’m really behind on it. I’m going to look into what you said, thank you. If you can direct me better on the subject, I would be very grateful! Thank you for your time!

  • In fact, I should have put the image upload in the same register that I’m doing, 1 thing only, I wouldn’t have any problems... but, I’m still doing some more things, I won’t be able to change everything, from scratch... so I think a solution, even if it is in "gambiarra"be the best for the moment.

  • @Everson, I need to take the full path of the image, to play on another form, which goes to the database, no matter the form, just need it to be on the new form, to perform the complete registration.

  • @Francis, the pages are as follows:: matricula.php, containing the form and upload.php, who sends the image.

Show 6 more comments

1 answer

0

As the questioner said that he does not have time to explore and the right way, he wants something simple and did not give enough information for a better answer, I will give a solution.

Although this solution will not bring any safety risk or performance to your application, do not recommend use it for organisational reasons. In the future, if you don’t do things as recommended, it will be almost impossible to maintain your code.

A second problem of using the method below is that if the user is disabled cookies, there is a real chance that your application will not work as expected. But since the people who disable cookies are a minority and given the above reasons, let’s go.

Initial considerations

Your code in a vulnerability called SQL Injection and is using a discontinued PHP function, all of it right there on the line where you do INSERT.

As it is another matter, I will not address it here. Just say it should be fixed before you put the system into production, otherwise you’ll get a headache.

Come on

At the beginning of your upload.php and matricula.php files, just after opening the PHP tag, start the Sessions and leave it as follows:

<?php

    session_start();

Now, we are able to use the super global variable $_SESSION. The variable $_SESSION is a array. You should store your data in it in array format, never directly. See an example:

<?php

    session_start();

    #certo
    $_SESSION['imageUrl'] = 'Aqui você pode colocar qualquer coisa'

    #errado
    $_SESSION = 'Essa é a maneira errada de usar sessions';

The magic behind the sessions is that unlike a common variable, whether it is superglobal or not, it will always be available, even on other pages of your application, even after the user gives F5 or even closes the tab and comes back after (closing the browser tab is different than closing the browser).

This magic works in a logical way, after all, there is no magic. For the sake of awareness, I will explain how this happens.

Brief explanation of how Sesssions work in PHP

When you start a Session with the command session_start(), PHP by default creates a file (this can be changed if you want) and that file will receive a random name. Inside this file, PHP stores a string with all information stored in the variable $_SESSION, so, when reloading the page, it goes after this file and brings back the data that is in it back. To make it work, it creates a cookie in the visitor’s browser and this cookie stores the session ID, so if the visitor has the cookies disabled it will not work. With the session ID, PHP does not generate another ID, it simply goes after the existing session data for that ID.

Of course this is a very basic explanation and does not cover everything that could be addressed. As I said, it is worth researching on the subject. Even, Sessions are a nearly mandatory feature for systems that need the user to be able to log in.

Solution to the case

<?php

session_start();

/* se enviar a foto, insere o nome da foto no banco de dados */
            if (move_uploaded_file($tmp, $pasta . $nome_atual)) {
                $_SESSION['imageUrl'] = $pasta . $nome_atual;
                mysql_query("INSERT INTO fotos (foto) VALUES (".$nome_atual.")");
                echo "<img src='fotos/".$nome_atual."' id='previsualizar' class='img-responsive'>"; //imprime a foto na tela
                echo "'http://audiosonic.com.br/novo/fotos/".$nome_atual."'";
            } else {
                echo "Falha ao enviar";
            }
        } else {
            echo "A imagem deve ser de no máximo 1MB";
        }
    } else {
        echo "Somente são aceitos arquivos do tipo Imagem";
    }
} else {
    echo "Selecione uma imagem";
    exit;
}

On the.php matricula page, only use the variable as follows, when convenient:

<?php

    session_start();

    echo "O caminho da imagem é {$_SESSION['imageUrl']}";

Remembering that you do not need to obligatorily put this path in an input. If it is not mandatory for the client to view the path, you can leave it only in the $_SESSION variable and use it only in PHP to register.

Tip: always use PHP documentation, there they have tips for using all language resources, including tips on Sessions.

  • did not work very well, because when I open the frame relative to this upload, it already shows a filename, even before I load. It seems to me to be the previous file. When I upload the image, so that it appears to me in visualization, the code is as follows:

  • <script src="../js/jquery-1.7.2.min.js"></script>&#xA;<script src="http://malsup.github.com/jquery.form.js"></script>&#xA;<script type="text/javascript">&#xA; $(document).ready(function(){&#xA; $('#imagem').live('change',function(){&#xA; $('#visualizar').html('<img src="loading.gif" />');&#xA; /* Efetua o Upload sem dar refresh na pagina */ $('#formulario').ajaxForm({&#xA; target:'#visualizar' // o callback será no elemento com o id #visualizar&#xA; }).submit();&#xA; });&#xA; })&#xA;</script>

  • This last echo, I put on purpose, to have the full path of the image: echo "'http://audiosonic.com.br/novo/fotos/".$nome_atual."'"; Is it not easier to "mirror" this echo on the registration page?

  • http://imgur.com/d6cAYeO - Here I show you what is happening

  • You can solve this by giving an unset($_SESSION['imageurl']); after using the value of the variable on the matricula.php page

  • It’s not working. Where I can post the full code, so you can see?

Show 1 more comment

Browser other questions tagged

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