I have login and logout pages but cannot logout always says the user already logged-in. Here is my login page:
<?php
session_start();
include_once("connection.php");
if(isset($_POST) & !empty($_POST)) {
$userName = mysqli_real_escape_string($connection, $_POST['userName']);
$userPassword = md5($_POST['userPassword']);
$login = "SELECT * FROM `users` WHERE userName = '$userName' and password = '$userPassword'";
$result = $connection->query($login);
while ($val = mysqli_fetch_array($result))
{
$isAdmin = $val['isAdmin'];
$companyID = $val['companyID'];
$branchID = $val['branchID'];
$ID = $val['ID'];
}
$count = mysqli_num_rows($result);
if($count == 1){
$_SESSION['userName'] = $userName;
setcookie("userID", $ID);
setcookie("companyID", $companyID);
setcookie("branchID", $branchID);
if(!$isAdmin){
header('location: home.php');
}
else {
header('location: admin/home.php');
}
}
else {
$fmsg = "Wrong user name";
}
}
if(isset($_SESSION['userName'])){
$smsg = "Already loggedin";
}
?>
Here is loggout page:
<?php
session_start();
session_destroy();
unset($_COOKIE['companyID']);
unset($_COOKIE['userID']);
unset($_COOKIE['branchID']);
setcookie('companyID', null, -1, '/');
setcookie('userID', null, -1, '/');
setcookie('branchID', null, -1, '/');
header('location: index.php');
?>
How could I solve this? Could anyone help me? Also there is an attached image show cookies.
Just use this:
$_SESSION = array();
session_destroy();
Here you can do is
$_SESSION['userName'] = ''; //clear userName only
And Add this in your Code
if(isset($_SESSION['userName']) && $_SESSION['userName'] != ''){
$smsg = "Already loggedin";
}
or
unset($_SESSION); //all session will be gone
$_SESSION = array();
// unset cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
Hope this helps
Here my code its work for me
session_start();
unset($_SESSION['userid']);
unset($_SESSION['username']);
unset($_SESSION['photo']);
session_destroy();
unset($_COOKIE['userid']);
unset($_COOKIE['emailid']);
unset($_COOKIE['photo']);
setcookie('userid', null, -1, '/');
setcookie('emailid', null, -1, '/');
setcookie('photo', null, -1, '/');
header("Location:login");
I think problem is with Firefox that's worked with MS Edge. Thank you for all your helps my code is here:
logout:
<?php
session_start();
setcookie("branchID", "", 1);
setcookie("companyID", "", 1);
setcookie("userID", "", 1);
setcookie("userName", "", 1);
session_destroy();
header('location: index.php');
?>
login:
<?php
session_start();
include_once("connection.php");
if(isset($_POST) & !empty($_POST)) {
$userName = mysqli_real_escape_string($connection, $_POST['userName']);
$userPassword = md5($_POST['userPassword']);
$login = "SELECT * FROM `users` WHERE userName = '$userName' and password = '$userPassword'";
$result = $connection->query($login);
while ($val = mysqli_fetch_array($result))
{
$isAdmin = $val['isAdmin'];
$companyID = $val['companyID'];
$branchID = $val['branchID'];
$ID = $val['ID'];
}
$count = mysqli_num_rows($result);
if($count == 1){
$_SESSION['userName'] = $userName;
setcookie("userID", $ID);
setcookie("companyID", $companyID);
setcookie("branchID", $branchID);
if(!$isAdmin){
header('location: home.php');
}
else {
header('location: admin/home.php');
}
}
else {
$fmsg = "Hatalı Kullanıcı Adı/Şifre";
}
}
if(isset($_SESSION['userName']) && $_SESSION['userName'] != ''){
$smsg = "Kullanıcı Halihazırda Giriş Yapmış";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/lib/lobipanel/lobipanel.min.css">
<link rel="stylesheet" href="css/lib/jqueryui/jquery-ui.min.css">
<link rel="stylesheet" href="css/lib/font-awesome/font-awesome.min.css">
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<header class="site-header">
<div class="container-fluid">
<a href="#" class="site-logo">
<img class="hidden-md-down" src="img/logo-2.png" alt="">
<img class="hidden-lg-up" src="img/logo-2-mob.png" alt="">
</a>
<div class="site-header-content">
<div class="site-header-content-in">
<div class="site-header-shown">
<a href="#" class="site-logo">
<img class="hidden-md-down" src="img/logo-ds.png" alt="">
<img class="hidden-lg-up" src="img/logo-ds-mob.png" alt="">
</a>
</div><!--.site-header-shown-->
HOŞ GELDİNİZ
</div><!--site-header-content-in-->
</div><!--.site-header-content-->
</div><!--.container-fluid-->
</header><!--.site-header-->
<div class="form-style-6">
<h1>Giriş Yap</h1>
<form action="" method="post">
<input type="text" name="userName" placeholder="Kullanıcı Adı" />
<input type="password" name="userPassword" placeholder="Şifre" />
<input type="submit" value="Giriş Yap" />
</form>
</div>
<div class="container">
<?php if(isset($smsg)){ ?>
<div class="alert alert-success" role="alert"> <?php echo $smsg; ?></div>
<?php } ?>
<?php if(isset($fmsg)){ ?>
<div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?></div>
<?php } ?>
<?php if(isset($asmsg)){ ?>
<div class="alert alert-success" role="alert"> <?php echo $asmsg; ?></div>
<?php } ?>
<?php if(isset($afmsg)){ ?>
<div class="alert alert-danger" role="alert"> <?php echo $afmsg; ?></div>
<?php } ?>
</div>
</body>
</html>
Related
When user logged in, the login link on nav bar should be gone and logout link should appear how should i do it?
index.html:
<nav>
<p class="menu">Home</p>
<p class="menu">Products </p>
<p class="menu">Login</p>
<p class="menu">Logout</p>
</nav>
Login.php file:
<?php
require 'db.php';
session_start();
$password = $mysqli->escape_string($_POST['Pass']);
$email = $mysqli->escape_string($_POST['EmailAdd']);
$result = $mysqli->query("SELECT * FROM Account WHERE Usermail='$email'");
//check email in db
if ($result->num_rows == 0)
{
$_SESSION['message'] = "Email does not exist";
print '<script type="text/javascript">alert("' . $_SESSION['message'] .
'");
</script>';
header("Location: ../register.html");
}
else
{
//get user array
$user = $result->fetch_assoc();
if ($password == $user['password'])
{
$box = "Login successful";
$_SESSION['email'] = $user['Usermail'];
$_SESSION['logged_in'] = true;
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Login Successful')
window.location.href='../index.html';
</SCRIPT>");
}
else
{
$_SESSION['message'] = "Wrong password";
header("Location: ../account.html");
echo "failed";
echo '<script language="javascript">';
echo 'alert("Wrong password")';
echo '</script>';
}
}
?>
I've gone through some of the post in stack overflow and apply things like if (!isset($_SESSION['email'])) and else statement on my index.php but its not working and i don't know what's the prob
Ps Previously was using index.php, since its not working so i change it back to index.html
<?php
if(!isset($_SESSION['logged_in'])){?>
<p class="menu">Login</p>
<?php }
else
{?> <p class="menu">Logout</p>
<?php } ?>
try the above code, Hope this helps
Assuming your code is correctly validating the credential and setting the auth state in the session $_SESSION['logged_in'] = true;
You can do something like this:
<nav>
<p class="menu">Home</p>
<p class="menu">Products </p>
<?php if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true): ?>
<p class="menu">Logout</p>
<?php else: ?>
<p class="menu">Login</p>
<?php endif; ?>
</nav>
Try this in your nav:
<?php
if($_SESSION['logged_in'] == "true"){
echo '<p class="menu">Login</p>';
}
else {
echo '<p class="menu">Logout</p>';
}
?>
It is not working because you use the .html extension instead of .php
<nav>
<p class="menu">Home</p>
<p class="menu">Products </p>
<?php if(empty($_SESSION['logged_in'])){ ?>
<p class="menu">Login</p>
<?php } else{ ?>
<p class="menu">Logout</p>
<?php } ?>
</nav>
This should work:
<nav>
<p class="menu">Home</p>
<p class="menu">Products</p>
<p class="menu">
<?php if(isset($_SESSION['logged_in]) && $_SESSION['logged_in]) {?>
Logout
<?php } else { ?>
Login
<?php } ?>
</p>
</nav>
I want to know how to add the logged in user's id in url (like ?id=")
I have searched a bit on Google, but I couldn't find anything that worked.
Here's the PHP code:
<?php
include("nav.php");
require("app/management/config.php");
session_start();
if(!isset($_SESSION['login_user']))
{
header("Location: index");
}
?>
<!DOCTYPE html>
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<!--<link rel="stylesheet" href="../css/providers.css">-->
<link rel="stylesheet" href="../css/main.css">
<link rel="stylesheet" href="../css/main2.css">
<meta charset="UTF-8">
<header class="header__wrapper wrapper">
<a href="/" class="header__habbo__logo">
<h1 class="header__habbo__name" id="ga-linkid-habbo-large"></h1>
</a>
</header>
<body>
<?php
include("header.php");
?>
<div class="info-block-homes">
<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$query = "SELECT * FROM `users` WHERE username = '{$_SESSION['login_user']}'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_array($data);
echo '<h1><font color="Red">Your Public Information:</font></h1>';
echo '<font color="green">' . $motto . '</font><font color="white">' . $row['motto'] . ' </font></br>';
echo '<font color="green">' . $credits . '</font><font color="white">' . $row['credits'] . ' </font></br>';
echo '<font color="green">' . $pixels . '</font><font color="white">' . $row['pixels'] . ' </font></br>';
echo '<font color="green">' . $points . '</font><font color="white">' . $row['points'] . ' </font></br>';
echo '<font color="green">' . $rank . '</font><font color="white">' . $row['rank'] .'</font>';
echo '<div style="margin-top:-130px; margin-left:150px;"><img src="http://www.habbo.com/habbo-imaging/avatarimage?figure='.$row['look'].'\"></div>';
?>
</div>
<div class="badges-block">
<h1><font color="Red">Your Badges:</font></h1>
<?php
$login_session=$_SESSION['login_user'];
$sql = "SELECT
so.*,
sr.*
FROM users AS so
INNER JOIN users_badges AS sr ON so.id = sr.user_id WHERE username = '{$_SESSION['login_user']}';";
$result = $dbconfig->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<img src='badges/".$row["badge_code"].".gif'>";
}
} else {
echo "0 results";
}
$dbconfig->close();
?>
</div>
<?php
include("footer.php");
?>
<div id="arrow-up-logout-homes" class="mydiv2"><ul><li><font color="white">Log Out</font></li></ul></div>
<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$online = "1";
$query = "SELECT count(id) as 'total' FROM `users` WHERE online = '$online'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($data);
$online=$row['total'];
echo '<div id="online-me" class="mydiv3"><center><span id="stats">'.$online.' User(s) Online!</span> </center></div>';
?>
<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$query = "SELECT * FROM `users` WHERE username = '{$_SESSION['login_user']}'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_array($data);
header('Location: /homes?id='.$row['id']);
exit;
?>
</body>
</head>
</html>
login page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://d3hmp0045zy3cs.cloudfront.net/2.2.21/providers.css">
<?php
require("nav.php");
echo "<title>$title - $desc - $title</title>";
?>
<?php
require("app/management/config.php");
session_start();
if(isset($_SESSION['login_user']))
{
header("Location: me");
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password received from loginform
$username=mysqli_real_escape_string($dbconfig,$_POST['username']);
$password=mysqli_real_escape_string($dbconfig,$_POST['password']);
$securitykey=mysqli_real_escape_string($dbconfig,$_POST['securitykey']);
$sql_query="SELECT * FROM users WHERE username='$username' and password='$password' and securitykey='$securitykey'";
$result=mysqli_query($dbconfig,$sql_query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$count=mysqli_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
$_SESSION['login_user']=$username;
header("location: me");
}
else {
$result = '<div style="position:absolute; margin-left:400px;">Invalid username or password (do not forget the security key if you got one)</div>';
echo "$result";
}
}
?>
<link rel="stylesheet" href="../css/main.css">
<link rel="stylesheet" href="../css/main2.css">
<head>
<header class="header__wrapper wrapper">
<a href="/" class="header__habbo__logo">
<h1 class="header__habbo__name" id="ga-linkid-habbo-large"></h1>
</a>
</header>
<body>
<div class="login-block">
<form method="post" action="" name="loginform">
<input type="text" value="" placeholder="Username" id="username" name="username" />
<input type="password" value="" placeholder="Password" id="password" name="password" />
<input type="securitykey" value="" placeholder="Security Key" id="securitykey" name="securitykey" />
<button type="submit">Submit</button>
</form>
</div>
<body>
<?php
include("header.php");
?>
<div id="content">
<!--<?php
// Create connection
$sql = "SELECT id, message, username FROM cms_message";
$result = $dbconfig->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<marquee behavior="scroll" direction="left">'.$row['username'].' says: '.$row['message'].'</marquee>';
}
} else {
echo "0 results";
}
$dbconfig->close();
?>-->
<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$online = "1";
$query = "SELECT count(id) as 'total' FROM `users` WHERE online = '$online'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($data);
$online=$row['total'];
echo '<div id="online" class="mydiv3"><center><span id="stats">'.$online.' User(s) Online!</span> </center></div>';
?>
<div id="arrow-up" class="mydiv2"><ul><li><font color="white">Register Now!</font></li></ul></div>
</br>
</br>
</br>
</br>
</br>
</br>
<?php
{
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$query="SELECT * FROM cms_news WHERE highlighted = '1' AND date IN (SELECT max(date) FROM cms_news)";
$data = mysqli_query($con, $query);
while($row = mysqli_fetch_array($data))
{
echo '<main class="wrapper wrapper--content" ui-view="">
<section>
<h1 translate="NEWS_TITLE">Latest news</h1>
<div class="main main--fixed">
<habbo-compile data="NewsController.promos">
<section>
<article class="news-header news-header--column">
<a href="'.$row["link"].''.$row["room_id"].'" class="news-header__link news-header__banner">
<figure class="news-header__viewport">
<img src="'.$row["image"].'" alt="'.$row["image"].'" class="news-header__image news-header__image--featured">
<img src="'.$row["thumbnail"].'" alt="'.$row["thumbnail"].'" class="news-header__image news-header__image--thumbnail">
</figure>
</a>
<a href="/hotel?room='.$row["room_id"].'" class="news-header__link news-header__wrapper">
<h2 class="news-header__title">'.$row["title"].'</h2>
</a>
<aside class="news-header__wrapper news-header__info">
<time class="news-header__date">'.$row["date"].'</time>
<ul class="news-header__categories">
<li class="news-header__category">
'.$row["category"].'
</li>
</ul>
</aside>
<p class="news-header__wrapper news-header__summary">'.$row["description"].'</p>
</article>
</section>
</main> ';
}
mysqli_close($con);
}
?>
<?php
{
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$query="SELECT * FROM cms_news WHERE highlighted = '0'";
$data = mysqli_query($con, $query);
while($row = mysqli_fetch_array($data))
{
echo '<div style="margin-top:-30px;"><main class="wrapper wrapper--content" ui-view="">
<article class="news-header">
<a href="/community/article/21340/habboxs-summer-weekend-event" class="news-header__link news-header__banner">
<figure class="news-header__viewport">
<img src="'.$row["thumbnail"].'" alt="'.$row["thumbnail"].'" class="news-header__image news-header__image--thumbnail">
</figure>
</a>
<a href="'.$row["link"].''.$row["category"].'" class="news-header__link news-header__wrapper">
<h2 class="news-header__title">'.$row["title"].'</h2>
</a>
<aside class="news-header__wrapper news-header__info">
<time class="news-header__date">'.$row["date"].'</time>
<ul class="news-header__categories">
<li class="news-header__category">
'.$row["category"].'
</li>
</ul>
</aside>
<p class="news-header__wrapper news-header__summary">'.$row["description"].'</p>
</article>
</main>
</div>';
}
mysqli_close($con);
}
?>
</div>
</div>
<?php
include("footer.php");
?>
</body>
</head>
</html>
Try:
header("Location: index?id=".$id);
As php.net says you need to use exit after header
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
so use this code:
header('Location: /index?id='.$row['id']);
exit;
Use this code:
header('Location: index?id='.$row['id']);
exit;
Why my $_SESSION["products"] has been destroy after logged in, How do I keep my $_SESSION["products"] after I logged in?
Add product to cart before logged in.
After logged in my cart is empty.
CODE
login.php
<?php
ob_start();
session_start();
include 'init.php';
require_once 'config.php';
//initalize user class
$user_obj = new Cl_User();
if(!empty( $_POST )){
try {
$user_obj = new Cl_User();
$data = $user_obj->login( $_POST );
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
header('Location: home.php');
}
} catch (Exception $e) {
$error = $e->getMessage();
}
}
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
header('Location: home.php');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Smart Login Page</title>
<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<?php require_once 'templates/ads.php';?>
<div class="login-form">
<?php require_once 'templates/message.php';?>
<h1 class="text-center">Login</h1>
<div class="form-header">
<i class="fa fa-user"></i>
</div>
<form id="login-form" method="post" class="form-signin" role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="email" id="email" type="email" class="form-control" placeholder="Email" autofocus>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
<button class="btn btn-block bt-login" type="submit" id="submit_btn" data-loading-text="loging in....">Login</button>
<br>
</form>
<div class="form-footer">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-lock"></i>
Forgot Password?
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-check"></i>
Sign up
</div>
</div>
</div>
</div>
</div>
<!-- /container -->
<script src="js/jquery.validate.min.js"></script>
<script src="js/login.js"></script>
</body>
</html>
<?php ob_end_flush(); ?>
login function in User.php
public function login( array $data )
{
$_SESSION['logged_in'] = false;
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$email = mysqli_real_escape_string( $this->_con, $trimmed_data['email'] );
$password = mysqli_real_escape_string( $this->_con, $trimmed_data['password'] );
if((!$email) || (!$password) ) {
throw new Exception( LOGIN_FIELDS_MISSING );
}
$password = md5( $password );
$query = "SELECT member_id, member_display_name, member_email, member_status, roles_id FROM fm_member where member_email = '$email' and member_pwd = '$password' ";
//$query = "SELECT user_id, name, email, created, roles_id, id FROM users where email = '$email' and password = '$password'"
$result = mysqli_query($this->_con, $query);
$data = mysqli_fetch_assoc($result);
$count = mysqli_num_rows($result);
mysqli_close($this->_con);
if( $count == 1){
$_SESSION = $data;
if($_SESSION['member_status'] == 'Activated') {
$_SESSION['logged_in'] = true;
return true;
} else {
throw new Exception( 'Your account is Deactiavted! <br> Please contact to Adminnistrator for more information.' );
$_SESSION['logged_in'] = false;
}
}else{
throw new Exception( LOGIN_FAIL );
}
} else{
throw new Exception( LOGIN_FIELDS_MISSING );
}
}
cart_process.php
session_start(); //start session
include_once("config.inc.php"); //include config file
setlocale(LC_MONETARY,"en_US"); // US national format (see : http://php.net/money_format)
############# add products to session #########################
if(isset($_POST["product_code"]))
{
foreach($_POST as $key => $value){
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING); //create a new product array
}
//we need to get product name and price from database.
$statement = $mysqli_conn->prepare("SELECT fm_product.p_name, fm_product.p_price, fm_product.p_member_id, fm_product.p_discount, fm_member.member_display_name, fm_member.member_payment, fm_product_image.img_1, shipping_cost.shipping_register,
shipping_cost.shipping_normal, shipping_cost.shipping_ems FROM fm_product LEFT JOIN fm_member ON fm_member.member_id = fm_product.p_member_id LEFT JOIN fm_product_image ON fm_product_image.p_id_img = fm_product.p_id LEFT JOIN shipping_cost ON shipping_cost.shipping_vendor = fm_member.member_id WHERE p_id=?");
$statement->bind_param('s', $new_product['product_code']);
$statement->execute();
$statement->bind_result($product_name, $product_price, $p_member_id, $p_discount, $member_display_name, $member_payment, $img_1, $shipping_register, $shipping_normal,$shipping_ems);
while($statement->fetch()){
$new_product["p_name"] = $product_name; //fetch product name from database
$new_product["p_price"] = $product_price;
$new_product["p_member_id"] = $p_member_id;
$new_product["p_discount"] = $p_discount;
$new_product["member_display_name"] = $member_display_name;
$new_product["member_payment"] = $member_payment;
$new_product["img_1"] = $img_1;
$new_product["shipping_register"] = $shipping_register;
$new_product["shipping_normal"] = $shipping_normal;
$new_product["shipping_ems"] = $shipping_ems;
//fetch product price from database
if(isset($_SESSION["products"])){ //if session var already exist
if(isset($_SESSION["products"][$new_product['product_code']])) //check item exist in products array
{
unset($_SESSION["products"][$new_product['product_code']]); //unset old item
}
}
$_SESSION["products"][$new_product['product_code']] = $new_product; //update products with new item array
}
$total_items = count($_SESSION["products"]); //count total items
die(json_encode(array('items'=>$total_items))); //output json
}
################## list products in cart ###################
if(isset($_POST["load_cart"]) && $_POST["load_cart"]==1)
{
if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){ //if we have session variable
$cart_box = '<ul class="cart-products-loaded">';
$total = 0;
foreach($_SESSION["products"] as $product){ //loop though items and prepare html content
//set variables to use them in HTML content below
$product_name = $product["p_name"];
if(!empty($product["p_discount"]))
{
$product_price = $product["p_discount"];
} else if(empty($product["p_discount"])) {
$product_price = $product["p_price"];
}
$product_code = $product["product_code"];
$p_member_id = $product["p_member_id"];
$member_display_name = $product["member_display_name"];
$member_payment = $product["member_payment"];
$product["product_qty"] = 1;
$product_qty = $product["product_qty"];
$cart_box .= "<li>$product_name — Price ".$product_price." x ".$product_qty." = ".sprintf($product_qty * $product_price)."×</li>";
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
$cart_box .= "</ul>";
$cart_box .= '<div class="cart-products-total" style="border-top: 1px solid #C0C0C0;">'.$quantity.'Total : '.sprintf($total).'<u>Check Out</u></div>';
die($cart_box); //exit and output content
}else{
die("Empty Cart!"); //we have empty cart
}
}
EDIT
home.php added
<?php
session_start();
include('connect.php');
$ID = $_SESSION['member_id'];
if(!isset($_SESSION['logged_in'])){
header('Location: index.php');
}
?>
<?php require_once 'templates/header.php';?>
<?php if($_SESSION['roles_id']=='1') { ?>
<div class="content">
<div class="container">
<div class="col-md-8 col-sm-8 col-xs-12">
<br>
<h1 class="text-center"> Admin Page </h1>
<br>
</div>
<?php require_once 'templates/sidebar.php';?>
</div>
</div> <!-- /container -->
<?php } else if($_SESSION['roles_id']=='2') { ?>
<div class="content">
<div class="container">
<div class="col-md-8 col-sm-8 col-xs-12">
<br>
<h1 class="text-center"> User Page </h1>
<br>
</div>
<?php require_once 'templates/sidebar.php';?>
</div>
</div> <!-- /container -->
<?php } ?>
looks like $_SESSION = $data; may be your culprit, you're resetting the entire session variable with data.
EDIT
Where $_SESSION = $data is change it to this;
$data["products"] = $_SESSION["products"];
$_SESSION = $data;
I have my index.php page, which is where users can register and log in with sessions.
This is the error I'm getting:
Notice: Undefined index: username in C:\wamp\www\CMS\admin\index.php on line 18.
What's wrong with my code?
Short snippet of index.php:
Source code:
<?php include "includes/admin_header.php" ?>
<div id="wrapper">
<!-- Navigation -->
<?php include "includes/admin_navigation.php" ?>
<div id="page-wrapper">
<div class="container-fluid">
<!-- Page Heading -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">
Welcome To Admin
<small><?php echo $_SESSION['username'] ?></small>
</h1>
</div>
</div>
This is my login.php
Source code:
<?php include "db.php"; ?>
<?php session_start(); ?>
<?php
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// For login security
$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
$query = "SELECT * FROM users WHERE username = '{$username}' ";
$select_user_query = mysqli_query($connection, $query);
if(!$select_user_query){
die("QUERY FAILED: " . mysqli_error($connection));
}
while($row = mysqli_fetch_array($select_user_query)) {
$db_user_id = $row['user_id'];
$db_username = $row['username'];
$db_user_password = $row['user_password'];
$db_user_firstname = $row['user_firstname'];
$db_user_lastname = $row['user_lastname'];
$db_user_role = $row['user_role'];
}
if ($username !== $db_username && $password !== $db_user_password) {
header("Location: ../index.php");
} else if($username === $db_username &&
$password === $db_user_password) {
$_SESSION['username'] = $db_username;
$_SESSION['firstname'] = $db_user_firstname;
$_SESSION['lastname'] = $db_user_lastname;
$_SESSION['user_role'] = $db_user_role;
header("Location: ../admin");
}
else {
header("Location: ../index.php");
}
}
?>
On the first line of your PHP script, write this:
if (session_status !== PHP_SESSION_ACTIVE) {
session_start();
}
For debugging purposes, add
var_dump($_SESSION);
after the if { } block. You also have to be sure that the session exists in every file you want to use it. To simplify the process I'll give you a short example:
You create a header.php file where you put the if {} block from above.
Whenever you want to use the session in a script, you just include that header file on the first line of your script.
//header.php
if (session_status !== PHP_SESSION_ACTIVE) {
session_start();
}
//index.php
include 'header.php';
echo $_SESSION['username'];
//login.php
include 'header.php';
$_SESSION['username'] = 'John Doe';
I am continuosly getting this error:
Commands out of sync; you can't run this command now
I don't know why is this happening and none of the preivous questions are helping.
This is my code:
User.php
public static function GetUserFullName($username){
if(Utilities::IsValid($username)){
$username = Utilities::SafeString($username);
Database::OpenConnection();
$query = Database::$databaseConnection->prepare("SELECT Name FROM user WHERE Username = ?") or die(Database::$databaseConnection->error);
$query->bind_param("s", $username);
$result = $query->execute();
Database::CloseConnection();
if($result){
$query->bind_result($name);
$query->fetch();
$query->close();
return $name;
}
}else return -1;
}
Skill.php
public static function UpdateSkills($id, $skill, $action){
if(Utilities::IsValid($id) && Utilities::IsValid($skill) && Utilities::IsValid($action)){
$id = Utilities::SafeString($id);
$skill = Utilities::SafeString($skill);
$action = Utilities::SafeString($action);
Database::OpenConnection();
if($action == 'i'){
$skill = str_replace(" ", "", $skill);
$db = Database::$databaseConnection;
$skills = explode(",", $skill);
$query = "";
foreach ($skills as $s){
$query .= "INSERT INTO skill (User_ID,Skill) VALUES({$id},'{$s}');";
}
$result = $db->multi_query($query);
echo $db->error;
Database::CloseConnection();
if($result) return 1;
else return -1;
}else if($action == 'd'){
$query = Database::$databaseConnection->prepare("DELETE FROM Skill WHERE Skill = ? AND User_ID = ?");
$query->bind_param("si", $skill,$id);
$result = $query->execute();
Database::CloseConnection();
if($result && $query->num_rows >0) return 1;
else return -1;
}
}
return -1;
}
header.php
<?php
require_once 'Classes/UserLogin.php';
require_once 'Classes/User.php';
$user_fullname = User::GetUserFullName($_SESSION["username"]);
?>
<header>
<div class="welcome_area">
<p>
Welcome, <b><?php echo $user_fullname; ?> </b>
</p>
</div>
<div class="menu">
<nav>
<ul>
<li>My Profile
<ul>
<li><div>My Questions</div>
</li>
<li><div>Settings</div>
</li>
<li style="margin-bottom: 5px;"><div>Logout</div>
</li>
</ul>
</li>
<li>Inbox
</li>
<li>Notifications
</li>
</ul>
</nav>
</div>
</header>
<section id="container">
<br />
<div id="logo"></div>
<div id="content">
profile.php
<?php
require_once "Classes/User.php";
require_once "Classes/Skill.php";
require_once "Classes/UserLogin.php";
if(!UserLogin::IsLoggedIn("username")) header("location: login.php");
$user_details = User::GetUserDetails($_SESSION["username"]);
echo Skill::UpdateSkills(11, "programmer,designer", "i");
?>
<!DOCTYPE html>
<html>
<head>
<title>Help Exchange</title>
<link rel="stylesheet" href="css/base.css" />
<link rel="stylesheet" href="css/profile.css" />
<link rel="stylesheet" href="css/user.css" />
<link rel="stylesheet" href="css/widgets.css" />
<script src="js/jquery.min.js"></script>
<script src="js/profile.js"></script>
</head>
<body>
<script>
var user_details = eval(<?php echo $user_details; ?>);
var about = user_details.About;
</script>
<?php require_once 'admin/header.php';?>
Please help me :'(