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();
}
}
?>
Related
I have created a login system with php, mysql, and html. I am trying to figure out how to display a different home page with html code based on whether someone is logged in or not.
I have tried to display profile button on the header if they are logged in and if they are not logged in it displays Login/Signup on the header.
index.php
<?php session_start();
include('server.php');
if (isset($_SESSION['username'])){
?>
<!DOCTYPE html>
<html lang = "en">
<!--
Capstone Project "Zoeker"
Michael Burnett, Annie Lalor, Sophia Michael, Hannah Smith
5/6/2021
-->
<head>
<title>Home Page</title>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Stylesheets -->
<link rel="stylesheet" href="CSS/Normalize.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="CSS/Styles.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<!-- Menu Bar -->
<div class="topnav" id="myTopnav">
<img src="Images/Logo.png" alt="Zoeker">
About
Contact
Stores Near You
Profile
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
<!-- Strip container for opening home page -->
<div class = "strip1">
</div>
<!-- FOOTER Containers-->
<div class="footer">
<div class="footer-box">
<ul>
<li><img src="Images/Logo.png" alt="Zoeker"></li>
</ul>
</div>
<div class="footer-box">
<h2>Navigation</h2>
<ul>
<li>Stores</li>
<li>About Us</li>
<li>Contact</li>
</ul>
</div>
<div class="footer-box">
<h2>Service Areas</h2>
<ul>
<li>Bloomington</li>
</ul>
</div>
<div class="footer-box">
<h2>Contact Us</h2>
<ul>
<li>812-123-4567</li>
<li>Support#Zoeker.com</li>
</ul>
</div>
</div>
</body>
</html>
<?php
}else{
// not logged in
}
?>
<!DOCTYPE html>
<html lang = "en">
<!--
Capstone Project "Zoeker"
Michael Burnett, Annie Lalor, Sophia Michael, Hannah Smith
5/6/2021
-->
<head>
<title>Home Page</title>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Stylesheets -->
<link rel="stylesheet" href="CSS/Normalize.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="CSS/Styles.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<!-- Menu Bar -->
<div class="topnav" id="myTopnav">
<img src="Images/Logo.png" alt="Zoeker">
About
Contact
Stores Near You
Login/Signup
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
<!-- Strip container for opening home page -->
<div class = "strip1">
</div>
<!-- FOOTER Containers-->
<div class="footer">
<div class="footer-box">
<ul>
<li><img src="Images/Logo.png" alt="Zoeker"></li>
</ul>
</div>
<div class="footer-box">
<h2>Navigation</h2>
<ul>
<li>Stores</li>
<li>About Us</li>
<li>Contact</li>
</ul>
</div>
<div class="footer-box">
<h2>Service Areas</h2>
<ul>
<li>Bloomington</li>
</ul>
</div>
<div class="footer-box">
<h2>Contact Us</h2>
<ul>
<li>812-123-4567</li>
<li>Support#Zoeker.com</li>
</ul>
</div>
</div>
</body>
</html>
server.php
<?php
session_start();
$username = "";
$email = "";
$errors = array();
//Connect to the database
$conn = mysqli_connect("db.luddy.indiana.edu", "i494f20_team36", "my+sql=i494f20_team36", "i494f20_team36");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ";
}
//if the register button is clicked
if (isset($_POST['register'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
//Check database for username and email already in use
$sql_u = "SELECT * FROM users WHERE username='$username'";
$sql_e = "SELECT * FROM users WHERE email='$email'";
$res_u = mysqli_query($conn, $sql_u);
$res_e = mysqli_query($conn, $sql_e);
//ensure form fields are filled in
if(empty($username)){
array_push($errors, "Username is required");
}
if(empty($email)){
array_push($errors, "Email is required");
}
if(empty($password)){
array_push($errors, "Password is required");
}
if(mysqli_num_rows($res_u) > 0) {
array_push($errors, "Username is already taken");
}
if(mysqli_num_rows($res_e) > 0) {
array_push($errors, "Email is already taken");
}
//if no errors, insert new user into database
if (count($errors) == 0){
$sql = "INSERT INTO users(username, email, password)
VALUES ('$username', '$email', '$password')";
mysqli_query($conn, $sql);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php'); //redirect to home page
}
else{
echo "not quite, but you'll get it";
}
}
// log user in from login page
if (isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username)){
array_push($errors, "Username is required");
}
if (empty($password)){
array_push($errors, "Password is required");
}
if (count($errors) == 0){
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1){
// log user in
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php'); //redirect to home page
}else{
array_push($errors, "Wrong username/password combination");
}
}
}
?>
The else was empty and the html version for users that are not logged in was always shown. By moving the closing else-bracket to the end of the file, you get the 2 versions depending on the user being logged in or not.
<?php
}else{
// not logged in
// THE CLOSING BRACKET IS NOW AT THE BOTTOM
?>
<!DOCTYPE html>
<html lang = "en">
<!-- LINES DELETED FOR BREVITY ->
</body>
</html>
<?php } // MOVED CLOSING BRACKET TO THE END
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']:"" ;
?>
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;
My reports.php page keeps redirecting me back to the login page even though i have supposedly logged into the website. I am not quite sure what i might be doing wrong here.
reports page:
<?php require_once('dbadmin.php');?>
<?php
session_start();
$user = $_SESSION['users'];
if(!isset($users)){
header("Location:admin_login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>e</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<header><img src="images/eastersealsclevelogo.png" alt="Easter Seals Logo" width="445" height="300"</img> </header>
<nav>
<ul>
<li>Home</li>
<li>Run Sign-Up</li>
<li>Refer-a-Friend</li>
<li>Admin Login</li>
<li>Reports</li>
</ul>
</nav>
<h1>Reports</h1>
<table border="1" style="width:100%">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Distance</th>
</tr>
<?php
include('dbuser.php');
$select = "SELECT `fname`, `lname`, `email`, `distance` FROM runner ORDER BY `lname`";
$result = mysql_query($connect, $select) or die ('Oops! '.mysql_error($connect));
if($rowcnt==0){
echo "<tr><td colspan=3>There are currently no results.</td</tr>";}
while($row = mysql_fetch_assoc($result)) {
echo '<tr><td>'.$row['fname'].'</td>';
echo '<td>'.$row['lname'].'</td>';
echo '<td>'.$row['email'].'</td>';
echo '<td>'.$row['distance'].'</td></tr>';
}
?> </table>
<footer></footer>
</body>
</html>
adminlogin page:
<?php require_once('dbadmin.php');?>
<?php
session_start();
if(isset($_POST['adminlogin'])) {
$username = trim($_POST['user']);
$password = trim($_POST['password']);
include('dbadmin.php');
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysql_query($sql) or die("Invalid query: ".mysql_error());
if(mysql_num_rows($result)==0) {
$confirm = '<h2 style="color:red;">Invalid Credentials!</h2>';
} else {
$_SESSION['user'] = $username;
$confirm = '<h2> Login Successful</h2>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>My Gaming Products Site</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<header><img src="images/eastersealsclevelogo.png" alt="Easter Seals Logo" width="445" height="300"/> </header>
<nav>
<ul>
<li>Home</li>
<li>Run Sign-Up</li>
<li>Refer-a-Friend</li>
<li>Admin Login</li>
<li>Reports</li>
</ul>
</nav>
<h1>Enter Your Login Information</h1>
<?php if(isset($confirm)) echo $confirm; ?>
<form method="post" name="adminlogin" id="adminlogin" title="adminlogin" action="admin_login.php">
<p>User: <br> <input type="text" name="user"></p>
<p>Password: <br><input type="password" name="password"></p>
<p><input type="submit" name="adminlogin" id="adminlogin" value="Login"></p>
</form>
</p>
<footer>| WDD420</footer>
</body>
</body>
</html>
I think it might be something with my reports page but i am not sure if it has anything to do with the login page either.
Try to make your script a bit more readable, I suggest with a function:
<?php
function is_loggedin()
{
return (!empty($_SESSION['users']));
}
session_start();
if(!is_loggedin()){
header("Location:admin_login.php");
exit;
}
?>
By doing $user = $_SESSION['users'] then checking if $user is set, that will always be true because you set it. You will want to check empty().
In your adminlogin.php page the session variable is $_SESSION['user']. But in reports.php page it checks for $_SESSION['users']. Change that to $_SESSION['user'] and change the variable name to $user from $users.
session_start();
$user = $_SESSION['user'];
if(!isset($user)){
header("Location:admin_login.php");
}
Try checking users by this :
session_start();
if(!isset($_SESSION['users']) && empty($_SESSION['users'])){
header("Location:admin_login.php");
}
try this for check the variable is set or not :
session_start();
if(isset($_SESSION['users']) && !empty($_SESSION['users'])) {
print_r($_SESSION['users']);
}
Try this to also to check => var_dump($_SESSION['users']);
Put session_start(); at the first line of your php page.
Note : Also keep in mind, you need to call session_start(); on each and every page if you are making use of session variables.
I'm trying to create a mobile site and I'm using sessions to get the users username. When I view the mobile site on my desktop it works fine and I can get the username of the user from page to page. But when I view the same site on my mobile browser the session doesn't carry over from page to page.
Here is my login page:
<?php
//allow sessions to be passed so we can see if the user is logged in
session_start();
ob_start();
//connect to the database so we can check, edit, or insert data to our users table
$con = mysql_connect(***info to connect to database) or die(mysql_error());
$db = mysql_select_db('dbname', $con) or die(mysql_error());
//include out functions file giving us access to the protect() function made earlier
include "./functions.php";
$userid = $_SESSION['uid'];
$lookupusername = mysql_query("SELECT * FROM users WHERE ID='$userid'");
$row = mysql_fetch_assoc($lookupusername);
$username = $row['username'];
$usercountry = $row['country'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>15:11 Project Mobile</title>
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.css" />
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.0/css/font-awesome.css" rel="stylesheet">
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
</head>
<body>
<!-- BEGIN LOGIN PAGE -->
<div data-role="page" id="login" style="background: #c66200;">
<div data-role="header">
</div>
<div data-role="content">
<center>
<div class="ui-grid-b">
<img src="images/logo_white.png">
</div>
</center>
<?
//check if the login session does no exist
if(strcmp($_SESSION['uid'],'') == 1){
//if it doesn't display an error message
header('Location: feed.php');
}
else {
//If the user has submitted the form
if($_POST['submit']){
//protect the posted value then store them to variables
$username = protect($_POST['username']);
$thepassword = md5($_POST['password']);
$password = protect($thepassword);
//Check if the username or password boxes were not filled in
if(!$username || !$password){
//if not display an error message
echo "<center>You need to fill in a <b>Username</b> and a <b>Password</b>!</center>";
}else{
//if the were continue checking
//select all rows from the table where the username matches the one entered by the user
$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."'");
$num = mysql_num_rows($res);
//check if there was not a match
if($num == 0){
//if not display an error message
echo "<center>The <b>Username</b> you supplied does not exist!</center>";
}else{
//if there was a match continue checking
//select all rows where the username and password match the ones submitted by the user
$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."'");
$num = mysql_num_rows($res);
//check if there was not a match
if($num == 0){
//if not display error message
echo "<center>The <b>Password</b> you supplied does not match the one for that username!</center>";
}else{
//if there was continue checking
//split all fields fom the correct row into an associative array
$row = mysql_fetch_assoc($res);
//check to see if the user has not activated their account yet
if($row['active'] != 1){
//if not display error message
echo "<center>You have not yet <b>Activated</b> your account!</center>";
}else{
//if they have log them in
//set the login session storing there id - we use this to see if they are logged in or not
$_SESSION['uid'] = $row['id'];
//show message
echo "<center>You have successfully logged in!</center>";
//update the online field to 50 seconds into the future
$time = date('U')+50;
mysql_query("UPDATE `users` SET `online` = '".$time."' WHERE `id` = '".$_SESSION['uid']."'");
//redirect them to the usersonline page
$loginpage="#feed";
header("Location: feed.php" . $loginpage);
exit();
}
}
}
}
}
}
?>
<center>
<form action="index.php#feed" method="post" data-ajax="false">
<div style="width: 75%; border-top: 1px solid #ffffff; margin-top: 20px; padding-top: 20px; border-bottom: 1px solid #ffffff; margin-bottom: 20px; padding-bottom: 20px;">
<div class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="username" data-mini="true" style="color: #c66200;"/><br>
<label for="password">password:</label>
<input type="password" name="password" id="password" value="" placeholder="password" data-mini="true" style="color: #c66200;"/><br>
</div>
<div style="width: 40%;">
<input type="submit" data-role="button" name="submit" value="Login" data-mini="true" style="color: #c66200 !important;"/>
</div>
</div>
</center>
<?
ob_end_flush();
?>
</div>
<div data-role="footer">
</div>
</div>
<!-- END LOGIN PAGE -->
</body>
</html>
Here is what I have for my feed.php page which the login page routes to. I can get the users info on this page. Whenever I click a link to go to the "browseresults" page the information doesn't carry over.
<?php
//allow sessions to be passed so we can see if the user is logged in
session_start();
ob_start();
//connect to the database so we can check, edit, or insert data to our users table
$con = mysql_connect(***db info***) or die(mysql_error());
$db = mysql_select_db('dbname', $con) or die(mysql_error());
//include out functions file giving us access to the protect() function made earlier
include "./functions.php";
$userid = $_SESSION['uid'];
$lookupusername = mysql_query("SELECT * FROM users WHERE ID='$userid'");
$row = mysql_fetch_assoc($lookupusername);
$username = $row['username'];
$usercountry = $row['country'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>15:11 Project Mobile</title>
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.css" />
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
</head>
<body>
<!-- BEGIN PAGE 3 -->
<div data-role="page" id="browse">
<div data-role="panel" id="settingspanel" data-position="left" data-display="overlay">
<ul data-role="controlgroup">
<li>Page Two</li>
<li>Page Three</li>
<li>Page Four</li>
<li>Logout</li>
</ul>
</div>
<div data-role="header" data-position="fixed" data-theme="c" data-tap-toggle="false" data-id="foo1" style="padding-top: 5px; border-bottom: 1px solid #eccfb3; padding-bottom: 5px;">
<center><img src="images/logo_app_white.png" width="30px"></center>
</div>
<div data-role="content">
<?php
$fquery = "SELECT state, city, count(city) as num FROM needs WHERE country='$usercountry' AND status='posted' GROUP BY state, city ORDER BY state, city";
if ($result = mysql_query($fquery)) {
$num_rows = mysql_num_rows($result);
echo "<table>";
$i = 1;
$cols = 2;
$prev = "";
while ($frows = mysql_fetch_array($result)) {
$fcity = $frows['city'];
$fstate = $frows['state'];
$fcitycount = $frows['num']; // num is holding your count by city
if ($fstate != $prev) {
echo "<tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr><th align='left'>$fstate</th></tr><tr>";
}
echo "<td><a href='browseresults.php?city=$fcity&state=$fstate'>$fcity, $fstate ($fcitycount)</a> </td>";
echo ($i < $num_rows) ? ((($i % $cols) == 0) ? '</tr>' : '') : '';
$i++;
$prev = $fstate;
}
echo "</table>";
}
?>
</div>
<div data-role="footer" data-position="fixed" data-theme="c" data-tap-toggle="false" data-id="foo1" style="border-top: 1px solid #eccfb3; padding-top: 5px;">
<div data-role="navbar" style="background: #ce8339;">
<ul>
<li>My Feed</li>
<li>Submit</li>
<li>Browse</li>
<li>Projects</li>
</ul>
</div><!-- /navbar -->
</div>
</div>
<!-- END PAGE 3 -->
</body>
</html>
And here is the browseresults.php page which is the page that is not getting the session data.
<?php
//allow sessions to be passed so we can see if the user is logged in
session_start();
ob_start();
//connect to the database so we can check, edit, or insert data to our users table
$con = mysql_connect(***dbinfo***) or die(mysql_error());
$db = mysql_select_db(dbname, $con) or die(mysql_error());
//include out functions file giving us access to the protect() function made earlier
include "./functions.php";
$userid = $_SESSION['uid'];
$lookupusername = mysql_query("SELECT * FROM users WHERE ID='$userid'");
$row = mysql_fetch_assoc($lookupusername);
$username = $row['username'];
$usercountry = $row['country'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>15:11 Project Mobile</title>
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.css" />
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
</head>
<body>
<!-- BEGIN PAGE 1 -->
<?
echo "$username";
?>
<!-- END PAGE 1 -->
</body>
</html>
no username is outputted. Can anyone help explain why and help me get this sorted out please?