I want to use the result of a mysql query to set a session variable however at present I am struggling to make it set.
My code I have is:
<?php
ob_start("ob_gzhandler");
?>
<?php
// Include required MySQL configuration file and functions
require_once('config.inc.php');
require_once('functions.inc.php');
// Start session
session_start();
// Check if user is already logged in
if ($_SESSION['logged_in'] == true) {
// If user is already logged in, redirect to main page
redirect('../index.php');
} else {
// Make sure that user submitted a username/password and username only consists of alphanumeric chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
(!ctype_alnum($_POST['username'])) ) {
redirect('../login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
if (mysqli_connect_errno()) {
printf("Unable to connect to database: %s", mysqli_connect_error());
exit();
}
// Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// Construct SQL statement for query & execute
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . md5($password) . "'";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;
redirect('../index.php');
} else {
// If number of rows returned is not one, redirect back to login screen
redirect('../login.php');
}
}
?>
I am then testing the session variables with:
<?php
session_start();
echo "Login Status is:".$_SESSION['logged_in'];
echo "<br/>";
echo "Auth status is level:".$_SESSION['auth_lvl'];
?>
On my testing page the session logged in works fine displaying the correct information however the auth lvl variable displays nothing.
I can only assume that I am not calling the information correctly that I am setting the variable with in the first place.
Any help would be appreciated.
Alan.
Something I have notice and I have been trying the suggestions is that if I set a definative rather than trying to retreive a value from the database that value will return on my test page. i.e.
$_SESSION['auth_lvl'] = 'test';
This tells me it is the way in which I am pulling the data from the database and trying to set it as $_SESSION['auth_lvl'] that is causing the problem.
Found the problem.
the code read:
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// ADD THIS SET OF LINES
$data = mysql_fetch_assoc( $result );
// Replace auth_lvl with the name of your database column name
$Auth_lvl = $data['Auth_lvl'];
// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;
Because I had used mysqli on this code I had not notice that on the //ADD THIS SET OF LINES piece of code that an 'i' was missing. When I changed the code to:
$data = mysqli_fetch_assoc( $result );
Everything fired into life.
Thanks for your help guys.
I can't see anywhere that you have assigned $Auth_lvl with a value, so when you do:
$_SESSION['auth_lvl'] = $Auth_lvl;
It's presumably getting assigned null.
I'm not seeing where you are setting $Auth_lvl. After you check for the results being there, and rows, you're going straight to setting a session variable against an empty variable.
if (is_object($result) && $result->num_rows == 1) {
// ADD THIS SET OF LINES
$data = mysql_fetch_assoc( $result );
// Replace auth_lvl with the name of your database column name
$Auth_lvl = $data['auth_lvl']'
// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;
redirect('../index.php');
Then with your logged_in session variable, you're setting it as a boolean, true, and then trying to echo it out as normal text.
if ( $_SESSION['logged_in'] ) { echo "Login status is: True"; }
I hope that helps.
-Dan
Related
My issue is that for some reason on the login.php page of my website, I initialize some $_Session Variables from my users table in the corresponding database, but while these variables seem to function properly on other pages I can't do anything with them immediately after initializing them, because they don't seem to exist. This is an issue because I would like to reference the variables I have defined to create other session variables for efficiency, and because I would like to use it for a welcome message like the simple example shown in my code. Here is the code in question:
if(isset($_POST['user_email']) && !empty($_POST['user_email']) AND isset($_POST['user_pass']) && !empty($_POST['user_pass']))
{
$email = mysqli_real_escape_string($link, $_POST['user_email']); // Set variable for the username
$password = mysqli_real_escape_string($link, sha1($_POST['user_pass'])); // Set variable for the password and convert it to an sha1 hash.
$result = mysqli_query($link, "SELECT user_email, user_pass, user_active FROM users WHERE user_email='".$email."' AND user_pass='".$password."' AND user_active='1'") or die(mysqli_error($link));
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysqli_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_uuid'] = $row['user_uuid'];
$_SESSION['user_level'] = $row['user_level'];
$_SESSION['user_rank'] = $row['user_level'];
}
echo 'Welcome, ' . $_SESSION['user_uuid'] . '. <br />Proceed to the forum overview.';
}
}
}
I have session_start(); at the top of my connect.php which is included at the top of the signin.php doc.
The result of this code on this page is something like:
Welcome, .
Proceed to the forum overview.
However if I run it on a different page on the site it properly prints, i.e.:
Welcome, username.
Proceed to the forum overview
Thanks.
As this page is owned by it users, so it has each credentials to enter it which it is by using login form of php (that's what I know so far, I am not very good in php, to be honest).
The problem I do really guess about this must be in the using of session function (and this is the most complicated things to me know, I am not very familiar of using this.)
In the config of the form, I set the session like this (Well, I just copy paste the code from somewhhere) as follow:
// User Redirect Conditions will go here
if($count==1)
{
// Save type and other information in Session for future use.
$_SESSION[type]=$row[0];
$_SESSION[Region]=$row[1];
$_SESSION[myemail]=$myemail;
// if user type is ACTAdmin only then he can access protected page.
if($row[0] == 'ACTAdmin') {
header( "location:index.php");
}
else {
header( "location:login.html");
}
}
else
{
header("location:login.html");
}
// Closing MySQL database connection
$dbh = null;
In the head of the home page (and in each all related pages), I write a session start there like this:
<?php
include('UserSessionAdmin.php');
?>
In which it will get the data from UserSessionAdmin.php:
<?php
session_start();
if($_SESSION[type]!='ACTAdmin'){
header('location:login.html');
exit();
}
include('configPDO.php');
?>
What is included in the configPDO.php is here:
<?php
// mysql hostname
$hostname = 'mysql.com';
// mysql username
$username = 'alkushh';
// mysql password
$password = 'alkush';
// Database Connection using PDO
try {
$dbh = new PDO("mysql:host=$hostname;dbname=user", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
It's been more than two days for me just to solve it but I don't have any idea how to. Some people who are experts in here may help me with this thing, please.
Thank you and regards,
Here is the full script that define the $count==1
<?php
// Start Session because we will save some values to session varaible.
session_start();
// include connection file
include("configPDO.php");
// Define $myusername and $mypassword
$myemail=$_POST['myemail'];
$mypassword=$_POST['mypassword'];
// We Will prepare SQL Query
$STM = $dbh->prepare("SELECT Type,Region FROM user WHERE myemail = :myemail AND mypassword = :mypassword");
// bind paramenters, Named paramenters alaways start with colon(:)
$STM->bindParam(':myemail', $myemail);
$STM->bindParam(':mypassword', $mypassword);
// For Executing prepared statement we will use below function
$STM->execute();
// Count no. of records
$count = $STM->rowCount();
//just fetch. only gets one row. So no foreach loop needed :)
$row = $STM -> fetch();
// User Redirect Conditions will go here
if($count==1)
.....
.....
Here it is
if ( $count == 1 ) {
$_SESSION['login_id'] = $row['id']; // i prefer to name it login_id, you can use $row['id'] or $row[0]. but i prefer to write with the column name
if ( $_SESSION['login_id'] == 1 ) { // it means if login id = 1 then go to index.php
header("location: index.php");
} else {
header("location: login.html");
}
}
else { header("location: login.html"); }
i cut session region because you didnt have a region column and also i cut session myemail because you didnt need it
UserSessionAdmin.php
<?php
session_start();
if ( $_SESSION['login_id'] == 0 || $_SESSION['login_id'] == '' ) {
header('location: login.html');
exit();
}
require_once('configPDO.php');
?>
Please turn on your error reporting to see, that there is no constants such as type, Region, myemail. Use " or ' around parameter of session:
if (strcmp($_SESSION['type'], 'ACTAdmin') !== 0) {
header('location:login.html');
exit();
}
I have created the following scenario.
I have the index.php file which shows the mainpage. On this there are two fields - User Id and password enclosed in a form tag. The submit button calls the login.php file.
Login.php validates the user id, password etc
Once validation is successful, I want the login.php page to take me to MyDashboard.php page (passing the User Id and Password along).
I tried Header in PHP but does not work. I also tried to do a Javascript window.location.href and tried to call it on $(document).ready but nothing happens.
Please help.
--- Edit ----
here is the code after modification
<?php
include_once('./library/Common.php');
$_EmailId = trim($_POST['validemailid']);
$_Password = trim($_POST['password1']);
$_Rememberme = trim($_POST['rememberme']);
// Get the username from the Email Id by searching for #
$_UName= substr($_EmailId, 0, strpos($_EmailId, '#'));
$_Password = md5($_Password);
session_start();
$_SESSION['username'] = $_UName;
$query = "select username, firstname, password_hash,userstatus from users where username = ? and emailid = ?";
$dbconn = new mysqli('localhost', 'root', '','myDB');
if($dbconn->connect_errno)
{
print getHTML('ERROR', "Error in connecting to mysql".$dbconn->connect_error);
}
if(!($stmt=$dbconn->prepare($query)))
{
print getHTML('ERROR',"error in preparing sql statement".$dbconn->error);
}
if(!($stmt->bind_param('ss',$_UName,$_EmailId)))
{
print getHTML('ERROR',"error in binding params in sql statement".$stmt->error);
}
if(!$stmt->execute())
{
print getHTML('ERROR',"Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
$result=$stmt->get_result();
$row = $result->fetch_assoc();
$_dbpwd = $row['password_hash'];
$_userstatus = $row['userstatus'];
$errstatus = false;
if ($row['username'] != $_UName)
{
print getHTML('ERROR',"User does not exist with the given email id: ".$_EmailId);
$errstatus = true;
}
if(($row['password_hash'] != $_Password) && !$errstatus)
{
print getHTML('ERROR',"Password does not match");
$errstatus = true;
}
if(($row['userstatus'] != 'ACTIVE') && !$errstatus)
{
print getHTML('ERROR',"User is inactive. Please check your email for activation");
$errstatus = true;
}
if(!$errstatus)
{
$_SESSION['firstname'] = $row['firstname'];
$chksession = "SELECT sessionid FROM USERSESSIONS WHERE USERNAME = ? AND ENDDATE IS NULL";
if(!($sessionstmt=$dbconn->prepare($chksession)))
{
print "error in preparing sql statement".$dbconn->error;
exit();
}
$sessionstmt->bind_param('s',$_UName);
$sessionstmt->execute();
$sessionresult=$sessionstmt->get_result();
$sessionrow= $sessionresult->fetch_assoc();
$currdate = date('y-m-d H:i:s');
if($sessionrow['sessionid'] == 0)
{
$insertstmt = $dbconn->query("INSERT INTO USERSESSIONS(USERNAME,STARTDATE,ENDDATE) VALUES ('".$_UName."','".$currdate."',null)");
$insertstmt->close();
}
}
$sessionstmt->close();
$stmt->close();
$dbconn->close();
header("Location :MyDashboard.php");
exit;
?>
--- End of Edit -----
Amit
You should use session variables to store variables within a login session. Passing a password along to other pages is not recommended, nor necessary. Read up on Sessions, and take a look at already existing login scripts. Below is a very simple example, redirecting to the next page using the header() function.
<?php
// Validate user credentials and save to session
session_start();
$_SESSION['userId'] = $userId;
// Redirect to next page
header("Location: dashboard.php");
// Make sure that code below does not get executed when we redirect
exit;
?>
If user authenticated,
In PHP:
header('Location:MyDashboard.php');
Try include()
This function allows you to include code from other php scripts.
The header function is the correct way. As long as you don't have any output before calling the header function, it should work.
http://us3.php.net/manual/en/function.header.php
Post your code, and let's see what it is that isn't working!
Header should work in your condition.
Tou can use following code:
header("Location:filename");
exit();
I have a slight problem with my log in script in PHP. When a user logs in, it only works after the second try, there is no error but it just looks like the user entered the wrong password on the first attempt.
Sometimes when I've been testing the site, after i try log in in the first time it sends me back to the log in page. Then I manually enter the url of the home page it will let me go there sometimes. (There's some php at the top that checks if the user is logged in already so im guessing sometimes the log in script sets the SESSION to true)
Majority of the time it doesn't do that though. It will just redirect me back to the log in with out printing the error message. I believe the problem is at the top of the home page and not with the log in script because after removing the redirect if mysql doesn't return a row with a user/password match it will direct me to the log in page anyways.
Here is my login script
<?php
session_start();
// Include required MySQL configuration file and functions
// Check if user is already logged in
if (isset($_SESSION['logged_in'])) {
// If user is already logged in, redirect to main page
redirect('home.php');
}
else {
// Make sure that the user submitted a username/password and username
// only consists of alphanumeric Chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
( !ctype_alnum($_POST['username'])) ) {
redirect('login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_errno()) { printf ("Unable to connect to database %s",
mysqli_connect_error());
exit();
}
//Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// construct SQL statement for query & execute
$sql = "SELECT * FROM peeps WHERE name = '" . $username . "'
AND pword = SHA1('" . $password . "') ";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid.
if ($result->num_rows == 1 ) {
// Set the session variable for login status to true
$_SESSION['logged_in'] = true;
$_SESSION['name'] = $username;
echo "successfull ";
redirect('home.php');
}
else {
echo "didnt return row<hr>";
redirect back to login page.
redirect('loginPage.php');
}
}
?>
And here is the code at the top of my home page..
<?php
// Start session
session_start();
// Include required functions file
require_once('functions.php');
// Check login status... if not logged in redirect to login screen
if (check_login_status() == false) {
redirect('loginPage.php');
}
$username = $_SESSION['name'];
?>
Any help would be appreciated, if you want to a little more clarification on what I mean you can sign up for gateKeeper and see what I'm talking about.
Also this is my first question so any comments on how I asked it would be appreciated.
Thanks!
Try debugging it by replacing
if (check_login_status() == false) {
redirect('loginPage.php');
}
with
if (!isset($_SESSION['name'])) { #could be any session variables that you like..
redirect('loginPage.php');
}
or do print_r($_SESSION) on top of your homepage.
I assume that the first page is the script that processes the form from loginPage.php (or loginPage.php itself) and the second one the page that you access after being authenticated.
If I'm not mistaken, the problem seems to be that sometimes you are not correctly identified and that's redirecting you to your login again. Can you show us how the code for the check_login_status() function?
I have a simple login form in which if an error occurs such as wrong password, I need it to be able to remember the username which was entered. Would I Go about doing this PHP or Javascript as I am not allowed to use JQuery.
My current PHP - (Not Including the HTML Form)
<?php
//MySQl Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("clubresults") or die(mysql_error());
//Initiates New Session - Cookie
session_start(); // Start a new session
// Get the data passed from the form
$username = $_POST['username'];
$password = md5($_POST['pass']);
// Do some basic sanitizing
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
//Performs SQL Query to retrieve Login Details from DB
$sql = "select * from admin_passwords where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
//Assigns a Variable Count to 0
$count = 0;
//Exectues a loop to increment on Successful Login
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
//If count is equal to 1 Redirect user to the Members Page and Set Cookie
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
header("Location: members.php"); // This is wherever you want to redirect the user to
} else {
//Else Echo that login was a failure.
die('Login Failed. <a href=login.php>Click Here to Try Again</a>');
}
?>
Any help would be appreciated. Cheers
You could use $_SESSION or $_COOKIE.
For $_COOKIE, just use setcookie(...) (for localhost, on $domain, use false)
For $_SESSION, just set it like any other array
To check for existence of the value, use isset(...).
Don't use session variable..you can achieve this by passing username as parameter to login form when login fails its means..
//Else Echo that login was a failure.
die('Login Failed. Click Here to Try Again');
in form
if (isset($_GET['username']) set it into login username field otherwise keep it empty