How to change the navbar after a user is logged in? - php

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
}
?>

Related

set cooke in php in login user [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I made a site with PHP that the user enters
I wanted to do something with cookies in PHP so that when the user enters another header is displayed
<?php
include "database/pdo_connection.php";
$error="";
$errorFild="";
if(
isset($_POST['phone']) && $_POST['phone'] !== ''
&& isset($_POST['password']) && $_POST['password'] !== ''
)
{
if(isset($_POST['sub'])){
$phone=$_POST['phone'];
$password=$_POST['password'];
$smt=$conn->prepare("SELECT `password` FROM users WHERE `phone`='$phone' ");
$smt->execute();
$result=$smt->fetchAll();
if(password_verify($password,$result[0]['password'])){
$result=$conn->prepare("SELECT * FROM users WHERE phone=? ");
$result->bindValue(1,$phone);
$result->execute();
$users=$result->Fetch(PDO::FETCH_ASSOC);
$_SESSION['id']=$users['id'];
$_SESSION['role']=$users['role'];
$_SESSION['phone']=$users['phone'];
**setcookie("phone", $users['phone'], time()+89000);**
header('location:index.php');
}
else{
$error=true;
}
}
}
else{
if( !empty($_POST)){
$errorFild =true;}
}
?>
This is the login page code
<li class="nav-item me-0">
<a class="nav-link mt-3 mt-lg-0" href="/login.php">
<i class="fa fa-sign-in ms-1"></i>
<span>login</span>
</a>
</li>
<li class="nav-item me-0">
<a class="nav-link mt-3 mt-lg-0" href="/register.php">
<i class="fa fa-user-plus ms-1"></i>
<span>register</span>
</a>
</li>
</li>
<li class="nav-item me-0">
<a class="nav-link mt-3 mt-lg-0" href="/codeyadproject2/logout.php">
<i class="fa fa-sign-in ms-1"></i>
<span>logout</span>
</a>
</li>
<li class="nav-item me-0">
<a class="nav-link mt-3 mt-lg-0" href="/codeyadproject2/PANEL/index.php">
<i class="fa fa-sign-in ms-1"></i>
<span>login to panel</span>
</a>
</li>
and index header
my Question:
I want him not to bring me another header when he comes in
For example, instead of logging in and registering, it should log in to the panel, or if it doesn't log in, it won't log in to the panel anymore
What code should I put? (with cookies)
Your script has a couple of issues:
Firstly, you're trying to use sessions, but sessions are not accessible until you call session_start().
You are executing the same query twice, it would be more efficient to consolidate these into the one.
You're using unprepared statements, which are vulnerable to SQL injection attacks (such attacks could lead to your entire database being deleted, or worse; leaked)
Cookies are not necessary for the purpose of logging in.
The fetchAll() command can be replaced with fetch() because you only need a singular record.
This is what that would look like with those things fixed:
login.php:
<?php
session_start();
include "database/pdo_connection.php";
$error = "";
if (isset($_POST['phone'], $_POST['password'], $_POST['sub'])) {
$phone = $_POST['phone'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM users WHERE `phone` = :phone");
$stmt->bindParam(':phone', $phone);
$stmt->execute();
$result = $stmt->fetch();
if ($result && password_verify($password, $result['password'])) {
$_SESSION['id'] = $result['id'];
$_SESSION['role'] = $result['role'];
$_SESSION['phone'] = $result['phone'];
} else {
$_SESSION['error'] = 'Your username or password was invalid';
}
header('location:index.php');
}
index.php:
<?php
session_start();
if (isset($_SESSION['error'])) {
$errorMsg = $_SESSION['error'];
unset($_SESSION['error']);
}
?>
<?php if (isset($errorMsg)) { ?>ERROR: <?=$errorMsg?><?php } ?>
<?php if (isset($_SESSION['phone'])) { ?>
<h1>Welcome back, <?php echo $_SESSION['phone']; ?></h1>
<?php } else { ?>
<h1>Welcome</h1>
<?php } ?>
(personally though I hate mixing HTML and PHP, but that should be enough to get you out of your writers block)

Forwarding to start page after successful registration

I have a small login system on my site. I want the user to be redirected to the home page after the successful login. After several attempts with many possibilities, I still do not succeed.
This is my login script:
<?php
if (isset($_POST["submit"])) {
require("mysql.php");
$stmt = $mysql->prepare("SELECT * FROM $accounts WHERE email = :email");
$stmt->bindParam(":email", $_POST["email"]);
$stmt->execute();
$count = $stmt->rowCount();
if ($count == 1) {
$row = $stmt->fetch();
if (password_verify($_POST["password"], $row["password"])) {
$_SESSION['username'] = $row['username'];
?>
<div class="alert alert-emerald text-center mb-50">
You have been successfully registered
</div>
Continue
<?php
} else {
?>
<div class="alert alert-red-ncs text-center mb-50">
The specified password is incorrect
</div>
<?php
}
} else {
?>
<div class="alert alert-red-ncs text-center mb-50">
An account with this email address was not found
</div>
<?php
}
}
?>
I have already had these attempts:
header("Location: index.php");
exit;
header("Location: index.php");
header('Location: login.php?redirect=index.php');
I'm really looking forward to an answer as I've been stuck on the solution for several hours now!

show logout link in navigation bar when logged in php

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>

Notice: Undefined index with PHP session

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';

showing username after login on the website

I am designing a website with login page. the login part and fetching from db works fine. but i want to show the username on the homepage after logging in. i use session_start(). but the username is not showing. i checked similar questions here but none of them was the answer for me. followings are codes:
php code:
$email = mysqli_real_escape_string($con,$_POST['user']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
$sel_user = "select * from admins where email='$email' AND password='$pass'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0)
{
$_SESSION['email']=$email
echo "<script>window.open('index2.html','_self')</script>";
}
else {
echo "<script>alert('Email or password is not correct, try again!')</script>";
}
index2.html :
<?php
session_start();
?>
<div class="inline-block">
<h5 class="no-margin"> Welcome </h5>
<h4 class="no-margin"> <?php echo $_SESSION['email']; ?> </h4>
<a class="btn user-options sb_toggle">
<i class="fa fa-cog"></i>
</a>
</div>
Try below code:
First code:
session_start();
$email = mysqli_real_escape_string($con,$_POST['user']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
$sel_user = "select * from admins where email='$email' AND password='$pass'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0)
{
$_SESSION['email']=$email
echo "<script>window.open('index2.html','_self')</script>";
}
else {
echo "<script>alert('Email or password is not correct, try again!')</script>";
}
index2.php :
<?php session_start(); ?>
<div class="inline-block">
<h5 class="no-margin"> Welcome </h5>
<h4 class="no-margin"> <?php echo $_SESSION['email']; ?> </h4>
<a class="btn user-options sb_toggle">
<i class="fa fa-cog"></i>
</a>
</div>
It should work.

Categories