How to keep user info in Session

Discussion in 'PHP' started by baris22, Aug 10, 2009.

  1. #1
    I am trying to make a login system for my site. I am kind of stucked. How can i save wheither the user logged in or not to session?

    This is my code

    
    <?php 
    		
    		mysql_connect("localhost", "user", "password") or die(mysql_error());
    		mysql_select_db("DBName") or die(mysql_error());
    			
    		if(isset($_POST['email']) && isset($_POST['password'])){
    			// Verify
    			$email = mysql_escape_string($_POST['email']);
    			$password = md5($_POST['password']);
    			
    			$gUser = mysql_query("SELECT * FROM users WHERE email='".$email."' AND password='".$password."' LIMIT 1") or die(mysql_error());
    			$verify = mysql_num_rows($gUser);
    			
    			if($verify > 0){
    			
    				echo '<h2>Login Complete</h2>
    				      <p>Click here to download our program</p>';
    			}else{
    				echo '<h2>Login Failed</h2>
    				      <p>Sorry your login credentials are incorrect.';
    			}
    		}else{
    		?>
    		<h2>Login</h2>
    		<p>Please enter your login credentials to get access to the download area</p>
    		
    		<form method="post" action="">
    			<fieldset>
    				<label for="email">Email:</label><input type="text" name="email" value="" />
    				<label for="password">Password:</label><input type="text" name="password" value="" />
    				<input type="submit" value="Login" />
    			</fieldset>
    		</form>
    		
    		<?php
    		}
    		?>
    
    
    PHP:
     
    baris22, Aug 10, 2009 IP
  2. dannywwww

    dannywwww Well-Known Member

    Messages:
    804
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    110
    #2
    Do you have some kind of user id field in the users table?

    you can use a mysql_fetch_array(), to get the userid from the query already, then store it in a session eg.
    $_SESSION['userid'] = $row['userid'];

    then, use the isset() function to check if the user is logged in. And just use the unset() function for the user logout part.
     
    dannywwww, Aug 10, 2009 IP
  3. baris22

    baris22 Active Member

    Messages:
    543
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    60
    #3
    Thank you. It is sorted. I did not think it would be that easy
     
    baris22, Aug 10, 2009 IP