I know there are many questions about this, but i could not find an answer for when i want the login to always redirect to the main page except when the user clicks on the "submit" page it should log in then allow the user to add a suggestion. I managed to redirect to log in page after clicking on the "submit" page but after that, it redirects to the main page and i get stuck in a loop. (Index is my main page). (suggest is where i want to force the log in). Here is what i have done so far: at the top of my suggest.php:
<?php
if(!isset($_SESSION['user_id']))
{
$_SESSION["login_redirect"] = $_SERVER["PHP_SELF"];
header("Location: login2.php");
exit;
}
?>
Login-form.php:
<?php
if(isset($_POST['loginbutton'])){
require 'dbh.inc.php';
$UsernameEmail = $_POST['username/email'];
$password = $_POST['password'];
if (empty($UsernameEmail)||empty($password)){
header("location: ../Index.php?error=emptyfields&username");
exit();
}else {
$sql = "SELECT * FROM users WHERE username=? OR email =? ;" ;
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)){
header("location: ../Index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt , "ss", $UsernameEmail,$UsernameEmail );
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if($row = mysqli_fetch_assoc($result)){
$pwdCheck = password_verify($password , $row['password']);
if($pwdCheck == false ){
header("location: ../Index.php?error=wrongPassword");
exit();
} else if ($pwdCheck == true ){
session_start();
$_SESSION['user_id']= $row['id'];
$_SESSION['user_name']= $row['username'];
} else {
header("location: ../Index.php?error=wrongPassword");
exit();
}
}
else {
header("location: ../Index.php?nouser/emailmatch");
exit();
}
}
}
}
else {
header("Location: ../Index.php?succses");
exit();
}
I also tried this code in SUGGEST.php
<?php
if(!isset($_SESSION['user_id']))
{
header('Location: login2.php?redirect=SUGGEST.php');
exit;
}
?>
and this one in login-form.php but that didn't work either
if (isset($_GET['redirect'])) {
header('Location: ' . $_GET['redirect']);
}
that is my first time coding in php, so i would really apperiate a detailed answer. Thank you
You should use session_start();
at first line of each page, actually without any space or break-line before that!
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.