skip to Main Content

I have a PHP website. I want to create a signup-login process. I have completed the signup process but when I log in I need to do some verification only after that it should redirect to the page where I want it to redirect.

I have the following pages:

index.php,
login.php,
handleLogin.php, and
blog.php

I want to make the validation like this when we log in from index.php or any other page but not from the blog page, there will be a link named login in the header, and when someone wants to click from there the login page will appear and after logged in, it will redirect to index.php. But when we click from the comment on the blog page, firstly it will redirect to the login page and when logged in is successful it will redirect to the same blog page.

Following are the HTML codes of the login page:

<div class="login_form">
    <form action="handleLogin.php" method="POST" class="login">
        <div class="mb-3">
            <label for="exampleInputEmail1" class="form-label">Email address</label>
            <input type="email" name="vEmail" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
        </div>

        <div class="mb-3">
            <label for="exampleInputPassword1" class="form-label">Password</label>
            <input type="password" name="vPass" class="form-control" id="exampleInputPassword1">
            <div id="emailHelp" class="form-text">We'll never share your email & password with anyone else.</div>
        </div>

        <button type="submit" class="btn btn-primary mb-3">Log in</button>

        <div class="create_account">
            <label for="exampleInputEmail1" class="form-label">Don’t have an account? <a href="signup.php"
                    class="signup_link">Sign up</a></label>
        </div>
    </form>
</div>

Following are the HTML codes of the handleLogin page:

<?php
// session_start ();
// $bid = $_GET['b'];
$bid = '0';

$showAlert = "false";
if($_SERVER["REQUEST_METHOD"]=="POST"){
    include '../partials/_dbconnect.php';

    $viewerEmail = $_POST['vEmail'];
    $viewerPass = $_POST['vPass'];

    $loginSql = "SELECT * FROM `viewers` WHERE `viewer_email`='$viewerEmail'";
    $loginResult = mysqli_query($conn, $loginSql);
    $loginNumRows = mysqli_num_rows($loginResult);

    if ($loginNumRows==1) {
        $showAlert = "Password not match";

        $loginRow = mysqli_fetch_assoc($loginResult);
        if (PASSWORD_VERIFY($viewerPass, $loginRow['viewer_pass'])) {

            session_start();
            $_SESSION['loggedin'] = true;
            $_SESSION['vid'] = $row['viewer_id'];
            $_SESSION['viewer_email'] = $row['viewer_email'];
            $_SESSION['viewer_name'] = $row['viewer_name'];

            // start
            $showAlert = "No authority";
            if (isset($_SESSION['loggedin']) && $_SESSION['loggedin']==true) {
                // header("Location: ../mains/blog?logininsuccess=true&b=$bid");
                // exist();
                if (($bid!=0) && ($bid!=NULL)) {
                    header("Location: ../mains/blog?logininsuccess=true&b=$bid");
                    exist();
                }
                else {
                    // header("Location: ../index");
                    // exist();
                    $showAlert = "No bid";
                    if (isset($_SESSION['loggedin']) && $_SESSION['loggedin']==true) {
                        
                        $showAlert = "Unknown bid";
                        if (($bid=0) && ($bid=NULL) && ($bid='')) {
                            header("Location: ../index?no_bid");
                            exist();
                        }
                        else {
                            header("Location: login?loginsuccess=false&error=$showAlert");
                        }
                    }
                    else {
                        header("Location: login?loginsuccess=false&error=$showAlert");
                    }
                }
            }
            else {
                header("Location: login?loginsuccess=false&error=$showAlert");
            }
            // end
        }
    }
    else {
        $showAlert = "Email not exist";
    }
    header("Location: login?loginsuccess=false&error=$showAlert");
}
?>

The result I am getting is as follows:

loginsuccess=false&error=Unknown%20bid

The result I am expected is as follows:

When $bid='0' or $bid='NULL' or $bid='' or there is no $bid then after logged in is successful it should redirect to index.php, but if $bid='5' then it should redirect to http://localhost/ows-backup-30-7-24/mains/blog?b=5

2

Answers


  1. Could you try this

     <?php
        session_start(); // Ensure session is started at the beginning
    
        if($_SERVER["REQUEST_METHOD"] == "POST") {
            include '../partials/_dbconnect.php';
    
            $viewerEmail = $_POST['vEmail'];
            $viewerPass = $_POST['vPass'];
    
            $loginSql = "SELECT * FROM `viewers` WHERE `viewer_email`='$viewerEmail'";
            $loginResult = mysqli_query($conn, $loginSql);
    
            if ($loginResult) {
                $loginRow = mysqli_fetch_assoc($loginResult);
                if (password_verify($viewerPass, $loginRow['viewer_pass'])) {
                    $_SESSION['loggedin'] = true;
                    $_SESSION['vid'] = $loginRow['viewer_id'];
                    $_SESSION['viewer_email'] = $loginRow['viewer_email'];
                    $_SESSION['viewer_name'] = $loginRow['viewer_name'];
    
                    // Determine where to redirect based on $bid
                    if (isset($_GET['b']) && ($_GET['b'] == '0' || $_GET['b'] == NULL || $_GET['b'] == '')) {
                        header("Location: ../index.php");
                        exit();
                    } else if (isset($_GET['b'])) {
                        $bid = $_GET['b'];
                        header("Location: ../mains/blog.php?b=$bid");
                        exit();
                    } else {
                        // Default redirect if $bid is not set or invalid
                        header("Location: ../index.php");
                        exit();
                    }
                } else {
                    $showAlert = "Password does not match";
                }
            } else {
                $showAlert = "Email not found";
            }
    
            // Redirect with error message
            header("Location: login.php?loginsuccess=false&error=" . urlencode($showAlert));
            exit();
        } 
    ?>
    
    Login or Signup to reply.
  2. I would recommend staying away from nested if else statements, it will greatly simplify your code and make things more understandable for yourself and others.

    In your script you have a number of issues:

    1. SQL injection

    $viewerEmail = $_POST['vEmail']; 
    $viewerPass = $_POST['vPass'];
    
    $loginSql = "SELECT * FROM `viewers` WHERE `viewer_email`='$viewerEmail'";
    

    The $viewerEmail variable is never escaped and attackers can exploit this.

    Use the following to ensure it is safe to use in a database query:

    $viewerEmail = mysqli_real_escape_string($conn, $_POST['vEmail']);
    

    2. Assignment Not Comparison

    if (($bid=0) && ($bid=NULL) && ($bid='')) {
       header("Location: ../index?no_bid");
       exist();
    }
    

    The above is setting $bid to 0 and evaluating falsely. Which means it will never execute.
    Use empty($bid) instead, as it does what you want. For example:

    if (empty($bid)) {
        header("Location: ../index?no_bid");
        exist();
    }
    

    3. Typo

    $loginRow = mysqli_fetch_assoc($loginResult);
    ...
    $_SESSION['vid'] = $row['viewer_id'];
    $_SESSION['viewer_email'] = $row['viewer_email'];
    $_SESSION['viewer_name'] = $row['viewer_name'];
    

    The variable $row is never defined, it should be updated to $loginRow.

    Recommended Solution

    This is a cleaner version of your script that might help explain everything a bit better:

    <?php
    /* only handle post requests */
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        exit();
    }
    
    /**
     * Require database connection
     * @var mysqli $conn
     */
    require '../partials/_dbconnect.php';
    
    /* Get possible request parameters */
    $viewerEmail = $_POST['vEmail'];
    $viewerPass = $_POST['vPass'];
    $bid = $_GET['b'] ?? 0; // optionally set the bid
    
    /* Fetch viewer from database */
    $loginSql = "SELECT * FROM `viewers` WHERE `viewer_email`= ?";
    $loginStmt = $conn->prepare($loginSql);
    $loginStmt->bind_param('s', $loginEmail);
    $loginEmail = $viewerEmail;
    if (!$loginStmt->execute()) {
        $error = urlencode('An error occurred');
        header("Location: login?loginsuccess=false&error={$error}");
        exit();
    }
    $loginResult = $loginStmt->get_result();
    $loginStmt->close();
    
    /* Check if we got a user */
    if (!$loginResult || $loginResult->num_rows < 1) {
        $error = urlencode('Email not exist');
        header("Location: login?loginsuccess=false&error={$error}");
        exit();
    }
    
    /* Get the user details */
    $loginRow = $loginResult->fetch_assoc();
    $loginResult->free();
    if (!$loginRow) {
        $error = urlencode('Email not exist');
        header("Location: login?loginsuccess=false&error={$error}");
        exit();
    }
    
    /* verify the password */
    if (!password_verify($viewerPass, $loginRow['viewer_pass'])) {
        header("Location: login?loginsuccess=false&error=false");
        exit();
    }
    
    /* Start and set login session data */
    session_start();
    $_SESSION['loggedin'] = true;
    $_SESSION['vid'] = $loginRow['viewer_id'];
    $_SESSION['viewer_email'] = $loginRow['viewer_email'];
    $_SESSION['viewer_name'] = $loginRow['viewer_name'];
    
    /* If for some reason the user is not logged in exit */
    if (empty($_SESSION['loggedin'])) {
        $error = urlencode('No authority');
        header("Location: login?loginsuccess=false&error={$error}");
        exit();
    }
    
    /* If we have a bid, redirect to the blog */
    if (!empty($bid)) {
        header("Location: ../mains/blog?logininsuccess=true&b={$bid}");
        // exist();
        exit();
    }
    
    /* If we get here, there is no bid and we can redirect to index */
    header("Location: ../index?no_bid");
    // exist();
    exit();
    
    

    Edits

    • Add prepared statement.
    • Using OOP interface.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search