passing a variable from page to another page

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • RomeoX
    New Member
    • Jan 2010
    • 25

    passing a variable from page to another page

    Hi there, I would like to ask a question about how to pass a variable from page to page. For example, I have my first page for login and used a session with cookie and after submitting successfully and redirect my page to another page I want show statement like Hello Smith or Welcome Smith, and it doesn't work properly. Anyone knows the soulution would be appreciated. Thanks

    Code:
    <?php
    if (loggedin())
    	{
    	header("Location: redirectpage.php");
    	exit();
    	}
    if ($_POST["login"])
    {
    	global $username;
    	$username = $_POST['username'];
    	$password = $_POST['password'];
    	$rememberme = $_POST['rememberme'];
    
    
    	if($username&&$password)
    	{
    
    	$login = mysql_query("SELECT * FROM usersystem where username='$username'");
    	while ($row = mysql_fetch_assoc($login))
    	{
    		$db_password = $row['password'];
    		if($password==$db_password)
    		
    	else
    		setcookie("username", $username, time()+7200);
    		else if ($rememberme=="")
    		$_SESSION['logged_in']== $username;
    		$_SESSION['username'] =$_POST['username'];
    
    //userarea.php
    		header("Location: redirectpage.php");
    		exit();
    
    		}
    
    	}
    
    	}
    	else
    	die("Please enter a username and password");
    
    }
    ?>
    This is the code for the second page that I want the name of the user to show up.

    Code:
    <?php
    session_start();
    
    $username = $_SESSION['username'];
    
    echo $_SESSION['username'];
    
    
    
    echo "Hello ". $username ;
    ?>
    So what's wrong with my code. Thanks again
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hey.

    There is a syntax error there on line 24. The if, else and else if statements don't match up.

    It is generally best to always use brackets with if statements, even if they only execute on line of code. It helps to avoid problems like these.

    [code=php]// Avoid this:
    if(true == true)
    echo "It is true!";
    echo "A completely unrelated line...";

    // Rather do this:
    if(true == true) {
    echo "It is true!";
    }
    echo "A completely unrelated line...";[/code]
    There are a couple of extra charachters required, but it makes it a whole lot clearer to read, especially if your indentations are sloppy.

    Comment

    • RomeoX
      New Member
      • Jan 2010
      • 25

      #3
      Actually the I wrote the code and I knew that it's wrong because I picked up just for example of how to pass session variable to another page and I was asking about this. Anyway thanks a lot of passing my thread.

      Comment

      • johny10151981
        Top Contributor
        • Jan 2010
        • 1059

        #4
        you can try this

        Code:
        redirectpage.php?user_name=johny&user_age=100
        then in redirectpage.ph p usign $_GET you can have the data. i.e
        Code:
        $name=$_GET[user_name];
        $age=$_GET[user_age];
        Regards
        johny

        Comment

        • RomeoX
          New Member
          • Jan 2010
          • 25

          #5
          Thanks for reply I'm really thankful to u

          by the way, actually the first code that I submitted in the first topic that will be in the login screen and I can't pass the login and password in the tool bar of the browser so I'm using POST instead of get because it's much secure. I tried your code but I used POST but couldn't get the username.

          So what should I do?

          Comment

          • johny10151981
            Top Contributor
            • Jan 2010
            • 1059

            #6
            I dont know what is your plan.

            But if you try session it may help. After user log in you can save the user_name and Password using session. your php page will be able to use these session anytime if session is valide. Cookie is a solution but a very easy solution to destroy the security.

            Regards,
            Johny

            Comment

            • Atli
              Recognized Expert Expert
              • Nov 2006
              • 5062

              #7
              OK, to answer the original question: there are a couple of methods you can use to pass things between pages.
              1. Sessions
                These are the most secure of the methods, because the actual data is stored on the server, while only a session identifier is passed to the browser (usually as a cookie). Any page on the domain can then activate the session and use the data, given that the cookie is not destroyed. This is highly recommended for storing sensitive data, such as user login information.
              2. Cookies
                Less secure and reliable than sessions, but more long-term. Whereas a session is destroyed every time the browser is closed (by default), a cookie can remain indefinitely. It is usually best not to use these to store sensitive info, only info that would not be a security threat if it fell into the wrong hands.
              3. GET parameters
                Adding variables to the URL can serve as a (very) short-term method of passing data between pages. This is usually reserved for things like passing paging information via navigation links. In general, if the same piece of data needs to be passed to more than a couple of pages, a session or a cookie is a better choice.

              There are a few more possible methods, but they are generally so situational and questionable that they are hardly worth mentioning.

              For the purposes of storing user login data, a session would be ideal. Putting the user name and ID into the session is pretty standard.

              This is a pretty generic example of how that would be done.
              [code=php]<?php
              // Make sure the login info was passed
              if(isset($_POST['name'], $_POST['password']))
              {
              // Fetch the user name from POST.
              // Note the use of the mysql_real_esca pe_string function.
              // It should ALWAYS be used on data that is to be
              // inserted into a SQL query.
              $name = mysql_real_esca pe_string($_POS T['name']);

              // Fetch the password. Note that I hash() the password.
              // This ensures the password is secure, even if
              // the database itself is comprimized. You should
              // ALWAYS hash passwords, and never store them as
              // plain text. The above rule about the escape_string
              // function does not apply here, as a hash is always
              // safe to put into a SQL query.
              $pwd_hash = hash('sha1', $_POST['password']);

              // Verify that the login info is valid.
              // It is better to fetch the user info based on
              // the username and the password, rather than to pass
              // it only the username and verify the password with
              // PHP. This way, if the login is invalid, the real
              // password never enters your PHP code, making it more
              // secure.
              $sql = "SELECT `id` FROM `user`
              WHERE (`name` = '{$name}')
              AND (`password` = '{$pwd_hash}')" ;

              $result = mysql_query($sq l) or trigger_error(m ysql_error(), E_ERROR);

              // If a single row was returned, the user info is
              // valid. If more than a single row was returned,
              // odds are that something went rong, or that your
              // code has somehow been comprimized. This is why
              // you should validate ONLY if a single row is returned.
              if(mysql_num_ro ws($sql) == 1)
              {
              $row = mysql_fetch_ass oc($sql);

              // Here we start the session and enter the
              // user info into it. Note that session values
              // can be arrays themselves, so that you can group
              // similar elements together, like I do here.
              session_start() ;
              $_SESSION['user']['id'] = $row['id'];
              $_SESSION['user']['name'] = $name;
              }
              else
              {
              echo "Login failed. Please try again!";
              }
              }
              else
              {
              echo "Username and/or password were not passed.";
              }

              ?>[/code]

              You can then verify a user as logged in on other pages by doing something like:
              [code=php]<?php
              session_start() ;

              // Check if the user session element exists.
              // If it does, we can assume the client has
              // already logged in. If not, we can not.
              if(!isset($_SES SION['user']))
              {
              // Redirect back to the user login page.
              header('Locatio n: login.php');
              exit;
              }

              // Display the rest of the user-secure content.
              echo "Welcome, {$_SESSION['user']['name']}!";
              ?>[/code]

              Originally posted by johny10151981
              After user log in you can save the user_name and Password using session.
              You should NEVER store the password anywhere, especially in it's plain-text form. If you absolutely can not avoid it, you should at least hash it before doing so. Passwords are one of the more sensitive pieces of info your application will ever handle and they should be used as little as possible.

              I mean, consider if a malicious user managed to inject a PHP script to your server. It would be fairly easy for him to hijack sessions and view all the session data, including the password. Limiting this to usernames and IDs makes this sort of breach a lot less damaging.

              Comment

              • kovik
                Recognized Expert Top Contributor
                • Jun 2007
                • 1044

                #8
                I disagree. The password should be stored in its hashed form. What if two users are logged into the same account at once? What if the valid user knew that someone knows his password and he needs to change it before the other user harms his account? He would then change his password. If the password was re-authenticated on every page request (as I believe it should be), then the false user would be essentially logged out.

                Comment

                • Atli
                  Recognized Expert Expert
                  • Nov 2006
                  • 5062

                  #9
                  That's an extremely rare scenario, to be honest, and preventing it hardly takes priority over the security of all passwords being used. Even in it's hashed form, in the hands of a malicious user a password would be a major security concern.

                  But if this scenario is of great concern to you, a far more sensible method - surely - would be to add a "modified" timestamp to the user account that would be updated with the password. The value of that timestamp at the time when a user is logged in would then be stored with the session and checked on every reload.

                  There is rarely a situation where you need to store the password anywhere - outside normal login and account maintenance - and you really should avoid it wherever possible, for obvious security reasons. That is what I would generally recommend, in any case.

                  Comment

                  • johny10151981
                    Top Contributor
                    • Jan 2010
                    • 1059

                    #10
                    Hi Atli,
                    You have comment out one of my line. Actually I am explaining it. I did tell to store data using SESSION but I didnt mean to store in storage device like hard disk. If I am not wrong session data get stored in the server and in the RAM. My understanding says Session stores run time data.

                    I also strongly disagree password in server's storage device.

                    Regards,
                    Johny

                    Comment

                    • kovik
                      Recognized Expert Top Contributor
                      • Jun 2007
                      • 1044

                      #11
                      ... Session data is stored on the HDD. Computers don't really "store" anything on the RAM. The contents of the RAM have the potential to be ever changing.

                      And in regards to the password, what if someone gained access to the session data? I think the risk of them simply guessing a user ID and gaining access to that account is less secure than them having to know the user name and the hashed password from the database.

                      Comment

                      • Atli
                        Recognized Expert Expert
                        • Nov 2006
                        • 5062

                        #12
                        You have comment out one of my line. Actually I am explaining it. I did tell to store data using SESSION but I didnt mean to store in storage device like hard disk. If I am not wrong session data get stored in the server and in the RAM. My understanding says Session stores run time data.
                        Session data is stored on the server's HDD by default. It can be configure to store it in shared memory (RAM), or even using a custom save handler, but that is usually not the case.

                        Anyways, it doesn't matter. If the server is secure, either method works fine. Your PHP application will never know the difference. - Your server's performance may vary, but that's irrelevant to our discussion.

                        Originally posted by kovik
                        And in regards to the password, what if someone gained access to the session data? I think the risk of them simply guessing a user ID and gaining access to that account is less secure than them having to know the user name and the hashed password from the database.
                        I don't follow. How would guessing a user ID allow them access to an account?
                        (I'm getting close to 28 hours without sleep, so forgive me if I am missing something obvious xD)

                        Comment

                        • kovik
                          Recognized Expert Top Contributor
                          • Jun 2007
                          • 1044

                          #13
                          Originally posted by Atli
                          I don't follow. How would guessing a user ID allow them access to an account?
                          (I'm getting close to 28 hours without sleep, so forgive me if I am missing something obvious xD)
                          In the event that they have access to the session data. It is more likely that this would be a trusted user that you had given your server password, but this user could potentially log in to any account that they wanted without needing to know their password. They would simply alter the user ID in their session data.

                          Comment

                          • Atli
                            Recognized Expert Expert
                            • Nov 2006
                            • 5062

                            #14
                            Originally posted by kovik
                            In the event that they have access to the session data. It is more likely that this would be a trusted user that you had given your server password, but this user could potentially log in to any account that they wanted without needing to know their password. They would simply alter the user ID in their session data.
                            If we are indeed talking about a trusted user, I would assume that trust covered not logging into other user's accounts. And if it were not a trusted user, and he manage to get your server passwords or hack into the server, the risk of him access random user accounts should be the least of your worries.

                            In any case, having the password in the session wouldn't really prevent this either. Any open session, or one that has not yet been cleaned up, would also be vulnerable. He would just have to copy the session as-is.

                            And if you implemented the "modified" timestamp, as I suggested before, guessing the ID of a user would not work. He would have to guess that exact timestamp as well. (Although this would of course not protect users with open/garbage sessions, no more than with the passwords.)

                            Comment

                            • kovik
                              Recognized Expert Top Contributor
                              • Jun 2007
                              • 1044

                              #15
                              Security is such a nitpicky subject, ain't it? :P

                              Comment

                              Working...