8 Replies - 2312 Views - Last Post: 24 September 2012 - 06:43 AM Rate Topic: -----

#1 Java Neil  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 140
  • Joined: 26-March 11

Remember User From Session

Posted 21 September 2012 - 12:48 PM

Hey everyone...I'm still very green to PHP and I'm trying to get my head around passing the session to the rest of the sites pages.

Here is my code...

 <?php
    require("connect.php");
	
    // At the top of the page we check to see whether the user is logged in or not
    if(empty($_SESSION['user']))
    {
        // If they are not, we redirect them to the login page.
        header("Location: ./");
        
        // Remember that this die statement is absolutely critical.  Without it,
        // people can view your members-only content without logging in.
        die("Redirecting to ./");
    }
	
	$_SESSION['username']="emily";
	
    $username=$_SESSION['username'];
	
    if(isset($_POST['submit']))
    {
        //get file attributes
        $name=$_FILES['myfile']['name'];
        $tmp_name=$_FILES['myfile']['tmp_name'];
        if($name)
        {
            //start upload process
            $location="avatars/$name";
            move_uploaded_file($tmp_name,$location);
            $query=mysql_query("UPDATE users SET imagelocation='$location' WHERE username='$username'");          
        }	
		
	}

 ?>


As you can see I can't figure out how to take "emily"; and replace it with the right session variable.

Any help would be great. Please go easy on me as I have been doing this for just a couple of weeks.

Is This A Good Question/Topic? 0
  • +

Replies To: Remember User From Session

#2 RudiVisser  Icon User is offline

  • .. does not guess solutions
  • member icon

Reputation: 1003
  • View blog
  • Posts: 3,562
  • Joined: 05-June 09

Re: Remember User From Session

Posted 21 September 2012 - 01:57 PM

View PostJava Neil, on 21 September 2012 - 08:48 PM, said:

As you can see I can't figure out how to take "emily"; and replace it with the right session variable.


Remove this line?
$_SESSION['username']="emily";


What's the actual problem? In one place you're using $_SESSION['user'] and then the next you use $_SESSION['username'], which is correct?
Was This Post Helpful? 0
  • +
  • -

#3 Java Neil  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 140
  • Joined: 26-March 11

Re: Remember User From Session

Posted 21 September 2012 - 02:47 PM

View PostRudiVisser, on 21 September 2012 - 03:57 PM, said:

View PostJava Neil, on 21 September 2012 - 08:48 PM, said:

As you can see I can't figure out how to take "emily"; and replace it with the right session variable.


Remove this line?
$_SESSION['username']="emily";


What's the actual problem? In one place you're using $_SESSION['user'] and then the next you use $_SESSION['username'], which is correct?


I see what you mean. Here is my login.php code...

<?php

    // connect to the database and start the session
    require("connect.php");
    
    // This variable will be used to re-display the user's username
    $submitted_username = '';
    
    // This if statement checks to determine whether the login form has been submitted
    if(!empty($_POST))
    {
        // This query retreives the user's information
        $query = "
            SELECT
                id,
                username,
                password,
                salt
            FROM users
            WHERE
                username = :username
        ";
        
        $query_params = array(
            ':username' => $_POST['username']
        );
        
        try
        {
            $stmt = $db->prepare($query);
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // display error
            die("Failed to run query: " . $ex->getMessage());
        }
        
        // successfully logged in or not.
        $login_ok = false;
        
        $row = $stmt->fetch();
        if($row)
        {
            // and comparing the hashed version already stored in the database.
            $check_password = hash('sha256', $_POST['password'] . $row['salt']);
            if($check_password === $row['password'])
            {
                // If they do, then we flip this to true
                $login_ok = true;
            }
        }
        
        // If the user logged in successfully, then we send them to the members page
        // Otherwise, we display a login failed message and show the login form again
        if($login_ok)
        {
            // removing the salt and password values
            unset($row['salt']);
            unset($row['password']);
            
            // This stores the user's data into the session
            $_SESSION['user'] = $row;
            
            // Redirect the user to the members page.
            header("Location: dashboard.php");
            die("Redirecting to: dashboard.php");
        }
        else
        {            
            // Show them their username again
            $submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
        }
    }
