I'm having a problem getting this code to work on the website that I'd like to launch soon. In particular when I sign in the header won't redirect after a successful login. I have used this code before many times and I've never had a problem with it. The only difference now is that I'm using a different server and a different database. Here's the code that is giving me trouble:
<?php
/*set all the variables*/
$email = $_POST['email'];
$password = sha1($_POST['password']); /* hash the password*/
$conn = mysqli_connect ('servername', 'username', 'password', 'databasename') or die('Error connecting to MySQL server');
/*select the id from the users table that match the conditions*/
$sql = "SELECT id FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
$count = mysqli_num_rows($result);
if ($count == 1) {
echo 'Logged in Successfully.';
$row = mysqli_fetch_array($result);
session_start();
$_SESSION['user_id'] = $row['id'];
/*If true head over to the users table*/
header('location: users_table.php');
}
/*If invalid prompt them to adjust the previous entry*/
else {
echo '<h2>Invalid Login</h2><br />';
echo '<h2>Click HERE to go back and adjust your entry.</h2>';
}
mysqli_close($conn);
?>
It's not a matter of it connecting properly because I get the message 'successful Login' but it won't redirect at all.
Thanks for all the answers, I tried removing the echo but all I get now is a blank page, I thought maybe it was the browser I was using so I switched to another and I still just get a blank page, any other suggestions?
You cannot echo anything before your header statement.
echo 'Logged in Successfully.';
This is causing the header call to not work.
if ($count == 1) {
echo 'Logged in Successfully.';
//this statement is creating problem
$row = mysqli_fetch_array($result);
session_start();
$_SESSION['user_id'] = $row['id'];
/*If true head over to the users table*/
header('location: users_table.php');
}
This is because you are echoing something berfore header
You should use ob_start() at start and ob_end_flush() at the end of the document..
or do not echo before header().As we found you haven't turned on the error.So turn it ON.
You can't be posting the header after the echo... if this actually worked you'd never see the text (it would simply redirect). (To fix remove/comment out the echo line)
Also the location header requires an absolute/full URL (although many browsers seem to cope with relative URLs).
If you want to do it this way (show some sort of status before hand), use an HTML or Javascript redirect that triggers after a couple of seconds.
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Logged in Successfully.</title>
<meta http-equiv="REFRESH"
content="5;url=http://www.example.com/users_table.php"></HEAD>
<BODY>
Logged in Successfully.
</BODY>
</HTML>
Javascript
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>Logged in Successfully.</title>
</HEAD>
<BODY onLoad="setTimeout(function() {
window.location='http://www.example.com/users_table.php'},5000)">
Logged in Successfully.
</BODY>
</HTML>
Better yet, allow the users_table.php page to display a successful login message and use the header-location redirect.
Related
The session is not passing and I want to restrict the users from viewing the login page while they are logged in for that I tried many things, but it didn't work:
My login page
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('connect.php');
extract($_POST);
$result = mysqli_query($link, "SELECT * FROM users ");
$row = mysqli_fetch_assoc($result);
//var_dump($row['username']);
//var_dump($row['password']);
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
if ($username == $row['username'] && $password == $row['password']){
session_start();
$_SESSION['nID'] = true;
//echo"Login";
header('Location: home.php');
} else {
echo"Login failed";
}
}
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title>Login page</title>
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<body>
<div id="frm">
<form action="login.php" method="POST" style="width: 232px; padding-left: 490px;">
<h1> Login</h1>
<p>
<label>Username</label>
<input type="text" id="username" name="username" />
</p>
<p>
<label>password</label>
<input type="password" id="password" name="password"/>
</p>
<p>
<input type="submit" id="btn" value="login" name="login" style="border-radius: 30%; background-color: gold; box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);"/>
</p>
<p>
Not yet a member Register here
</form>
</div>
</body>
</html>
My home page
<?php
session_start();
if ($_SESSION['nID'] == false) {
header("Location: login.php");
die();
} elseif ($_SESSION['nID'] == true) {
header("Location: Home.php");
die();
} else {
echo"cant connect";
}
?>
<html>
<head>
<link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<ul class="nav nav-pills">
<li role="presentation" class="active">Home</li>
<li role="presentation">Information</li>
<li>Logout
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</body>
</html>
The session is not passing and it doesn't prevent the user from viewing the homepage while they aren't logged in.
I have tried many different things, but nothing seems to work.
Some thoughts on this question:
1) Stop using extract(). You simply don't need it.
Warning Do not use extract() on untrusted data, like user input (i.e. $_POST, $_FILES, etc.). If you do, for example if you want to temporarily run old code that relied on register_globals, make sure you use one of the non-overwriting flags values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.
From the Manual.
2) As noted in another answer Your SQL query is far too vague; you're returning the first answer of a search of the whole DB rather than searching for any specific criteria.
SELECT password FROM users WHERE username=username_here LIMIT 1
And then take this row and compare with the given password:
if($password === $row['password'])
3) Your password system used on MySQL / PHP is NOT GOOD ENOUGH. Stop using md5() and employ password_hash and password_verify PHP functions. Please read how to do it properly and this comment.
4) Every time you use header("Location: ...") to redirect the user it is highly recommended you add a die or exit command immediately afterwards in order to cease the code execution on the current page. For example:
header("Location: this_page_will_never_load.php");
header("Location: this_page_will_always_load_instead.php");
5) require and include functions do not require brackets.
NOTE
Re the numerous answers here referencing session_start(); if session_start() is called after output is sent to the browser, then there will be an error notice generated. OP has not reported an error notice even with:
error_reporting(E_ALL);
ini_set('display_errors',1);
So session_start() placement in the code is not an issue in this specific situation.
However:It is best practise to put your session_start() as early as possible in your code and before such debug things as var_dump which would cause session_start not to load becase var_dump has already thrown data out to the browser.
Finally, an answer to your problem:
I want to restrict the users from viewing the login page while they are logged in for that I tried many things but it didn't work:
Your code in login.php:
if(isset($_POST['login'])){
///session stuff etc.
}
The above code on your login.php page will only execute if the page is being given POSTed data. What you have is that once someone is logged in correctly and they then return to the login.php page, they are not resubmitting the POSTed data so this code block is simply not running.
Because this code block contains all your $_SESSION references this is why it looks like $_SESSION is not running.
Instead you want to do this (simplified) in login.php:
session_start();
if(isset($_POST['login'])){
// setup session values,
// once POSTed login data is checked and authorised in the database
$_SESSION['nID'] = true;
}
elseif ($_SESSION['nID'] === true){
// is already logged in so redirect to the index page.
header("Location: index.php");
exit;
}
else {
// this fires if no POSTed data is sent and no valid
// session is found.
}
Try this condition in your home.php file:
session_start();
if (!isset($_SESSION['nID']) || empty($_SESSION['nId'])) {
header("Location: login.php");
die();
}
You try this code:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('connect.php');
extract($_POST);
$result = mysqli_query($link, "SELECT * FROM users ");
$row = mysqli_fetch_assoc($result);
//var_dump($row['username']);
//var_dump($row['password']);
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
if ($username == $row['username'] && $password == $row['password']){
//session_start(); removed it
$_SESSION['nID'] = true;
//echo"Login";
header('Location: home.php');
} else {
echo"Login failed";
}
}
?>
On every page, you need to add session_start() in the page heading.
First: First of all, your query is wrong. You're always checking the value with the first user in the table. You need to a query with the where clause.
SELECT * FROM users WHERE username=username_here AND password=hash_password_here
Second: Your If statement should be like the following.
<?php
session_start();
if (!isset($_SESSION['nID'])) {
header("Location: login.php");
die();
}
?>
Third: Try to use prepared statements to avoid an SQL injection.
$stmt = $link->prepare("SELECT * FROM users where username=? and password=?");
$stmt->bind_param('ss', $username, md5($password));
$stmt->execute();
$get_result = $stmt->get_result();
$row_count = $get_result->num_rows;
if ($row_count > 0) {
session_start();
$_SESSION['nID'] = true;
header('Location: home.php');
die();
}
else {
echo"Login failed";
}
4th: Don't use Md5() for passwords. Try to use password_hash() and password_verify(). Reference link.
While registrating, use password_hash() to hash the password and store it in the database and while logging in, use password_verify() to verify the password like this. Reference link.
You have to call the session_start() function in the file where you are trying to use a session variable.
You need to add session_start(); on every page to get the session variables.
I am creating some kind of a login/registration system right now. Registration form, email confirmation and login is already working. I now have problems with my sessions. Please keep in mind that this project is just a test project. I know that I should use PDO but for this testing purposes I need to find out why it is not working they way I did it.
Here is my login.php PHP code:
<?php include ('inc/database.php');
if (isset($_POST['submit'])) {
// Initialize a session:
session_start();
$error = array();//this aaray will store all error messages
if (empty($_POST['email'])) {//if the email supplied is empty
$error[] = 'You forgot to enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
$Email = $_POST['email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['passwort'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['passwort'];
}
if (empty($error))//if the array is empty , it means no error found
{
$query_check_credentials = "SELECT * FROM user WHERE email='$Email' AND password='$Password' AND activation IS NULL";
$result_check_credentials = mysqli_query($connect, $query_check_credentials);
if(!$result_check_credentials){//If the QUery Failed
echo 'Query Failed ';
}
if (#mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull
{ // A match was made.
$row = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email'] = $row["email"];
//Assign the result of this query to SESSION Global Variable
header("Location: index.php");
}else
{ $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect';
}
} else {
echo '<div> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
if(isset($msg_error)){
echo '<div>'.$msg_error.' </div>';
}
/// var_dump($error);
} // End of the main Submit conditional.
?>
Here is the beginning of my protected index.php
<?php
ob_start();
session_start();
if(!isset($_SESSION['email'])){
header("Location: login.php");
}
include 'header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
.....
There must be a problem with my session and I do not know why. Is it wrong to use the email as session? Am I using the email as session? What other options do I have?
Problem is right now, that if I click on Login, nothing happens. I will be redirected to login.php instead of index.php!
Any suggestions?
As Fred -ii- already mentioned in comments above, your $_SESSION['email'] is never set, and therefor you are re-directed to your login-page every time.
It's also worth noting that when using header("Location: ...");, you can not have any output prior to the header! Otherwise the header will fail. Output is generally any HTML, echo, whitespace (see this SO).
So, once you make sure that your header("Location: index.php"); actually works, move on to fixing your $_SESSION.
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC); does not set $_SESSION['email'] (as already stated by Fred -ii-). To fix this, you need to fix your results from the database.
$row = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email'] = $row["email"];
The code above will return the row "email" from the result in the database, and set it to the session of "email", which later is checked when you are trying to access index.php.
A couple of side-pointers (not really your current problem, but a few tips to make your code better).
You should use exit; after using header("Location: ..."); (See this SO)
You are not hashing your password, so it's stored in plain-text in your database (big no-no)
Indenting your code properly makes it a lot easier to read, and in turn easier to troubleshoot
If you do the above, and it still doesn't work, we'd need some more information to help troubleshoot further (like what happens when you're logging in (is it as expected?), what results are returned, and so forth).
try to change,
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
to
$results = mysqli_fetch_row($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email']=$results['email'];
and try to check your "activation" field in database for null while login...
I have a php script. Many of my customers are using it. But for few they say, they are able to login but when they click on any links from the menu, it just redirects to index.php
I have checked my code, menu links, folders... I have even checked users browser settings, antivirus, firewall... But no problem.
I am not getting why it is happening. here is my session file, while submitting login details i include this file
admin_auth.php
session_start();
if(isset($_SESSION['ADMIN']))
{
$_SESSION['name'] = $_SESSION['ADMIN'];
try {
$bdd = new PDO('mysql:host=localhost;dbname=nerp', 'root', '');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
$m1 = "select * from users where username='".$_SESSION['ADMIN']."'";
$resultat = $bdd->query($m1) or die(print_r($bdd->errorInfo()));
//$m2 = mysql_query($m1) or die (mysql_error());
//$m3 = mysql_fetch_array($resultat);
$m3 = $resultat->fetch(PDO::FETCH_ASSOC);
$_SESSION['uid'] = $m3['id'];
$_SESSION['name'] = $m3['firstname'] ." ". $m3['lastname'];
$_SESSION['pos']= $m3['position'];
$_SESSION['department'] =$m3['department'];
$_SESSION['location'] =$m3['location'];
$_SESSION['password'] =$m3['password'];
$_SESSION['auth'] = md5( date('Ymd') . $_SESSION['password'] );
$_SESSION['email'] = $m3['email'];
}
else
if(!isset($_SESSION['ADMIN']) )
{
header("location:index.php");
}
login_submit.php
<?php
ob_start();
error_reporting(0);
session_start();
include("connect.php");
$user=$_POST['login_name'];
$pass=$_POST['login_password'];
$sql="SELECT * FROM users WHERE username='".$user."' AND password='".$pass."' ";
$query=mysqli_query($con, $sql) or die(mysqli_error());
$row=mysqli_fetch_array($query);
$username=$row['username'];
$count=mysqli_num_rows($query);
if($count==1)
{
$_SESSION['ADMIN']=$row['username'];
$_SESSION['name'] = $row['firstname'];
header("location:dashboard.php?user=".$_SESSION['ADMIN']."");
}
else
{
header("location:index.php");
echo "could not connect";
}
?>
is there any problem with this? . if not, why they are not able to open any links.
Based your code, and the symptom you described of those few users, it looks like those few users have disallowed cookies. So when a user with cookies disallowed goes to make a subsequent request after authenticating, they don't send the PHPSESSID cookie (here you can see an example)
So, what happens in your code is, the server sees isset($_SESSION['ADMIN']) is not set, and it drops them to the bottom of your code, which sends them back to index.php.
You can test this by disallowing cookies in your browser. A way to fix it (other than telling your users to enable cookies) is to attach some kind of ID to the URL and maintain an ID as your users move though the site. PHP can do this for you if you set:
<?php
ini_set("session.use_cookies",1);
ini_set("session.use_only_cookies",0);
ini_set("session.use_trans_sid",1);
session_start();
?>
Although I should mention this works with regular html links. It works by the PHP preprocessor adding its code to your links. Since you mentioned a menu, if your menu links are generated by javascript the PHP preprocessor won't know to add its code to the links there.
Successful login on my login page should direct to a homepage (which it does - I double checked to see is the variables are set and they are when a correct username/password is entered). Otherwise, the login page should be private.
LOGIN PHP (works fine)
<?php
session_start();
require_once("../inc_files/Lesson_5_DB_Connection.php");
error_reporting(E_ALL);
ini_set('display_errors', 1);
$error_message= "";
$user_name = "";
$user_password= "";
$_SESSION['username']="";
$_SESSION['employeeNumber']="";
if (isset($_POST['submit'])) {
$user_name = $_POST['user'];
$user_password= $_POST['pass'];
// ADD QUERY TO CHECK IF USER/PASS COMBO IS CORRECT
if(!empty($user_name) && !empty($user_password)) {
$query = "SELECT * FROM employees WHERE username='$user_name' and password='$user_password'";
$result = mysqli_query($dbc, $query)
or die ('Error querying username/password request');
if(mysqli_num_rows($result) == 1) {
while ($row = mysqli_fetch_array($result)) {
$_SESSION['username'] = $row['username'];
$_SESSION['employeeNumber'] = $row['employeeNumber'];
}
header("Location: /LESSON5/3%20-%20HOMEPAGE%20:%20WELCOME.php");
exit;
} // end if rows
else {
$error_message = "You were not able to log in";
} // end else
// Direct to other webpage
} // end query
} // end isset
?>
The homepage should only be visible if the $_SESSION variables are set. If the user is not logged in (session variables not set) then the homepage should redirect to the login page. Now, I added a validation to see if variables are not set (!isset). This validation keeps the page from showing any content. When I delete this validation the HTML shows up fine. When I delete the validation and echo the variable values I get the values returned.
It's just the if(!isset($_SESSION['username']) && !isset($_SESSION['employeeNumber']) keeping from showing any content on the page.
HOMEPAGE
<?php
session_start();
require_once("../inc_files/Lesson_5_DB_Connection.php");
if(!isset($_SESSION['username']) && !isset($_SESSION['employeeNumber']) {
header("Location: /LESSON5/1%20-%20LOGIN.php");
}
?>
<!DOCTYPE html>
<head>
<title></title>
<meta charset="utf-8">
<link type="text/css" rel="stylesheet" href="/LESSON5/5_Signup_CSS.css">
</head>
<body>
<p><span id="logout">Logout</span></p>
<hr>
<h1>Welcome to my homepage! <br> You have successfully logged in.</h1>
<?php
mysqli_close($dbc);
?>
</body>
</html>
Is there any reason why that validation is keeping the PHP from showing the HTML(if user login is correct) or redirect the page(if user not logged in)?
Basically error is in your php if condition. One parenthesis is missing. change like this:-
if(!isset($_SESSION['username']) && !isset($_SESSION['employeeNumber']))
Note:- try to add error_reporing at the top of your all php pages so that you can get php errors if happen. check the manual of error_reporing on php site. Thanks.
If you are working on local server you can change your php.ini settings for this.
You can get how to change php.ini setting on google easily.
ini_set is function of php is for this purpose if you want to do it programmatically not with php.ini directly.
<?php
session_start();
include 'db.php';
include 'header.html';
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['email'])) {
header("location:profile.php");
} elseif(!empty($_POST['email']) && !empty($_POST['pass'])) {
$email = mysql_real_escape_string($_POST['email']);
$pass = md5(mysql_real_escape_string($_POST['pass']));
$sql = mysql_query("SELECT id, name, email, pass FROM users WHERE email='$email' AND pass='$pass'");
$row = mysql_fetch_array($sql);
$id = $row['id'];
$email1 = $row['email'];
$name = $row['name'];
$num = mysql_num_rows($sql);
if($num == 1) {
$_SESSION['id'] = $id;
$_SESSION['email'] = $email1;
$_SESSION['name'] = $name;
$_SESSION['LoggedIn'] = 1;
$update = mysql_query("UPDATE users SET lastlogin=NOW() WHERE email='$email1'");
header("location:profile.php");
} else {
echo "<h1>Error</h1>";
echo "<p>Sorry! Either your account could not be found or you have entered the wrong email or password. Please try again.</p>";
}
}
?>
This script works perfectly in my localhost environment but when uploaded to host, it does not go to the profile.php after logging in. Also, it doesn't redirect to profile.php if the session is set or not empty. Any ideas?
And second question, is my code correct for updating the 'lastlogin' to the current time? What does the database structure have to be for this? It is not updating in my database.
Thank you for your help.
your code is very ok for updating the lastlogin, but what is the error you get? please give what type of error you get on this. logically your code seems to be right, it may be some syntax error. add error_reporting(E_ALL) on top of your page and see what error is occurred actually.
header("location: profile.php");
^ //space should present because in some host environment it creates problem
If you are redirecting to the login script from a form using most likely POST, shouldn't you use $_POST[''] instead of $_SESSION?
Just a thought.
Always use exit(); after header redirection
Ok figured it out with an extensive search. The headers were already being sent with the
include header.html
line so it could not perform the
header(location: profile.php)
line. I had never heard of this issue before until now. So to resolve this issue, I just moved
<?php
...
include header.html
?>
to the bottom of the php code right before the HTML starts. Now the include header line can do it's thing and then the header will still be loaded for the page.
Thanks for all your help with this.