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

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']!="")) {

Related

header function not redirecting to home.php, why?

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
?>

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

How to redirect to different page after form is submitted using header()?

I've looked at lots of answers to redirect to a different page after submitting a form, but haven't been able to get it to work thus far, probably because I have no idea where to actually put the code. Can anyone help? The rest of this code is working fine, i just need to know where to place header():
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
//connects to database, checks username & password against database to see is user exists
if($username && $password)
{
include ("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if($numrows !==0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
//if username and password are correct
if($username==$dbusername&&md5($password)==$dbpassword)
{
echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
}
//if password is incorrect
else
echo "Your password is incorrect.";
}
//if username is incorrect
else
die("Username does not exist.");
}
//if no information is submitted
else
die("Please enter your login details.");
//prevents errors from displaying on page
error_reporting(0);
?>
I also need to know where it goes for this page:
<?php
//Check if register button was pressed
$button = $_POST['button'];
//if button was pressed,
if ($button)
{
//get data from form,
$username = $_POST['username'];
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
}
//check if all information has been entered,
if ($username && $password && $retype_password && $first_name && $last_name)
{
//check if password and retype_password are the same
if($password==$retype_password)
{
//check if username already exists
include("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username = '$username'");
$numrows = mysql_num_rows($query);
if($numrows == 0)
{
//encrypt password
$password = md5($password);
//sends data from form to database - creates new user
$register = mysql_query("INSERT INTO users VALUES ('', '$username', '$password', '$first_name', '$last_name')");
echo "You are now registered. <a href='main.php'>Continue to site.</a>";
}
else
echo "Username is unavailable.";
}
else
echo "Password did not match.";
}
//prevents errors from displaying on page
error_reporting(0);
?>
Thanks in advance!
if($username==$dbusername&&md5($password)==$dbpassword)
{
$_SESSION['username'] = $username;
header( 'Location: http://www.yoursite.com/new_page.html' ) ;
}
You should put it once the job is done : that is after
//echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
header('Location: your url');
exit;
Don't forget the "exit" or what follow will be executed.
That said, you cannot echo something before a doing redirection, that's logical because the echo can't be seen.
So, either you do not echo :
$_SESSION['username'] = $username;
header('Location: your url');
exit;
Or you do a HTML (or javascript) redirection, with a 5 seconds delay:
echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
exit;
In which case you have to put it in the < head > section, to do the HTML redirection:
<meta http-equiv="refresh" content="0; url=http://example.com/main.php" />
Also
error_reporting(0);
Should be put at the beginning of the page, unless you want errors for previous lines to be shown.
BUT : error_reporting(0); should NEVER be used on a development site (and always on a production site).
You should turn on display_errors('on') and error_reporting(E_ALL) to see errors - errors are very useful for a developer.

mysql check account type to see if admin on login

hi in my script i have it logging in users , but i want to have the script also check if the user is an admin by seeing if the account_type is a,b,c account type "c" is the admin and i would like it to redirect the admin to the admin page ...
<?php // Start Session to enable creating the session variables below when they log in
// Force script errors and warnings to show on page in case php.ini file is set to not display them
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once("security/checkuserlog.php");
if (isset($_SESSION['idx'])) {
echo '<script language="Javascript">';
echo 'window.location="home.php"';
echo '</script>';
}
//-----------------------------------------------------------------------------------------------------------------------------------
// Initialize some vars
$errorMsg = '';
$username = '';
$pass = '';
$remember = '';
if (isset($_POST['username'])) {
$username = $_POST['username'];
$pass = $_POST['pass'];
if (isset($_POST['remember'])) {
$remember = $_POST['remember'];
}
$username = stripslashes($username);
$pass = stripslashes($pass);
$username = strip_tags($username);
$pass = strip_tags($pass);
// error handling conditional checks go here
if ((!$username) || (!$pass)) {
$errorMsg = '<font color="red">Please fill in both fields</font>';
} else { // Error handling is complete so process the info if no errors
include 'connect_to_mysql.php'; // Connect to the database
$username = mysql_real_escape_string($username); // After we connect, we secure the string before adding to query
//$pass = mysql_real_escape_string($pass); // After we connect, we secure the string before adding to query
$pass = md5($pass); // Add MD5 Hash to the password variable they supplied after filtering it
// Make the SQL query
$sql = mysql_query("SELECT * FROM members WHERE username='$username' AND password='$pass'");
$login_check = mysql_num_rows($sql);
// If login check number is greater than 0 (meaning they do exist and are activated)
if($login_check > 0){
while($row = mysql_fetch_array($sql)){
// Create session var for their raw id
$id = $row["id"];
$_SESSION['id'] = $id;
// Create the idx session var
$_SESSION['idx'] = base64_encode("g4p3h9xfn8sq03hs2234$id");
$username = $row["username"];
$_SESSION['username'] = $username;
} // close while
// Remember Me Section
// All good they are logged in, send them to homepage then exit script
header("location: home.php");
exit();
} else { // Run this code if login_check is equal to 0 meaning they do not exist
$errorMsg = '<font color="red">The Username And Password did not match.</font>';
}
} // Close else after error checks
} //Close if (isset ($_POST['uname'])){
?>
if ($row["account_type"] == "c") { header("Location: admin.php"); }; in your while loop should do it.
This will basically set the "Location" header to "admin.php" or whatever admin page you want, however don't forget to check in your admin page if the user is actually logged in, to avoid users simply going manually to "admin.php" and bypassing the permission check.
$account_type= $row["account_type"];
$_SESSION['account_type'] = $account_type;
then change header("location: home.php"); into
if($account_type=='admin')
{
header("location: adminpanel.php");
}
else
{
header("location: home.php");
}

Is $_SERVER[HTTP_HOST] the cause of redirect issues?

I have enabled vanity urls (user.domain.com). When a session expires or somebody clears the cookies, the page would get redirected to user.domain.com which has the login page. So, on all pages i am using the following code:
if(!isset($_SESSION['user_name'])) { header("Location: http://$_SERVER[HTTP_HOST]");}
2 of of 10 times i get a redirect error saying that the page is redirecting too many times.
Could this be the reason? And if it is what can i do to redirect in a way that won't cause such issues.
Thanks.
Login code:
<?php
session_start();
// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];
// Set up the session variables
$_SESSION["user_name"] = $username;
$ugData = $_REQUEST['sub_name'];
if($_POST){
$_SESSION['user_name']=$_POST["user_name"];
$_SESSION['password']=$_POST["password"];
}
$secret = $info['password'];
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site']))
//if there is, it logs you in and directes you to the members page
{
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$check = mysql_query("SELECT user_name, password FROM accounts WHERE user_name = '$username' and sub_name='$ugData'")or die(mysql_error());
while($info = mysql_fetch_array( $check ))
{
if (# $info['password'] != $pass)
{
}
else
{
header("Location: home.php");
}
}
}
//if the login form is submitted
if (isset($_POST['submit'])) { // if form has been submitted
// makes sure they filled it in
if(!$_POST['user_name'] | !$_POST['password']) {
die('You did not fill in a required field.');
}
// checks it against the database
if (!get_magic_quotes_gpc()) {
$_POST['user_name'] = addslashes($_POST['user_name']);
}
$check = mysql_query("SELECT user_name,password FROM accounts
WHERE user_name = '".$_POST['user_name']."'
and sub_name='".$ugData."'")or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
die('That user does not exist in our database.
<a href=add.php>Click Here to Register</a>');
}
while($info = mysql_fetch_array( $check ))
{
$_POST['password'] = md5($_POST['password']);
$_POST['password'] = $_POST['password'];
//gives error if the password is wrong
if (# $_POST['password'] != $info['password']) {
die('Incorrect password, please try again');
}
else
{
// if login is ok then we add a cookie
$_POST['user_name'] = stripslashes($_POST['user_name']);
$hour = time() + 3600;
setcookie(ID_my_site, $_POST['user_name'], $hour);
setcookie(Key_my_site, $_POST['password'], $hour);
//then redirect them to the members area
header("Location: home.php");
}
}
}
else
{
?>
The header("Location: http://{$_SERVER['HTTP_HOST']}"); isn't the problem per-say.
However, if you do have that code on your login page then yes, you'll just keep redirecting yourself to the home page because you won't be able to login.
Make sure that you do not redirect the user if he's on the login page.
EDIT: Try header('Location: /'); Maybe you have some weird server issue which causes $_SERVER['HTTP_HOST'] do sometimes be null.
Assuming that redirecting to http://yourserver/ means http://yourserver/index.php, then you should change the if to read
if(!isset($_SESSION['user_name']) && $_SERVER['PHP_SELF'] != '/index.php')
{
header("Location: http://$_SERVER[HTTP_HOST]");
}
This will avoid endless redirects.
Try using this with a die():
if(!isset($_SESSION['user_name'])) { header("Location: http://user.domain.com"); die();}
If url changes from user to user grab username from db first, and use it in redirection. Try something like:
...
$username = $row["username"];
...
and use it:
if(!isset($_SESSION['user_name'])) { header("Location: http://".$username.".domain.com"); die();}

Categories