header function not redirecting to home.php, why? - php

Here i am using header function to redirect to home.php after login, but header function is not redirecting to that page. Even when i run same code on my local computer it works fine.
<?php
ob_start();
session_start();
require_once 'phpconnection.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location:home.php");
exit;
}
$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['password']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$errMsg = "Please enter valid email address.";
}
// if there's no error, continue to login
if (!$error) {
$res=mysql_query("SELECT userId, userfName, userlName,userPassword FROM userdata 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['userPassword']==$pass ) {
$_SESSION['user'] = $row['userId'];
header("Location:home.php");
} else {
$errMsg = "Try again...";
}
}
}
?>

You do not need the !="" on line 5 because isset() already checks for existence. Either its there or its not.
if (isset($_SESSION['user'])){
header("Location: home.php");
exit;
} else {
echo "something here";
}
You can use !isset() to get the opposite result as well.

Try your code with this code,
<?php
ob_start();
session_start();
if ( isset($_SESSION['user'])!="" ) {
header("Location:home.php");
exit;
}
require_once 'phpconnection.php';
// it will never let you open index(login) page if session is set
?>

Related

Retaining the $_GET url in the link when the user returns to the same page.in mysql php

When the user reset the password by sending their email id. The mail which they receive, is something like this.
Email
http://localhost/folder/folder/reset.php?email=foobar#foo.com&hash=07c5807d0d927
When the above link is clicked, the user fills the New password and Confirm password. We are getting the email and the has from the url. The code below.
reset.php
if( isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash']) ) {
$email = $con->escape_string($_GET['email']);
$hash = $con->escape_string($_GET['hash']);
$result = $con->query("SELECT * FROM users WHERE email='$email' AND hash='$hash'");
if ( $result->num_rows == 0 ) {
$_SESSION['message'] = "Invalid URL for password reset!";
header("location: ../error.php");
}
}
else {
$_SESSION['message'] = "Verification failed, try again!";
header("location: ../error.php");
}
<!-- form goes here -->
We are using the code below to check the matching password.
resetpassword.php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Make sure the two passwords match
if ( $_POST['newpassword'] == $_POST['confirmpassword'] ) {
$new_password = password_hash($_POST['newpassword'], PASSWORD_BCRYPT);
// We get $_POST['email'] and $_POST['hash'] from the hidden input field of reset.php form
$email = $con->escape_string($_POST['email']);
$hash = $con->escape_string($_POST['hash']);
$sql = "UPDATE users SET password='$new_password', hash='$hash' WHERE email='$email'";
if ( $con->query($sql) ) {
$_SESSION['message'] = "Your password has been reset successfully! <a href='login.php'>Login</a>";
header("location: ../success.php");
}
}
else {
$_SESSION['message'] = "Passwords did not match, try again!";
header("location: ../reset.php");
}
}
Now the problem is here. If the users password did not match they goes to reset.php page and when they need to come back to to try again again. When that happens how do we get their email and hash back.
else {
$_SESSION['message'] = "Passwords did not match, try again!";
header("location: ../reset.php");
}
This is what we get, when they come back.
http://localhost/folder/folder/reset.php
Using sessions is your best option here.
Currently the code has another problem which you might want to avoid. Your user can go to resetpassword.php page with ANY email and reset the password for that email, which would result in a very unpleasant security issue.
The proper way of doing what you intend to do would be
reset.php
<?php
$email = array_key_exists('email', $_GET) && !empty($_GET['email']) ? $_GET['email'] : null;
$hash = array_key_exists('hash', $_GET) && !empty($_GET['hash']) ? $_GET['hash'] : null;
session_start();
if( $email !== null && $hash !== null) {
$email = $con->escape_string($email);
$hash = $con->escape_string($hash);
$result = $con->query("SELECT * FROM users WHERE email='$email' AND hash='$hash'");
if ( $result->num_rows == 0 ) {
$_SESSION['message'] = "Invalid URL for password reset!";
header("location: ../error.php");
} else {
$_SESSION['reset_email'] = $email;
$_SESSION['reset_hash'] = $hash;
// do redirect to your new password page or smth
}
}
else {
$_SESSION['message'] = "Verification failed, try again!";
header("location: ../error.php");
}
and resetpassword.php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && array_key_exists('reset_email', $_SESSION) && !empty($_SESSION['reset_email'])) {
// Make sure the two passwords match
if ( $_POST['newpassword'] == $_POST['confirmpassword'] ) {
$new_password = password_hash($_POST['newpassword'], PASSWORD_BCRYPT);
// not sure why you would need to update password reset hash there, so i removed it
$sql = "UPDATE users SET password='$new_password' WHERE email='{$_SESSION['reset_email']}'";
if ( $con->query($sql) ) {
$_SESSION['message'] = "Your password has been reset successfully! <a href='login.php'>Login</a>";
$_SESSION['reset_email'] = null;
$_SESSION['reset_hash'] = null;
header("location: ../success.php");
} else {
// error probably a good thing here (for the user)
$_SESSION['message'] = "Verification failed, try again!";
header("location: ../error.php");
}
}
else {
$_SESSION['message'] = "Passwords did not match, try again!";
header("location: ../reset.php?email={$_SESSION['reset_email']}&hash={$_SESSION['reset_hash']}");
}
}

