1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Session Won't Start?

Discussion in 'PHP' started by phplduser, Mar 25, 2020.

  1. #1
    Hi all,

    I'm trying to code a login script but the new user session won't start and just returns to login page -

    <?php
    session_start();
    
    require_once "db.php";
    
    if(isset($_SESSION['user_id'])!="") {
        header("Location: dashboard.php");
    }
    
    if (isset($_POST['login'])) {
        $email = mysqli_real_escape_string($conn, $_POST['email']);
        $password = mysqli_real_escape_string($conn, $_POST['password']);
    
        if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
            $email_error = "Please Enter Valid Email ID";
        }
        if(strlen($password) < 6) {
            $password_error = "Password must be minimum of 6 characters";
        } 
    
        $result = mysqli_query($conn, "SELECT * FROM users WHERE email = '" . $email. "' and pass = '" . md5($password). "'");
       if(!empty($result)){
            if ($row = mysqli_fetch_array($result)) {
                $_SESSION['user_id'] = $row['uid'];
                $_SESSION['user_name'] = $row['name'];
                $_SESSION['user_email'] = $row['email'];
                $_SESSION['user_mobile'] = $row['mobile'];
                header("Location: dashboard.php");
            }
        }else {
            $error_message = "Incorrect Email or Password!!!";
        }
    }
    ?>
    Code (markup):
    Any idea's (i'm a novice!)

    Best Regards
    Justin
     
    phplduser, Mar 25, 2020 IP
  2. wmtips

    wmtips Well-Known Member

    Messages:
    598
    Likes Received:
    70
    Best Answers:
    1
    Trophy Points:
    150
    #2
    The strange code is here:
    if(isset($_SESSION['user_id'])!="") {
        header("Location: dashboard.php");
    }
    PHP:
    isset returns boolean TRUE or FALSE and you are comparing result to a string.
    Maybe it should be
    if(isset($_SESSION['user_id']))
        header("Location: dashboard.php");
    
    PHP:
     
    wmtips, Mar 25, 2020 IP
  3. wmtips

    wmtips Well-Known Member

    Messages:
    598
    Likes Received:
    70
    Best Answers:
    1
    Trophy Points:
    150
    #3
    Also you need to stop script output by calling die() or exit() after the header("Location...") because returned content can prevent the redirect.
     
    wmtips, Mar 25, 2020 IP
    phplduser likes this.
  4. Ian Haney

    Ian Haney Banned

    Messages:
    131
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    78
    #4
    If it helps, this is what mine looks like @phplduser

    <?php
    
    // Initialize the session
    session_start();
    // Check if the user is already logged in, if yes then redirect him to welcome page
    if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true)  {
        header("location: user-account.php?user=$username");
        exit;
    }
    // Include config file
    require_once "registerconfig.php";
    // Define variables and initialize with empty values
    $username = $password = "";
    $customername = $username = "";
    $customeremail = $username = "";
    $username_err = $password_err = "";
    // Processing form data when form is submitted
    if($_SERVER["REQUEST_METHOD"] == "POST"){
        // Check if username is empty
        if(empty(trim($_POST["user_name"]))){
            $username_err = "Please enter username.";
        } else{
            $username = trim($_POST["user_name"]);
        }
       
        // Check if password is empty
        if(empty(trim($_POST["user_pass"]))){
            $password_err = "Please enter your password.";
        } else{
            $password = trim($_POST["user_pass"]);
        }
       
        // Validate credentials
        if(empty($username_err) && empty($password_err)){
            // Prepare a select statement
            $sql = "SELECT user_id, user_name, user_pass, customer_name, customer_email FROM users WHERE user_name = ?";
           
            if($stmt = mysqli_prepare($link, $sql)){
                // Bind variables to the prepared statement as parameters
                mysqli_stmt_bind_param($stmt, "s", $param_username);
               
                // Set parameters
                $param_username = $username;
                $param_customername = $customername;
                $param_customeremail = $customeremail;
               
                // Attempt to execute the prepared statement
                if(mysqli_stmt_execute($stmt)){
                    // Store result
                    mysqli_stmt_store_result($stmt);
                   
                    // Check if username exists, if yes then verify password
                    if(mysqli_stmt_num_rows($stmt) == 1){                   
                        // Bind result variables
                        mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password, $customername, $customeremail);
                        if(mysqli_stmt_fetch($stmt)){
                            if(password_verify($password, $hashed_password)){
                                // Password is correct, so start a new session
                                session_start();
                               
                                // Store data in session variables
                                $_SESSION["loggedin"] = true;
                                $_SESSION["user_id"] = $id;
                                $_SESSION["user_name"] = $username;
                                $_SESSION["customer_name"] = $customername;
                                $_SESSION["customer_email"] = $customeremail;
                               
                                if($_POST["remember"]==true) {
                                    $hash=md5($id);
                                    setcookie ("token",$hash,time()+ (365 * 24 * 60 * 60),'/');
                                    $hstmt = mysqli_prepare($link,"UPDATE users SET remember = ? WHERE user_id = ?");
                                    mysqli_stmt_bind_param($hstmt,"si", $hash, $id);
                                    mysqli_stmt_execute($hstmt);
                                   
                                           
                                } else {
                                    if(isset($_COOKIE["token"])) {
                                        setcookie ("token","");
                                            $hstmt = mysqli_prepare($link,"UPDATE users SET remember = '' WHERE user_id = ?");
                                            mysqli_stmt_bind_param($hstmt,"i", $id);
                                            mysqli_stmt_execute($hstmt);
                                    }
                               
                                }
                               
                                // Redirect user to welcome page
                                header("location: user-account.php?user_name=$username");                           
                            } else{                           
                                // Display an error message if password is not valid
                                $password_err = "The password does is incorrect for the username entered.";
                            }
                        }
                    } else{
                        // Display an error message if username doesn't exist
                        $username_err = "No account found with that username.";
                    }
                } else{
                    echo "Oops! Something went wrong. Please try again later.";
                }
            }
           
            // Close statement
            mysqli_stmt_close($stmt);
        }
       
        // Close connection
        mysqli_close($link);
    }
    ?>
    PHP:
     
    Ian Haney, Mar 25, 2020 IP
    phplduser likes this.
  5. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #5
    ON top of correcting the broken check on isset -- which is indeed where most of your problem likely lies -- It might also help if you used mysqli PROPERLY.. See this?

        $email = mysqli_real_escape_string($conn, $_POST['email']);
        $password = mysqli_real_escape_string($conn, $_POST['password']);
    
        if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
            $email_error = "Please Enter Valid Email ID";
        }
        if(strlen($password) < 6) {
            $password_error = "Password must be minimum of 6 characters";
        } 
    
        $result = mysqli_query($conn, "SELECT * FROM users WHERE email = '" . $email. "' and pass = '" . md5($password). "'");
    
    Code (markup):
    100% hurr-durrz and completely defeats the reason the old mysql_ functions were abandoned... and why you shouldn't be building queries that way any time after 2005! Do NOT slop variables into the query string, that's why we have prepare->execute. If you have something like an invalid password length that should be handled BEFORE you even get as far as the query.

    Don't even get me started about this header redirection BS. Just include() the correct page. Again, this is where anything but the "one index to rule them all" approach is incompetent trash.

    
    <?php
    
    // I'd put this in your index.php and/or every user callable file.
    
    session_start();
    session_regenerate_id();
    
    require_once('db.php');
    
    $loginErrors = [];
    
    if (isset($_POST['login']) {
    	if (
    		empty($_POST['email']) ||
    		empty($_POST['password'])
    	) {
    		$loginErrors['login'] = 'You failed to provide an E-Mail or password';
    	} else {
    		if (filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {
    			$loginErrors['email'] = 'Invalid E-mail';
    		}
    		if (strlen($_POST['password']) < 6) {
    			$loginErrors['password'] = "Password must be minimum of 6 characters";
    		} 
    		if (!$loginErrors) { // remember, empty is loose false
    			$pass = hash('sha512', $password);
    			$stmt = $conn->prepare('
    				SELECT uid, name, email, mobile
    				FROM users
    				WHERE email = ?
    				and pass = ?
    			');
    			$stmt->bindParam('ss', $_POST['email'], $pass);
    			$stmt->execute();
    			$stmt->bind_result(
    				$_SESSION['user_id'],
    				$_SESSION['user_name'],
    				$_SESSION['user_email'],
    				$_SESSION['user_mobile']
    			);
    			if (!$stmt->fetch()) {
    				$loginErrors['login'] = 'Invalid username or password';
    			}
    		}
    	}
    } else {
    	// handle that no login was sent here
    }
    
    if ($loginErrors) {
    	// re-send form using $loginErrors to pass what errors occurred.
    } else {
    	// handle successful login here
    }
    
    Code (markup):
    Notice using sha512 instead of the pointless and rainbow-tabled MD5, the proper use of prepare/execute (I think, I'm more of a PDO than mysqli guy), ditching the derpy function based version of mysqli for the object one, since we have prepare/execute we don't need that dumbass real_escape_string trash (again, this isn't 2005), how we can bind straight to $_SESSION skipping a slew of "variables for nothing", etc, etc, etc.

    Side note, you may want to ditch the outdated mysqli_ garbage for PDO.
     
    deathshadow, Mar 25, 2020 IP
    phplduser likes this.
  6. phplduser

    phplduser Member

    Messages:
    297
    Likes Received:
    28
    Best Answers:
    0
    Trophy Points:
    43
    #6
    Hi All,

    Thank you, This helps alot.

    Have a great day!
    Justin
     
    phplduser, Mar 27, 2020 IP