简体   繁体   中英

my login form doesn't redirect me if success or show error message if fail, the page only refreshes

im making a login/regitration system, the registration works fine, but when i enter the phone number and password and press login, nothing loads, it refreshes and stays on the login page, i have three files, loginValidation that validates the phone number and password, loginHandler that handles the inputs and calls validation functions, and the loginPage that has the actual form

i have this in my loginValidation.php

class loginValidation
{

function validateLogin($phone,$password)
{
    
         $phoneResult = $mysqli->query("SELECT $phone FROM reg WHERE phone='$phone'");
         $passwordResult = $mysqli->query("SELECT $password FROM reg WHERE phone='$phone'");

         if($phoneResult->num_rows >0)
         {
             if( verify_password($password,$passwordResult)==false)
             {
                  $_SESSION["g"]="Phone Number or password is not valid, please check and try again";
                  header("Location: loginPage.php");
             }
           
         }
         else
            unset($_SESSION["g"]);  
        
}

}

and the loginHnadler.php

if(isset($_POST['finishlog']))
{
    if (!empty('phone') && !empty('password'))
    {
        $phone = $_POST['phone'];
        $password = $_POST['password'];
        
         $obj = new loginValidation();
         $obj->validateLogin($phone, $password);
         
         if(isset($_SESSION["g"])==false)
         {
              header("Location: first.php");
         }
         
    }
}

and the loginPage.php

<div class=login action="loginHandler.php" method="POST">
              <form action="">
                     <h1>Log in </h1>
                     <input type="text" name="phone" placeholder="PHONE NUMBER" class="formtexts">
                     <br>
                     <input type="password" name="password" placeholder="PASSWORD" class="formtexts"> <br>
                     <?php if(isset($_SESSION["f"])){ echo $_SESSION[d]; unset($_SESSION["f"]); } ?>
</div>

it's connected to the database, i didn't show the whole code, i only showed what matters.

i have no idea why it's not working, maybe it's because of the verify_password() as am new to this, can someone help me? thank you.

The problem with your code is as stated in the answer above, the action and method classes should be in the form tag and not on the div tag. like this;

<form action="" method="">
</form>

and not

<div action="" method="">
</div>

However i have included another login system for you to use if you wish.

regards

config.php

<?php
/* Database credentials. Assuming you are running MySQL */
define('DB_SERVER', '');
define('DB_USERNAME', '');
define('DB_PASSWORD', '');
define('DB_NAME', '');
 
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

?>

login.php

<?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: blah.php");
   //Redirect User To Page That User Came From
                            if(isset($_SESSION['url'])) 
                            $url = $_SESSION['url']; // holds url for last page visited.
                            else 
                            $url = "index.php"; // default page for 
                            header("Location: https://blahblah/$url"); 
    exit;
}
 
// Include config file
require_once "config.php";
 
// Define variables and initialise with empty values
$username = $password = "";
$username_err = $password_err = $login_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
    // Check if username is empty
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter username.";
    } else{
        $username = trim($_POST["username"]);
    }
    
    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter your password.";
    } else{
        $password = trim($_POST["password"]);
    }
    
    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
        $sql = "SELECT username, password FROM blah WHERE username = ?";
        
        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;
            
            // 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);
                    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["username"] = $username;                            
                            
                            // Redirect user to welcome page
                            /*header("location: index.php");*/
                            
                            //Redirect User To Page That User Came From
                            if(isset($_SESSION['url'])) 
                            $url = $_SESSION['url']; // holds url for last page visited.
                            else 
                            $url = "index.php"; // default page for 
                            header("Location: https://blahblah/$url"); 

                        } else{
                            // Password is not valid, display a generic error message
                            $login_err = "Invalid username or password.";
                        }
                    }
                } else{
                    // Username doesn't exist, display a generic error message
                    $login_err = "Invalid username or password.";
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }
    
    // Close connection
    mysqli_close($link);
}
?>

Now append to the login.php file your form;

<div class="login"  method="POST">
              <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
                     <h1>Log in </h1>
                     <input type="text" name="username" placeholder="PHONE NUMBER" class="formtexts">
                     <br>
                     <input type="password" name="password" placeholder="PASSWORD" class="formtexts"> <br>
      </form>              
</div>

Can you try to change this part of code action="loginHandler.php" method="POST" to your form tag?

It will look like this:

<form action="loginHandler.php" method="POST">
...
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM