Help with Sessions :/
Results 1 to 15 of 15

Thread: Help with Sessions :/

  1. #1
    Junior Member
    Join Date
    Jan 2013
    Posts
    8

    Help with Sessions :/

    I have been following some tutorials on creating a php and mysql based login system. I have the basics down, however simply trying to echo out the user username when they are logged in and cant seem do it.

    When a user successfully logs in a session is creation with a value of 'authorised' this allows them to access the 'admin' page. This is where I would like to echo out their username. So I tried starting another session that stores their user name, this will be created the 'authorised' session is started i.e. when a user logs in. However trying to echo out either of those session on the admin page is proving impossible. i simply get an error stating "ndefined index: authorised in C:\wamp\www\Login\admin.php on line 27".

    I wonder if you can help.

    This is teh admin page, when the session 'athorised' is started they can access this page, this is where I want to echo out the username.

    Code:
    <?php
    require_once 'classes/loginClass.php';
    $login = new Login();
    
    $login->confirm_Member();
    ?>
    <!doctype html>
    <html>
    	<head>
    		<meta charset="utf-8">
            <meta name="viewport" content="width=device-width, maximum-scale=1.0, minimum-scale=1.0, initial-scale=1.0" />
    		<title>Admin</title>
            <link rel="stylesheet" type="text/css" href="css/admin_styles.css" />
            <link rel="stylesheet" type="text/css" href="css/admin_styles_large.css" />
            <link rel="stylesheet" type="text/css" media="only screen and (min-width:50px) and (max-width:500px)" href="css/admin_styles_small.css" />
            <link rel="stylesheet" type="text/css" media="only screen and (min-width:501px) and (max-width:800px)" href="css/admin_styles_medium.css" />
            <!--[if lt IE 9]>
    			<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    		<![endif]-->
    	</head>
    	<body>
    		<div class="page">
            
            	<header>
                	<div class="user_container">
                      <p>Username: Chris</p>
                      <?php echo $_SESSION['user']; ?>
                      <a href="login.php?status=loggedout">Log Out</a> 
                    </div>
                </header>
                
                <div class="widget_container">
                	<div class="widget_1"></div>
                    <div class="widget_2"></div>
                    <div class="widget_3"></div>
                    <div class="widget_4"></div>
                </div>
                
                <article>
                	
                </article>
                            
                <nav>
                	<a href="#">Dashboard</a>
                    <a href="#">Manage Users</a>
                    <a href="#">Manage Products</a>
                </nav>
                
                <footer>
                	© Web Assignment 2 - 2013
                </footer>
            
            
            </div>
    
    
    	</body>
    </html>
    And this is the class that logs them in:

    Code:
    <?php
    
    require 'mysqlClass.php';
    
    class Login {
    	
    	public $user = 'Test';
    	
    	function checkLogin($username, $password) {
    		
    			$mysql = new Mysql();
    			$check_credentials = $mysql->verify_username_and_password($username, md5($password));
    			
    			if($check_credentials) {
    				
    				$_SESSION['status'] = 'authorised';
                                    $_SESSION['user'] = $username;
    				header("location: admin.php");
    				
    			} else return "Please enter a correct username and password.";
    		
    	}
    	
    	function logOutUser() {
    		
    		if(isset($_SESSION['status'])) {
    			
    			unset($_SESSION['status']);
    			
    			if(isset($_COOKIE[session_name()])) {
    				
    				setcookie(session_name(), '', time() - 10000);
    				session_destroy();	
    				
    			}
    			
    		}
    		
    	}
    	
    	function confirm_Member() {
    		
    		session_start();
    		
    		if($_SESSION['status'] !='authorised') {
    			
    			header("location: login.php");	
    			
    		}
    		
    	}
    	
    }
    
    ?>

  2. #2
    Pna lbh ernq guvf¿
    Join Date
    Jul 2004
    Location
    Kansas City area
    Posts
    19,354
    Where do you call session_start()?

  3. #3
    Junior Member
    Join Date
    Jan 2013
    Posts
    8
    Quote Originally Posted by bradgrafelman View Post
    Where do you call session_start()?
    The session is started within the 'confirm_member()' function. I have tried starting it on the admin page with the same results.

  4. #4
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,776
    Quote Originally Posted by chinds
    "ndefined index: authorised in C:\wamp\www\Login\admin.php on line 27".
    Which is line 27? I don't see anywhere that you're trying to do anything with a session variable named "authorised" (i.e., $_SESSION['authorised']).

    © Web Assignment 2 - 2013
    That's a funny name. Web Assignment 2's parents must have had a weird sense of humour.
    Last edited by Weedpacket; 01-20-2013 at 03:44 PM.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  5. #5
    Junior Member
    Join Date
    Jan 2013
    Posts
    8
    Quote Originally Posted by Weedpacket View Post
    Which is line 27? I don't see anywhere that you're trying to do anything with a session variable named "authorised" (i.e., $_SESSION['authorised]).

    That's a funny name. Web Assignment 2's parents must have had a weird sense of humour.
    haha it is. This is an assignment for my UNi work, have to build a shopping cart, im trying to go the extra mile, byt including and admin system and using OOP methods.

    Sorry I changed the code when i entered it here, line 27 is this line in the 1st code block: <?php echo $_SESSION['user']; ?>

    I am trying to echo out the user session but it wasn't working so i tried to echo 'authorized' session. and got the same error.

  6. #6
    Senior Member
    Join Date
    Apr 2003
    Location
    Silver Lake
    Posts
    4,811
    You cannot ever refer to values in $_SESSION unless you have first called session_start. If you do, you are just wasting your time. You may want to reconsider where you call session_start -- perhaps before you define your class or in the constructor for Login.
    IMPORTANT: STOP using the mysql extension. Use mysqli or pdo instead.
    World War One happened 100 years ago. Visit Old Grey Horror for the agony and irony.

  7. #7
    Junior Member
    Join Date
    Jan 2013
    Posts
    8
    Quote Originally Posted by sneakyimp View Post
    You cannot ever refer to values in $_SESSION unless you have first called session_start. If you do, you are just wasting your time. You may want to reconsider where you call session_start -- perhaps before you define your class or in the constructor for Login.
    This worked perfectly. I put the session_start() in the log in constructor like you said, and it works perfectly Thanks. I just didn't want to move things around in case I broke it somehow

  8. #8
    Senior Member
    Join Date
    Apr 2003
    Location
    Silver Lake
    Posts
    4,811
    Quote Originally Posted by chinds View Post
    This worked perfectly. I put the session_start() in the log in constructor like you said, and it works perfectly Thanks. I just didn't want to move things around in case I broke it somehow
    Sounds like it was broken to start with
    IMPORTANT: STOP using the mysql extension. Use mysqli or pdo instead.
    World War One happened 100 years ago. Visit Old Grey Horror for the agony and irony.

  9. #9
    Junior Member
    Join Date
    Jan 2013
    Posts
    8
    Quote Originally Posted by sneakyimp View Post
    Sounds like it was broken to start with
    Well this part wasn't in the tutorial, i wanted to add more bits myself afterwards i.e. the displaying of the logged in users user name etc. Is there a limit to how many session i shoud start? Not looking to use loads just curious as t how many i can use.

  10. #10
    Senior Member
    Join Date
    Apr 2003
    Location
    Silver Lake
    Posts
    4,811
    Quote Originally Posted by chinds View Post
    Well this part wasn't in the tutorial, i wanted to add more bits myself afterwards i.e. the displaying of the logged in users user name etc. Is there a limit to how many session i shoud start? Not looking to use loads just curious as t how many i can use.
    For any one user/visitor, there should be only one session -- their session. As for how many sessions your server can handle (e.g., how many users) that would depend on a lot of things.

    If you want to store more than one value in session, this is entirely feasible. Just assign a new value in $_SESSION, like $_SESSION["username"] or $_SESSION["userid"]. You could define quite a few this way, but I usually define just a couple of items and then use the userid to fetch their information from the database. If you have a lot of traffic, I understand that sessions can become a bottleneck because they are written to and read from disk as tiny files. You can rely on things like Memcache as session handlers which stores things in memory instead of on disk. Offhand, I'm not familiar with how to do this.
    IMPORTANT: STOP using the mysql extension. Use mysqli or pdo instead.
    World War One happened 100 years ago. Visit Old Grey Horror for the agony and irony.

  11. #11
    Junior Member
    Join Date
    Jan 2013
    Posts
    8
    Quote Originally Posted by sneakyimp View Post
    For any one user/visitor, there should be only one session -- their session. As for how many sessions your server can handle (e.g., how many users) that would depend on a lot of things.

    If you want to store more than one value in session, this is entirely feasible. Just assign a new value in $_SESSION, like $_SESSION["username"] or $_SESSION["userid"]. You could define quite a few this way, but I usually define just a couple of items and then use the userid to fetch their information from the database. If you have a lot of traffic, I understand that sessions can become a bottleneck because they are written to and read from disk as tiny files. You can rely on things like Memcache as session handlers which stores things in memory instead of on disk. Offhand, I'm not familiar with how to do this.
    I see, So how I have done it so far it not good practice then? I have one session that is set to authorised when the login credentials are confirmed, and then I another session that simply holds the username of the logged in user.

  12. #12
    Senior Member
    Join Date
    Apr 2003
    Location
    Silver Lake
    Posts
    4,811
    Quote Originally Posted by chinds View Post
    I see, So how I have done it so far it not good practice then? I have one session that is set to authorised when the login credentials are confirmed, and then I another session that simply holds the username of the logged in user.
    It looks fairly good to me. There's nothing wrong with storing a couple of values in a session -- I think we are having a bit of a terminology problem. You are not setting "another session" because your visitor has only one session and its contents are stored in $_SESSION. $_SESSION is a superglobal array and you may assign multiple values in there if you like. Each value is identified by its associative key -- i.e., the alphanumeric word you use to name it. There's nothing wrong with storing a few elements in your $_SESSION array for a given user. If you start cramming everything under the sun into it, you are probably doing something wrong. Two elements is totally normal, although I would probably store a userid.
    IMPORTANT: STOP using the mysql extension. Use mysqli or pdo instead.
    World War One happened 100 years ago. Visit Old Grey Horror for the agony and irony.

  13. #13
    Junior Member
    Join Date
    Jan 2013
    Posts
    8
    Hi again

    Just wondering if you could help me with another problem.

    The current script only looks for the username and password from the database, however I also want to return the permissions value for each user. this is either 0 or 1.

    Just wondering how to do that with the way this login function has been written, i simply want to get the permissions value for the logged in user and store it in a session. everything I have tried so far breaks the login script.

    This is the current login script:

    PHP Code:
    <?php

    require_once('includes/constants.php');

    class 
    Mysql {
        
        private 
    $conn;
        
        function 
    __construct() {
            
            
    $this->conn = new mysqli(DB_SERVERDB_USERDB_PASSWORDDB_NAME) or die ('There was a problem connecting to the database.');    
            
        }
        
        function 
    verify_username_and_password($username$password) {    
            
            
    $query "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1";
            
            if (
    $stmt $this->conn->prepare($query)) {
                
                
    $stmt->bind_param('ss'$username$password);
                
    $stmt->execute();
                
                if(
    $stmt->fetch()) {
                    
    $_SESSION['permissions'] = 'permissions';
                    
    $stmt->close();
                    return 
    true;
                    
                    
                }
                
            }
        }        

    }


    ?>
    Last edited by bradgrafelman; 01-23-2013 at 10:07 AM. Reason: bbcode tags modified

  14. #14
    Junior Member
    Join Date
    Jan 2013
    Posts
    8
    Quote Originally Posted by chinds View Post
    Hi again

    Just wondering if you could help me with another problem.

    The current script only looks for the username and password from the database, however I also want to return the permissions value for each user. this is either 0 or 1.

    Just wondering how to do that with the way this login function has been written, i simply want to get the permissions value for the logged in user and store it in a session. everything I have tried so far breaks the login script.

    This is the current login script:
    Posted that code snippet wrong, sorry, this is the correct code:

    PHP Code:
    <?php

    require_once('includes/constants.php');

    class 
    Mysql {
        
        private 
    $conn;
        
        function 
    __construct() {
            
            
    $this->conn = new mysqli(DB_SERVERDB_USERDB_PASSWORDDB_NAME) or die ('There was a problem connecting to the database.');    
            
        }
        
        function 
    verify_username_and_password($username$password) {    
            
            
    $query "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1";
            
            if (
    $stmt $this->conn->prepare($query)) {
                
                
    $stmt->bind_param('ss'$username$password);
                
    $stmt->execute();
                
                if(
    $stmt->fetch()) {
                    
                    
    $stmt->close();
                    return 
    true;
                    
                    
                }
                
            }
        }        

    }


    ?>
    Last edited by bradgrafelman; 01-23-2013 at 10:06 AM. Reason: bbcode tags modified

  15. #15
    Pna lbh ernq guvf¿
    Join Date
    Jul 2004
    Location
    Kansas City area
    Posts
    19,354
    Few things:

    1. When posting PHP code, please use the board's [php]..[/php] bbcode tags as they make your code much easier to read and analyze.
    2. Stop using 'SELECT *' queries - 99% of the time, these are unnecessary, less efficient, and less descriptive than explicitly SELECT'ing the columns from which you actually need data.
    3. Once you fix the above issue, you can use mysqli_stmt::bind_result() to bind the 'permissions' column value to a variable when you fetch() the row.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •