Fetch row and display using sessions - php

been working on this project where I want people to login and when successful see info that we get from the database. I am not sure how to get the user email and other data stored to session
My problem is that I am struggling to store the data in sessions. I can sign in and echo the username that I created a session for, but the other data is not working.
I have gone through stacks of stuff on here, but obviously I am a little lost.
Here is the code for my checklogin.php
<?php
session_start();
ob_start();
include_once 'config.php';
// Connect to server and select databse.
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$db = new PDO('mysql:host='.$host.';dbname='.$db_name.';charset=utf8', $username, $password);
}
catch(Exception $e)
{
die('Error : ' . $e->getMessage());
}
// Define $myusername and $mypassword
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
$myemail =
// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$stmt = $db->query("SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'");
// rowCount() is counting table row
$count = $stmt->rowCount();
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1){
// Register $myusername, $mypassword and print "true"
echo "true";
$_SESSION['username'] = $myusername;
$_SESSION['email'] = $myemail;
}
else {
//return the error message
echo "<div class=\"alert alert-danger alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>Wrong Username or Password</div>";
}
ob_end_flush();
?>
and then my index.php looks like this
<?php
session_start();
if(!isset($_SESSION['username'])){
header("location:main_login.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
<link href="css/main.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
<div class="form-signin">
<div class="alert alert-success">You have been <strong>successfully</strong> logged in as <?php echo $_SESSION['username']; ?>. Your email is <?php echo $row['email']; ?></div>
Logout </div>
</div>
<!-- /container -->
</body>
</html>
Note that on index.php the username works fine when I echo it, but not the email.
Any help would be appreciated

This is supposed to be a comment, but i have a low reputation here.
First of all, please consider binding your values. PDO luckily has that functionality.Also as an observation, stripslashes does not totally prevent SQL injection.
From what i see, your email address is not saved in any session variable. This should fix,
$myemail = $_SESSION['name_of_email_from_database'];
Also do not forget, to access your session variables, include session_start() on every page that needs it. To prevent PHP's warning message of too many session starts, add the following code:
<?php
if(!isset($_SESSION)){
session_start();
}
?>

You can use query here to get all data for the session user, by select query.
$q= "select * from user where username = '$yoursessionusername'"
By this query you will get all details for the loggedin user.
Can create one session.php with below code:
session_start();
$username=$_SESSION['username'];
$email=$_SESSION['email'];
and can use those variables to your page.

Related

Missing responsiveness for button

I'm new to php and backend, I tried making a login and I wanted to buttons to change the background colour. Instead of using javascript, I use php to program it, to create sessions.
Below is the code. The buttons work in the url bar, but nothing is happening.
What am I missing or overseeing?
<?php
// Initialize the session
session_start();
require_once "config.php";
session_start();
require_once "config.php";
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$sql = "SELECT background FROM users ORDER BY id DESC";
$backgroundColour = [];
$colour = [];
$result = $link->query($sql);
$data = [];
while ($row = $result -> fetch_object()) {
$data[] = $row;
}
$backgroundColour['backgroundColour'] = $data;
$_SESSION['colour'] = $colour;
if(isset($_GET['colour'])){
$colour = $_GET['colour'];
$_SESSION['colour'] = $colour;
}
$colour_session = $_SESSION['colour'];
$sql = "INSERT INTO users (background) VALUES ('$colour_session')";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<h1>Choose background color</h1>
Hvid
Sort
</div>
<title>Welcome</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<h1 class="my-5">Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
<p>
Reset Your Password
Sign Out of Your Account
</p>
</body>
</html>
At least you need to tell the client side (the browser) that the background color is set as $_SESSION["color"] (e.g. black)
So, one of the ways is to add the following line to the end of your script (your script already has <body></body>) :
<?php
echo '<script>document.body.style.backgroundColor = "'. $_SESSION['colour'] . '";</script>';
?>
So, omitting the db part, the code (tested, fully working) will be
<?php
session_start();
if(isset($_GET['colour'])){
$colour = $_GET['colour'];
$_SESSION['colour'] = $colour;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<h1>Choose background color</h1>
Hvid
Sort
</div>
</body>
<?php
echo '<script>document.body.style.backgroundColor = "'. $_SESSION['colour'] . '";</script>';
?>
For the db part:
You may need to re-write the part on the db queries. For example, apart from the need to use parameterized prepared statement in your query (to avoid SQL injection attacks). Consider using "update user set background=? where id=?" instead of an insert query, For a multi-user system, it will be something like:
$sql = "UPDATE users SET background=? WHERE id=?";
$stmt= $link->prepare($sql);
$stmt->bind_param("si", $_SESSION['colour'], $_SESSION["id"]);
$stmt->execute();
It is because each user should have only a single record in the db table (so logically it is an update instead of an insert).

Web location read from mysql database by sessionID

this is my problem. each user should have specific "dashboard" and they should be blocked if user is not logged in. So user1 ==> login==> go to dasboard 1 etc. Dashboard locations are saved in mysql database in specific field. I am using login/sigup form in php and this works. when user is logged comes to welcome page.I want add iframe/content from link in db to be visible for that session user.
I tried loading session element, and displaying it but it dont works and I dont get any errors.
if($stmt->execute()){
// Check if username exists, if yes then verify password
if($stmt->rowCount() == 1){
if($row = $stmt->fetch()){
$id = $row["id"];
$page = $row["location"];
$username = $row["username"];
$hashed_password = $row["password"];
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION["location"] = $page;
// Redirect user to welcome page
header("location: welcome.php");
and this is welcome.php
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: log.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<div class="page-header">
<h1>Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?> </b>. Welcome to our site.</h1>
</div>
<?php echo $_SESSION ["location"]; ?>
<p>
Reset Your Password
Sign Out of Your Account
</p>

PHP Session and Cookie error in my Admin login page

I am working on Admin login page using PHP and MySQL. I am using XAMPP Control Panel v3.2.2 and Chrome browser.
I have used session and cookie in my admin login page but I have found following error
Notice: Undefined index: nam in C:\xampp\htdocs\online_voting\admin\index.php on line 3
Notice: Undefined index: pas in C:\xampp\htdocs\online_voting\admin\index.php on line 4
in my index.php page.
I can not find out cause of this error. What might be the problem?
This is my MySQL database connection page.
connection.php
<?php
error_reporting(1);
mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('poll') or die(mysql_error());
?>
For Login :
Email : admin#gmail.com
Password : admin
Database name is poll and table name is tbadministrators .
-- Table structure for table `tbadministrators`
--
CREATE TABLE IF NOT EXISTS `tbadministrators` (
`admin_id` int(5) NOT NULL AUTO_INCREMENT,
`first_name` varchar(45) NOT NULL,
`last_name` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
PRIMARY KEY (`admin_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `tbadministrators`
--
INSERT INTO `tbadministrators` (`admin_id`, `first_name`, `last_name`, `email`, `password`) VALUES
(1, 'Md. Rezwanul', 'Haque', 'admin#gmail.com', '21232f297a57a5a743894a0e4a801fc3');
-- --------------------------------------------------------
I have used following pages for admin login .
index.php
<?php
session_start();
$myusername = $_SESSION['nam'] ;
$mypassword = $_SESSION['pas'] ;
?>
<?php
if(isset($_COOKIE['$email']) && $_COOKIE['$pass']){
header("Location:admin.php");
exit;
}
?>
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Admin Login Form</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel='stylesheet prefetch' href='https://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
<link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>
<link rel="stylesheet" href="css/style.css">
<script language="JavaScript" src="js/admin.js">
</script>
</head>
<body style="background-image:url('images/demo/backgrounds/bCY7Scu.png');">
<div class="pen-title">
<h1>Admin Login Form</h1>
</div>
<div class="container" >
<div class="card"></div>
<div class="card">
<h1 class="title">Login</h1>
<form name="form1" action="checklogin.php" method="post" onsubmit="return loginValidate(this)">
<div class="input-container">
<input name="myusername" value="<?php echo $myusername ?>" type="text" required="required"/>
<label>Email</label>
<div class="bar"></div>
</div>
<div class="input-container">
<input name="mypassword" value="<?php echo $mypassword ?>" type="password" required="required"/>
<label>Password</label>
<div class="bar"></div>
</div>
<center><tr><td colspan="2" align="center"><input type="checkbox" name="remember" value="1"> <font color="blue">Remember Me</font></td></tr></center><br>
<div class="button-container">
<button name="Submit"><span>Login</span></button>
</div>
<br><br>
<center>Return to Voter Panel</center>
</form>
</div>
</div>
</body>
</html>
checklogin.php
<!DOCTYPE html>
<html>
<body style="background-color:powderblue;">
<?php
//session_start();
ini_set ("display_errors", "1");
error_reporting(E_ALL);
ob_start();
session_start();
require('../connection.php');
$tbl_name="tbAdministrators"; // Table name
/*
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$encrypted_mypassword=md5($mypassword);
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
*/
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$encrypted_mypassword=md5($mypassword);
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE email='$myusername' and password='$encrypted_mypassword'" or die(mysql_error());
$result=mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result);
if($count==1){
// If everything checks out, you will now be forwarded to admin.php
// $user = mysql_fetch_assoc($result);
// $_SESSION['admin_id'] = $user['admin_id'];
// header("location:admin.php");
if(isset($_POST['remember']))
{
setcookie('$email',$_POST['myusername'], time()+30*24*60*60);
setcookie('$pass', $_POST['mypassword'],time()+30*24*60*60);
$_SESSION['curname']=$myusername;
$_SESSION['curpass']=$mypassword;
$user = mysql_fetch_assoc($result);
$_SESSION['admin_id'] = $user['admin_id'];
header("Location:admin.php");
exit;
}
else
{
$log1=11;
$_SESSION['log1'] = $log1;
$_SESSION['curname']=$myusername;
$_SESSION['curpass']=$mypassword;
$user = mysql_fetch_assoc($result);
$_SESSION['admin_id'] = $user['admin_id'];
header("Location:admin.php");
exit;
}
}
//If the username or password is wrong, you will receive this message below.
else {
echo "<br> <br> <br> ";
echo "<center> <h3>Wrong Username or Password<br><br>Return to login </h3></center>";
}
ob_end_flush();
?>
</body>
</html>
admin.php
<?php
session_start();
require('../connection.php');
$log1 = $_SESSION['log1'];
?>
<?php
if(isset($_COOKIE['$email']) && $_COOKIE['$pass']){
$curnam = $_SESSION['curname'];
$curpas = $_SESSION['curpass'];
}
else if($log1 == 11)
{
$curnam = $_SESSION['curname'];
$curpas = $_SESSION['curpass'];
}
else
{
echo '<img src="e1.jpg" width="100%" height="100%" />'; /* here goes the page when destroy the cookies */
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>online voting</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link href="layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
<script language="JavaScript" src="js/user.js">
</script>
</head>
<body id="top">
<div class="wrapper bgded overlay" style="background-image:url('images/demo/backgrounds/background1.jpg');">
<section id="testimonials" class="hoc container clear">
<h2 class="font-x3 uppercase btmspace-80 underlined"> Online Voting</h2>
<ul class="nospace group">
<li class="one_third">
<blockquote>In this page, Admin can set candidates for voting and view results.</blockquote>
</li>
</ul>
</section>
</div>
<!-- JAVASCRIPTS -->
<script src="layout/scripts/jquery.min.js"></script>
<script src="layout/scripts/jquery.backtotop.js"></script>
<script src="layout/scripts/jquery.mobilemenu.js"></script>
<!-- IE9 Placeholder Support -->
<script src="layout/scripts/jquery.placeholder.min.js"></script>
<!-- / IE9 Placeholder Support -->
</body>
</html>
logout.php
<?php
session_start();
//session_destroy();
/*header("location: index.php");
exit;*/
if( isset($_COOKIE['$email']) and isset($_COOKIE['$pass'])){
setcookie('$email',' ',time()-30*24*60*60);
setcookie('$pass',' ',time()-30*24*60*60);
$nam=$_COOKIE['$email'];
$pas=$_COOKIE['$pass'];
$_SESSION['nam'] = $nam;
$_SESSION['pas'] = $pas;
header("location: index.php");
exit;
}
else
{
header("location: index.php");
exit;
}
?>
PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"
From their solutions could not help me properly.
When you first time visit the page at that time your value not set in session. So you have to check first if value is set or not then assign the value. Change the following in index.php:
<?php
session_start();
$myusername = isset($_SESSION['nam'])?$_SESSION['nam']:"" ;
$mypassword = isset($_SESSION['pas'])?$_SESSION['pas']:"" ;
?>

Sessions In PHP not working

okay so I am getting users to sign in and then "if successful" I redirect them to index.php where I would like to display some info from the database.
my users are validated and I can log in but I think I having issues with the Session.
The user name session does not display any info when I call it on the index.php page.
I am new to php and learning as I go. I have spent the last two days browsing this site for answers to my issue, but can't find anything that really works.
Here is the code
checklogin.php
<?php
session_start();
ob_start();
include_once 'config.php';
// Connect to server and select databse.
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$db = new PDO('mysql:host='.$host.';dbname='.$db_name.';charset=utf8', $username, $password);
}
catch(Exception $e)
{
die('Error : ' . $e->getMessage());
}
// Define $myusername and $mypassword
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$stmt = $db->query("SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'");
// rowCount() is counting table row
$count = $stmt->rowCount();
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1){
// Register $myusername, $mypassword and print "true"
echo "true";
$_SESSION['username'] = 'myusername';
$_SESSION['password'] = 'mypassword';
}
else {
//return the error message
echo "<div class=\"alert alert-danger alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>Wrong Username or Password</div>";
}
ob_end_flush();
?>
index.php
<?php
session_start();
if(!isset($_SESSION['username'])){
header("location:main_login.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
<link href="css/main.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
<div class="form-signin">
<div class="alert alert-success">You have been <strong>successfully</strong> logged in <?php echo $_SESSION['username']; ?>.</div>
Logout </div>
</div>
<!-- /container -->
</body>
</html>
I would really appreciate any help or links to articles that can help.
Thanks
Sean
Just change $_SESSION['username'] = 'myusername'; to $_SESSION['username'] = $myusername;

PHP Session doesn't exist on index.php

I get this error while checking for user session on index.php. Once a user has logged on, I want to display a "Log out" button in the menu. This is the code:
session.php
<?php
include('config.php');
session_start();
$user_check = $_SESSION['login_user'];
$ses_sql = mysqli_query($db,"select username from users where username = '$user_check' ");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_session = $row['username'];
?>
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
include('session.php');
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="/css/main.css" />
<title>LVRP</title>
</head>
<body>
<div id="top-line"></div>
<div id="header">
<div class="wrapper">
<div class="logo"> </div>
</div>
</div>
<div id="menu">
<div class="wrapper">
<ul id="navigation">
<li><a class="active" href="index.php">Home</a></li>
<li><a class="inactive" href="/forum" target="_blank">Forums</a></li>
<li><a class="inactive" href="ucp.php">User Control Panel</a></li>
<?php if(isset($_SESSION['login_user'])){echo('<li><a class="inactive" href="logout.php">Log out</a></li>');} ?>
</ul>
</div>
</div>
<div id="content">
</div>
</body>
</html>
It returns Notice: Undefined index: login_user in /var/www/html/session.php on line 5 on index.php
"It dies with a blank page."
Enable errors using
ini_set('display_errors', 'On');
At the top of your page, in your PHP tags and post the error.
try the following corrections:
<?php
include("config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT ID FROM users WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
//$active = $row['active'];
$active = $row['ID'];
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
// This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. (From: http://php.net/manual/en/function.session-register.php)
//session_register("myusername");
$_SESSION['login_user'] = $myusername;
header("location: ucp.php");
}else {
$error = "Wrong username/password.";
echo "<pre>";var_dump($error);exit();
}
}
?>

Categories