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';
Related
I currently have 2 different navbars. One with Login and Sign up at the top and one with Account. I want the navbar to change to the one with Account after a user is logged in. My registration and login system is already working, so that won't have to change (connected to a database). Don't mind the names, it's for a school project.
These are my 2 navbars:
<div class="navbar">
<a class="active" href="Boomba.php">Boomba</a>
<div class="dropdown">
<button class="dropbtn">Boomba News
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
New News
Dead News
</div>
</div>
Boomba Store
Contact
<div class="floatr">
Sign Up
Login
Account
</div>
</div>
I currently have this at the top of the page:
<?php
session_start();
?>
Please let me know if there's an easier way overall to make this happen as well, this is my first website.
Thanks in advance :)
Edit:
My config file:
<?php
define('DB_SERVER', '-');
define('DB_USERNAME', '-');
define('DB_PASSWORD', '-');
define('DB_NAME', '-');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
My Login file:
<?php
session_start();
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: welcome.php");
exit;
}
require_once "0config.php";
$username = $password = "";
$username_err = $password_err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
if(empty($username_err) && empty($password_err)){
$sql = "SELECT id, username, password FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "s", $param_username);
$param_username = $username;
if(mysqli_stmt_execute($stmt)){
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
session_start();
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
header("location: welcome.php");
} else{
$password_err = "The password you entered was not valid.";
}
}
} else{
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
mysqli_stmt_close($stmt);
}
mysqli_close($link);
}
?>
You are duplicating a lot of code for your navbar here. You could do something like this if the other parts of your navbar don't need to change :
<div class="navbar">
<a class="active" href="Boomba.php">Boomba</a>
<div class="dropdown">
<button class="dropbtn">Boomba News
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
New News
Dead News
</div>
</div>
Boomba Store
Contact
<div class="floatr">
<?php if (isset($_SESSION['loggedin']) && $_SESSION['loggedin']): ?>
Account</li>
<?php else: ?>
Sign Up</li>
Login</li>
<?php endif; ?>
</div>
</div>
After the login operation, you must load the user-specific data to $_SESSION array. Imagine you have stored the user data to $_SESSION then you can check the $_SESSION value exist or not.
A sample code is given below. If you don't understand please let me know.
<?php
session_start();
if (isset($_SESSION["loggedin"]) && ($_SESSION["loggedin"] == TRUE)) {
//write a nav menu html code here
?>
<div>
nav-1
</div>
<?php
} else {
//write another nav menu html code here
?>
<div>
nav-2
</div>
<?php
}
?>
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>
Below is my Code which I am running on WAMP 2.5. The works fine on MAMP but on WAMP it keeps giving undefined variable error. For instance $dbhandle is undefined error as per php while I have explicitly defined it way before line# 49. What I am feeling that PHP interpreter is not accessing file sequentially. It read directly thing between html and /html rather reading from top.
<?
ini_set('display_errors',0);
ini_set('display_startup_errors',0);
error_reporting(E_ALL);
include_once 'config.php';
$username = "";
$password = "";
$dbhandle = null;
$row = null;
$username = $config['user'];
$password = $config['password'];
$hostname = $config['server'];
$db = $config['db'];
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)or die(mysql_error($dbhandle));
$selected = mysql_select_db($db,$dbhandle)or die(mysql_error($dbhandle));
if(isset($_GET['id']))
{
$id = intval($_GET['id']);
$query = "Delete from posts WHERE sb_id = $id";
$result = mysql_query($query, $dbhandle) or die(mysql_errno($dbhandle));
$query = "Delete from comments WHERE post_id = $id";
$result = mysql_query($query, $dbhandle) or die(mysql_errno($dbhandle));
header("Location: index.php");
}
?>
<html>
<head>
<title>
Latest Fb Posts
</title>
</head>
<body>
<style>
#container{padding-top: 5%;padding-left: 5%;}
.post{background-color: #e7ecfd;width:90%;padding: 1%;margin-bottom: 2%;}
.post a{font-size: 80%;}
.commentbox{font-size: 90%;font-family: Arial;padding:1%;;margin-top: 2%;margin-bottom: 2%;width: 75%;background-color: #dadbe1;-webkit-border-radius: 3px;}
.author{display: block; width: 50%;color: #1e3493;font-weight: bold;font-size: 70%;padding-bottom: 2%;}
.date{color: #d2d4df;display: block;width: 30%;margin-top: 2%;}
</style>
<?php
$query = "SELECT * FROM posts order by sb_id Asc";
$result = mysql_query($query, $dbhandle);
?>
<div id="container">
<?
while ($row = mysql_fetch_object($result))
{
?>
<div class="post">
<?= $row->content ?>
<span class="date">
<?
$newDate = date("d-M-Y", strtotime($row->post_date));
?>
<?= $newDate ?>
</span>
<br />
<?
$queryComment = "SELECT * from comments where post_id = $row->sb_id";
$resultComment = mysql_query($queryComment, $dbhandle);
while ($rowComment = mysql_fetch_object($resultComment))
{
?>
<div class="commentbox">
<span class="author">Adnan Commented:</span>
<?= $rowComment->content ?>
</div>
<?
}
?>
Delete
</div>
<?
}
?>
</div>
</body>
</html>
Everytime I go to my index.php page, I am getting the following error on Google Chrome:
This webpage has a redirect loop
Oh my phpmyadmin database, if the text in account_type is 'deactivate', I made it so the user is automatically redirected to logout.php (This is in the functions.php page)
If it's 'active', then nothing happens.
My index.php code:
<?php include_once 'connect.php';?>
<?php include_once 'functions.php';?>
<!doctype html>
<html lang="en" class="home-page">
<head>
</head>
<body>
<ul class="linklist-admin">
<?php
if (loggedin()){ ?>
<li>My Profile</li>
<?php } else { ?>
<li>Sign In</li>
<?php } ?>
</ul>
</body>
</html>
My functions.php code:
<?php
session_start();
function loggedin(){
if (isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])){
return true;
} else {
return false;
}
}
if(loggedin()){
$my_id = $_SESSION['user_id'];
$user_query = mysql_query("SELECT username, account_type FROM users WHERE id='$my_id'");
$run_user = mysql_fetch_array($user_query);
$username = $run_user['username'];
$account_type = $run_user['account_type'];
$query_level = mysql_query("SELECT name FROM user_level WHERE id='$user_level'");
$run_level = mysql_fetch_array($query_level);
$level_name = $run_level['name'];
$d = 'deactivate';
$a = 'active';
}
if($account_type == $d) { //logs you out if your account is deactivated.
header('location: logout.php');
}
?>
My logout.php code:
<?php
include 'connect.php';
include 'functions.php';
session_destroy();
header('location: index.php');
if($account_type == $d) {
//do stuff here
}
I think that's what you want.
I'm working on a website with where a user profile page is part of.
This is my code on top of the page:
<?php
require 'includes/connect.inc.php';
session_start();
$id = $_SESSION['user_id'];
$userResult = mysqli_query("SELECT * FROM users where user_id ='$id'");
while($userRow = mysqli_fetch_array($userResult)) {
$avatar = $userRow['avatar'];
$locatie = $userRow['locatie'];
$info = $userRow['info'];
$email = $userRow['email'];
$username = $userRow['username'];
}
?>
And this is the part where it has to display the rows from the database (the part the user can see when he is on his own profile page)
<?php if(isset($_SESSION['username'])){
?>
<div class="col-lg-6">
<h4>Naam:</h4>
<p><?php echo $username; ?></p>
<h4>Locatie:</h4>
<p><?php echo $locatie; ?></p>
<h4>E-mailadres:</h4>
<p><?php echo $email; ?></p>
<h4>Informatie:</h4>
<p><?php echo $info; ?></p>
Klik hier om uw profiel te bewerken.
</div>
<div class="col-lg-6">
<?php echo "<img class='useravatar' src='/avatar/user" . $id . ".jpg'></img>"; ?>
<?php
} else {
echo "U hebt geen bevoegdheid om deze pagina te bekijken";
}
?>
Why does it not show anything?
this is the verify page from the login form:
$query = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'") or die(mysql_error());
$row = mysql_num_rows($query) or die(mysql_error());
if($row == 1){
$queryFetch = mysql_fetch_array($query);
session_start();
$_SESSION['username'] = $queryFetch['username'];
$_SESSION['role'] = 'user';
$_SESSION['email'] = $queryFetch['email'];
$_SESSION['user_id'] = $queryFetch['user_id'];
if(isset($_SESSION['username'])){
header ('location: /usercp.php');
}
}
}
?>