So , I have made a website and its login system . There is a Landing page , a "New post" page and a login page . I do not want the user to access the "New post" page if not logged in [That's solved] , but , if he will try to access it without a session , it will redirect him to the login page with a /login/?new . When he logs in with ?new in the address bar , it should redirect him to the "New post" page , if the url is only /login/ , it takes him to the landing . That's the code I tried to do :
if( $count == 1 && $row['userPass']==$password && isset($_POST["new"]) ) {
$_SESSION['user'] = $row['userId'];
header('Location:../new');
} else if ($count == 1 && $row['userPass']==$password) {
$_SESSION['user'] = $row['userId'];
header('Location:../');
}
else {
$errMSG = "Incorrect Credentials, Try again...";
}
That's the full code :
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($email)){
$error = true;
$emailError = "Please enter your email address.";
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
// if there's no error, continue to login
if (!$error) {
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT userId, userName, userPass FROM users WHERE userEmail='$email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if( $count == 1 && $row['userPass']==$password && isset($_POST["new"]) ) {
$_SESSION['user'] = $row['userId'];
header('Location:../new');
} else if ($count == 1 && $row['userPass']==$password) {
$_SESSION['user'] = $row['userId'];
header('Location:../');
}
else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>