?>


and my updated index.php

 <?php
    require("connect.php");
	
    // At the top of the page we check to see whether the user is logged in or not
    if(empty($_SESSION['user']))
    {
        // If they are not, we redirect them to the login page.
        header("Location: ./");
        
        // Remember that this die statement is absolutely critical.  Without it,
        // people can view your members-only content without logging in.
        die("Redirecting to ./");
    }

    $username = $_SESSION['user'];
	
    if(isset($_POST['submit']))
    {
        //get file attributes
        $name=$_FILES['myfile']['name'];
        $tmp_name=$_FILES['myfile']['tmp_name'];
        if($name)
        {
            //start upload process
            $location="avatars/$name";
            move_uploaded_file($tmp_name,$location);
            $query=mysql_query("UPDATE users SET imagelocation = '$location' WHERE username = '$username'");          
        }	
		
	}
 ?>


The only problem is it's not changing anything in the database when the original code did at least work for the user "emily". The other problem is this code breaks the look of the page, misalignment elements on the page.

Any ideas?

This post has been edited by Java Neil: 21 September 2012 - 02:48 PM

Was This Post Helpful? 0
  • +
  • -

#4 Java Neil  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 140
  • Joined: 26-March 11

Re: Remember User From Session

Posted 22 September 2012 - 09:00 PM

Can no one help me out with this?
Was This Post Helpful? 0
  • +
  • -

#5 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3718
  • View blog
  • Posts: 5,986
  • Joined: 08-June 10

Re: Remember User From Session

Posted 22 September 2012 - 09:40 PM

In your login code you set the $_SESSION["user"] element to an array containing both the id and the username.

But in your update code you do this:
$username = $_SESSION['user'];


Now the $username variable would be assigned to an array containing the id and the username values. So when you proceed to use that variable in your SQL query, PHP would not fill it in with the username, but instead just use the string "Array".

It should also print a notice about that, if your error reporting settings were set to show such things. (Which they should be in a development environment!)
Was This Post Helpful? 1
  • +
  • -

#6 Java Neil  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 140
  • Joined: 26-March 11

Re: Remember User From Session

Posted 23 September 2012 - 06:06 AM

I understand the problem.What I don't understand is how to fix it where the current 'user' is passed to the variable $username;? Once again, I am bran-new to this.
Was This Post Helpful? 0
  • +
  • -

#7 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3718
  • View blog
  • Posts: 5,986
  • Joined: 08-June 10

Re: Remember User From Session

Posted 23 September 2012 - 06:17 AM

You need to fetch the username element of the $_SESSION['user'] array.
$username = $_SESSION['user']['username'];


Even though it is in a session element, the 'user' element is just a normal array and can be used as such.

Alternatively, you could just use the $_SESSION['user']['username'] element in your query, instead of copying it to a variable first. There really is no need to copy variables like that, even when dealing with session or request data. You can just as well use it from it's original source:
$sql = "UPDATE users SET stuff = 'more stuff'
        WHERE username = '{$_SESSION["user"]["username"]}'";



Of course, what you should be doing is escaping the data first. When using the old MySQL API functions, you should always escape all data you are intending to put into it, unless you can be 110% sure it is safe. (Like if it's been type-cast to an int.) - You can do that with the mysql_real_escape_string() function.
$username = mysql_real_escape_string($_SESSION["user"]["username"]);

$sql = "UPDATE users SET stuff = 'more stuff'
        WHERE username = '{$username}'";



What would be even more safe would be to use MySQLi or PDO, who both allow the more modern method of using stored procedures, which eliminates the need for escaping. You should definitely look into that.
Was This Post Helpful? 1
  • +
  • -

#8 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3525
  • View blog
  • Posts: 10,170
  • Joined: 08-June 10

Re: Remember User From Session

Posted 23 September 2012 - 10:22 PM

side question, did you start your session at all?
Was This Post Helpful? 0
  • +
  • -

#9 Java Neil  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 140
  • Joined: 26-March 11

Re: Remember User From Session

Posted 24 September 2012 - 06:43 AM

Thanks guys!

$username = $_SESSION['user']['username'];


This did the trick.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1