PHP can't determine whether user is logged in or not

I'm creating a system that the header will show 'login' if the user is not logged in, and if they are, it'll display logout. I've simplified it for now, just showing if the user is logged in or not. With "Login!" meaning they need to login, and "Welcome!" if they are logged in. I used the PHP Code Checker website (https://phpcodechecker.com/) and it couldn't find any errors. I also searched stackoverflow, and everyone else's seems to work.
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
echo "Login!";
} else {
echo "Welcome!";
}
?>
is the code that checks if the user is logged in or not.
My login page works for EVERYTHING else, for my homepage is shows that the user is logged in, but here is the code anyway. (This is only the PHP code, there is HTML for the submit button, ect.)
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location: index.php");
exit;
}
$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);
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($name)){
$error = true;
$nameError = "Please enter your username.";
}
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, userEmail, userPass FROM users WHERE
userName='$name'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if email/pass correct it returns must be
1 row
if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['userId'];
header("Location: dashboard.php");
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
It connects to the database fine, and i'm certain there is no problems with the database, since it works on my other pages.
I've spent a long-while trying to figure this out, and can't.
Thanks!
In your code
if ( isset($_SESSION['user'])!="" ) {
you are comparing true|false != ""
change it to if (isset($_SESSION['user'])) {
or
if (isset($_SESSION['user']) && ($_SESSION['user']!="")) {

Add validation for empty inputs to current PHP Login form

I currently have a form that checks if the username and password exist and logs you and redirects you to the homepage. However if you leave the email and password section blank, you also are able to log into the site. I'm looking to add some sort of validation to avoid someone from just using empty input variables.
This is what I have...
<?php
session_start();
include_once 'config.php';
$email ="";
$userpassword ="";
$errors = 0;
$emailError ="";
$passwordError ="";
if(isset($_SESSION['user'])!="")
{
header("Location: home.php");
}
if(isset($_POST['loginBtn']))
{
if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
{
$emailError = "Email is not valid";
$errors = 1;
}
if(!empty($_POST["password"])) {
$passwordError = "Please enter a Password";
$errors = 1;
}
$email = mysql_real_escape_string($_POST['email']);
$userpassword = mysql_real_escape_string($_POST['password']);
$result=mysql_query("SELECT * FROM users WHERE emailAddress='$email'");
$row=mysql_fetch_array($result);
if($row['password']==md5($userpassword))
{
$_SESSION['user'] = $row['user_id'];
header("Location: home.php");
}
else
{
?>
<script>alert('First time visitors, please create an account to play'); </script>
<?php
}
}
?>
Client Side validation such as JavaScript and HTML5 can be turned off or directly edited via the browser. Always use server side validation as the final authority.
Also, When checking login credentials you need to do a combination check in the where clause.
WHERE username ='$u_user' AND password = '$u_pass'
This is especially the case when allowing the reuse of controlling columns (username, email). Passwords are not always unique.
In the OP's case the lookup on the email only could return multiple results.
<?php
session_start();
include_once('config.php');
IF (isset($_SESSION['user'])!="") { header("Location: home.php"); }
IF (isset($_POST['loginBtn'])) { // the form was submitted
$err = ""; // default error as empty
$email= trim($_POST['email']);
$password = trim($_POST['password']);
// validation
IF (empty($email)) { $err .= "Email is empty<br>";
}ELSE{
IF (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$err .= "Email is not valid<br>";
}
}
IF (empty($password)) { $err .= "Password is empty<br>"; }
IF (!empty($err)) {
// there are errors
echo("<p>".$err."</p>");
}ELSE{
// No errors
$uemail = mysql_real_escape_string($email);
$upass = mysql_real_escape_string(md5($password));
$result = mysql_query("SELECT * FROM users WHERE emailAddress='$uemail' && password = '$upass'");
IF ($result) {
// set session
$row = mysql_fetch_array($result);
$_SESSION['user'] = $row['user_id'];
}ELSE{
echo("<p>Email address and or your password was incorrect.<br>If you do not have an account please create one.</p>");
}
// Close DB connection
mysql_close($Your_db_connection);
// redirect if session is set
IF (isset($_SESSION['user'])) { header("Location: home.php"); }
}
}ELSE{
// form not submitted
}
?>
You can use html5 validation for login form use required attributes for blank input field validation this validation is very easy and user friendly please use this way

Login Not Working PHP MySQL

I'm trying to fix my login page...
It works fine on the login.php with redirecting but on the index it doesn't redirect even if the session is empty. Any pointers? I'm new to this, so forgive me if it's really obvious.
<?php
require_once('../includes/config.php');
session_start();
if(!isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='no'){
// not logged in
header("location: login.php");
exit();
} else {
$_SESSION['loggedin'] = 'yes';
}
?>
<?php
include("../includes/config.php");
$error = NULL;
$atmpt = 1;
if (!isset($_SESSION)) {
session_start();
}
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='yes'){
// logged in
header("location: index.php");
exit();
}
if(isset($_POST['login']))
{
/* get username and password */
$username = $_POST["username"];
$password = $_POST["password"];
/* MySQL Injection prevention */
$username = mysqli_real_escape_string($mysqli, stripslashes($username));
$password = mysqli_real_escape_string($mysqli, stripslashes($password));
/* check for user in database */
$query = "SELECT * FROM admin_accounts WHERE username = '$username' AND password = '$password'"; // replace "users" with your table name
$result = mysqli_query($mysqli, $query);
$count = $result->num_rows;
if($count > 0){
//successfully logged in
$_SESSION['username']=$username;
$_SESSION['loggedin']='yes';
$error .= "<div class='alert alert-success'>Thanks for logging in! Redirecting you..</div>";
header("refresh:1;url=index.php");
} else {
// Login Failed
$error .= "<div class='alert alert-danger'>Wrong username or password..</div>";
$_SESSION['loggedin']='no';
$atmpt = 2;
}
}
?>
The line
session_start();
should be the very first line in the php script.
Just modify first three lines.
As session_start() should be put before any output has been put on the browser (even space).
<?php
session_start();
require_once('../includes/config.php');
if (empty($_SESSION['loggedin']) && $_SESSION['loggedin']=='no') {
...

php sessions to authenticate user on login form

I have the following code designed to begin a session and store username/password data, and if nothing is submitted, or no session data stored, redirect to a fail page.
session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
} else {
header('Location:http://website.com/fail.php');
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
Its not working the way it should and is redirecting me to fail even though i submitted my info and stored it in the session. Am i doing something wrong?
NOTE the authed function worked fine before i added the session code.
what about using this to setup session
session_start();
if( isset($_POST['username']) && isset($_POST['password']) )
{
if( auth($_POST['username'], $_POST['password']) )
{
// auth okay, setup session
$_SESSION['user'] = $_POST['username'];
// redirect to required page
header( "Location: index.php" );
} else {
// didn't auth go back to loginform
header( "Location: loginform.html" );
}
} else {
// username and password not given so go back to login
header( "Location: loginform.html" );
}
and at the top of each "secure" page use this code:
session_start();
session_regenerate_id();
if(!isset($_SESSION['user'])) // if there is no valid session
{
header("Location: loginform.html");
}
this keeps a very small amount of code at the top of each page instead of running the full auth at the top of every page. To logout of the session:
session_start();
unset($_SESSION['user']);
session_destroy();
header("Location: loginform.html");
First, don't store the password in the session. It's a bad thing. Second, don't store the username in the session until after you have authenticated.
Try the following:
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$authed = auth($username, $password);
if (! $authed) {
header('Location: http://website.com/fail.php');
} else {
$_SESSION['username'] = $username;
}
}
if (isset($_SESSION['username'])) {
$navbar = 1;
$logindisplay = 0;
} else {
header ('Location: http://website.com/fail.php');
}
Just some random points, even though they may not actually pertain to the problem:
Don't store the password in plaintext in the session. Only evaluate if the password is okay, then store loggedIn = true or something like that in the session.
Check if the password and the username are $_POSTed, not || (or).
Don't pass password and username back and forth between $password and $_SESSION['password']. Decide on one place to keep the data and leave it there.
Did you check if you can store anything at all in the session? Cookies okay etc...?
To greatly simplify your code, isn't this all you need to do?
if (isset($_POST['username'] && isset($_POST['password'])) {
if (auth($_POST['username'], $_POST['password'])) {
$_SESSION['user'] = /* userid or name or token or something */;
header(/* to next page */);
} else {
// display "User credentials incorrect", stay on login form
}
} else {
// optionally: display "please fill out all fields"
}
Here are a few other things, which may or may not help you, by the way :
Do you have error_reporting on ? (see also)
Do you have display_errors on ?
Is session_start the first thing you are doing in your page ? There must be nothing output before
Are the cookies created on the client-side ?
header Location indicates the browser it has to go to another page ; it doesn't stop the execution of the PHP script. You might want to (almost always anyway) add "exit" after it.
Headers are not function calls. They put a directive into the HTTP headers, and the last one to execute is the one which will be processed. So let say if you have something like this
if ($bAuthed)
{
header("location: login.php");
}
// error case
header("location: error-login.php");
You will always be redirected to error-login.php no matter what happens. Headers are not function calls!
The solution to my specific problem above
session_start();
if(isset($_POST['username']) || isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
} else {
header('Location:http://website.com/fail.php');
}
Don't use else section in second if statement.
session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}

Categories