PHP variable storage - $_SESSION x $_GET

Asked

Viewed 1,377 times

1

Hello friends. I have a question about best practices applied in development: What would be the best form of temporary storage of variables in an application? I have a PHP application where I can edit users, where I just click on the link and direct me to the editing page where the ID is recovered through the query string user.

http://www.app.com.br?usuario=23

Would this be the best way? Or would it be better to store it in a session variable? I appreciate the help!

  • 1

    As long as you don’t let me change the 23 for 24 and let me change other people’s settings no problem. Stackoverflow uses this, /edit/15089, the 15089 is my ID. If you are not logged in to my account will give error, this is precisely what should occur in your application, prevent other people change settings of other people.

  • 1

    Just like @Inkeliz said, you can save anywhere, although GET is mostly used for this type of situation.

1 answer

3


With $_GET you will only have access to the variable, in this with the case with value 23 in the service http://www.app.com.br?usuario=23, because in the http://www.app.com.br?usuario=24 you will no longer have your variable with the value 23, but yes 24.

That being said, to store a variable temporarily throughout your application, you should use Session or cookies.

In this case if you want to keep the value $_GET['usuario'] in a session, you do (this is a very basic way):

<?php
session_start();
$_SESSION['usuario'] = $_GET['usuario'];

Where you’ll have access to all the other pages, if you put it on top of all of them session_start().

But this doesn’t make much sense to me (from what I understand), because if the user then goes to the url http://www.app.com.br?usuario=24 , the variable $_SESSION['usuario'] now becomes the value 24 .

My tip, in case the user 23 cannot visualize http://www.app.com.br?usuario=24 is to save that id from login and check that page:

<?php
session_start();
if($_SESSION['usuario'] != $_GET['usuario']) {
    header('Location: OUTRA_PAG.php');
    die();
}

Browser other questions tagged

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