Sessions In PHP not working - php

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;

Related

Session gets destroyed after page refresh

Login.php
<?php
session_start();
$server = "localhost";
$user = "...";
$pass = "...";
$database = "...";
$verbindung = mysqli_connect($server, $user, $pass, $database)
or die("Verbindung konnte nicht hergestellt werden.");
$Email = $_POST["Email"];
$Passwort = $_POST["Passwort"];
$sql = "SELECT passwort FROM accounts WHERE email = '".$Email."'";
$hashPasswort = mysqli_query($verbindung, $sql);
$VerifyHash = mysqli_fetch_assoc($hashPasswort);
if(password_verify($Passwort, $VerifyHash['passwort']))
{
session_regenerate_id();
$_SESSION['email'] = $Email;
echo "<script type='text/javascript'>
window.location.replace('...');
</script>";
}
else
{
echo '<script type="text/javascript">
window.location.replace("...");
</script>';
}
$return = mysqli_close($verbindung);
if (!$return) {
echo "<p>Die Verbindung mit dem Server konnte nicht geschlossen werden.</p>";
}
?>
Index.php
<?php
session_start();
if (!isset($_SESSION['email'])) {
header('Location: Login.php?login=loginRequired');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=0.85">
<link rel="icon" type="image/png" href="../Bilder/favicon.ico"/>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Erste-Hilfe Kurs</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='../CSS/main.css'>
<link rel='stylesheet' type='text/css' media='screen' href='../CSS/index.css'>
</head>
<body>
<header>
<div class="container">
<img src="../Bilder/Litec.png" alt="Litec" class="logo">
<img src="../Bilder/RotesKreuz2.png" alt="Litec" class="logo">
<nav>
<ul>
<li><b><u>Home</u></b></li>
<li>Über uns</li>
<li>Anmeldung</li>
<li>Impressum</li>
<li>LOGOUT</li>
</ul>
</nav>
</div>
</header>
<label id="email"></label>
<?php echo("{$_SESSION['email']}"."<br />");?>
</body>
</html>
I made a Login script which opens, if the password is correct, the Index.php site. When first opening the Index.php site via the Login script everything works fine and the session is set. But after I refresh the page the sessions gets destroyed and is not set.
So how can I save the session, so it's not getting destroyed by refreshing the browser?
This line in your index.php destroys your session:
<li>LOGOUT</li>
^^^^^^^^^^^^^^^^^
To realize your logout process, you could link to another php file and do your session_destroy(); there - for example.

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']:"" ;
?>

Fetch row and display using sessions

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.

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();
}
}
?>

how to display user name after they login by their id number?

sorry if thie is duplication question, i did try to find the answer in internet and use it.. but i still can make it done... here my problem... i want to know how to display name when login using no id? it like welcome screen for the user after they login using their no id. here my code and sorry if it messed up...
my login.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="1234"; // Mysql password
$db_name="vronline"; // Database name
$tbl_name="user_information"; // Table name
// Connect to server and select databse.
$con = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE user_id='$myusername' and user_password='$mypassword'" ;
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
$row=mysql_fetch_array($result);
if ($row['group_id']==0){
header("location:../user.php");
}
elseif ($row['group_id']==1) {
header("location:../admin.php");
}
//header("location:../menu.php");
}
else {
echo "Wrong Username or Password";
}
?>
this is my user.php
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:../login_main.php");
}
?>
<?php
include ('php/dbconnect.php');
$matric = $_session['myusername'];
mysql_query("SELECT name FROM user_information WHERE user_id=".$_SESSION['myusername']);
?>
<html>
<head>
<title>user</title>
<link href="source/loginstyle.css" rel="stylesheet" type="text/css" media="all" />
<link href="source/kepala.css" rel="stylesheet" type="text/css" media="all" />
<link href="source/content.css" rel="stylesheet" type="text/css" media="all" />
<link href="source/menuBox.css" rel="stylesheet" type="text/css" media="all" />
<link href="source/bottomfoot.css" rel="stylesheet" type="text/css" media="all" />
<link href="source/accessibility_foundicons.css" rel="stylesheet" type="text/css" media="all"/>
<link href="source/general_foundicons.css" rel="stylesheet" type="text/css" media="all" />
<script src="source/Chart.js"></script>
</head>
<body>
<div>
<!--head-->
<div class= "kepala">
<h1>
<span class="foundicon-smiley"></span> <?php $row['name']; ?>
</h1>
</div>
<div class= "content">
<h4>content</h4>
<div class="menu">
<div class="menu_box_list">
<ul>
<li><span class="foundicon1-person"></span> manage user<i class="manageuser"> </i><div class="clear"></div> </li>
<li><span> </span>vehicle manager <i class="vehicle manager"> </i><div class="clear"></div> </li>
<li><span class= "foundicon-page"></span> report <i class="Report"> </i><div class="clear"></div> </li>
<li><span class= "foundicon-settings"></span> log out<i class="settings"> </i><div class="clear"></div> </li>
</ul>
<div class="clear"></div>
</div>
</div>
<div class = "2nd_menu">
</div>
</div>
<div class= "Bfooter">
<h4></h4>
</div>
</div>
</body>
</head>
</html
i cant solve around this code
mysql_query("SELECT name FROM user_information WHERE user_id=".$_SESSION['myusername']);
how i can make it appear name instead of user_id?
sorry i am not really good about this
sorry i forgot to add this
i want the user name display here
<a href="#"<span></span></a> <?php $row['name']; ?>
whenever i write i cant get the name on there.. it either not display anything or error
You may want to try this :
$qry_sel = "SELECT name FROM user_information WHERE user_id=".$_SESSION['myusername'].";";
$qry_res = mysql_query($qry_sel);
$row = mysql_fetch_array($qry_res);
echo $row['name'];
In your login.php page use this code
header("location:../user.php");
session_start();
$_SESSION['myusername']=$myusername;
And try this in user.php
ob_start("ob_gzhandler");
session_start();
$matric = $_session['myusername'];
$result=mysql_query("SELECT name FROM user_information WHERE user_id='$matric'");
if(mysql_num_rows($result)>0)
{
while($r=mysql_fetch_array($result))
{
$name=$r['name'];
echo $name;
}
}

Categories