This question already has answers here:
PHP Session variable not getting set
(9 answers)
Closed 1 year ago.
I've been following Dani Krossings Login System It's a great tutorial and is just what I am looking for, there is just one thing I'm struggling with.
After logging in, the header doesn't refresh. Following login, the header should change to ...Profile Page, Logout. The code I have stays as Sign Up, Login. It is as is the $_SESSION variable has not come through to the header. However, if after login, I select the Sign up or login link, the header changes to what it should be.
Function code
function uidExists($conn, $username) {
$sql = "SELECT * FROM users WHERE usersUid = ? OR usersEmail = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("location: ../signup.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt, "ss", $username, $username);
mysqli_stmt_execute($stmt);
// "Get result" returns the results from a prepared statement
$resultData = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($resultData)) {
return $row;
}
else {
$result = false;
return $result;
}
mysqli_stmt_close($stmt);
}
function loginUser($conn, $username, $pwd) {
$uidExists = uidExists($conn, $username);
if ($uidExists === false) {
header("location: ../login.php?error=wronglogin");
exit();
}
$pwdHashed = $uidExists["usersPwd"];
$checkPwd = password_verify($pwd, $pwdHashed);
if ($checkPwd === false) {
header("location: ../login.php?error=wronglogin");
exit();
}
elseif ($checkPwd === true) {
session_start();
$_SESSION["userid"] = $uidExists["usersId"];
$_SESSION["useruid"] = $uidExists["usersUid"];
header("location: ../index.php?error=none");
exit();
}
}
header.php
<?php
session_start();
include_once 'includes/functions.inc.php';
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>PHP Project 01</title>
<!--I won't do more than barebone HTML, since this isn't an HTML tutorial.-->
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght#0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!--A quick navigation-->
<nav>
<div class="wrapper">
<img src="img/logo-white.png" alt="Blogs logo">
<ul>
<li>Home</li>
<li>About Us</li>
<li>Find Blogs</li>
<?php
if (isset($_SESSION["useruid"])) {
echo "<li><a href='profile.php'>Profile Page</a></li>";
echo "<li><a href='logout.php'>Logout</a></li>";
}
else {
echo "<li><a href='signup.php'>Sign up</a></li>";
echo "<li><a href='login.php'>Log in</a></li>";
}
?>
</ul>
</div>
</nav>
<!--A quick wrapper to align the content (ends in footer.php)-->
<div class="wrapper">
Login.php
<?php
include_once 'header.php';
?>
<section class="signup-form">
<h2>Log In</h2>
<div class="signup-form-form">
<form action="includes/login.inc.php" method="post">
<input type="text" name="uid" placeholder="Username/Email...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="submit">Sign up</button>
</form>
</div>
<?php
// Error messages
if (isset($_GET["error"])) {
if ($_GET["error"] == "emptyinput") {
echo "<p>Fill in all fields!</p>";
}
else if ($_GET["error"] == "wronglogin") {
echo "<p>Wrong login!</p>";
}
}
?>
</section>
<?php
include_once 'footer.php';
?>
login.inc.php
<?php
if (isset($_POST["submit"])) {
// First we get the form data from the URL
$username = $_POST["uid"];
$pwd = $_POST["pwd"];
// Then we run a bunch of error handlers to catch any user mistakes we can (you can add more than I did)
// These functions can be found in functions.inc.php
require_once 'dbh.inc.php';
require_once 'functions.inc.php';
// Left inputs empty
if (emptyInputLogin($username, $pwd) === true) {
header("location: ../login.php?error=emptyinput");
exit();
}
// If we get to here, it means there are no user errors
// Now we insert the user into the database
loginUser($conn, $username, $pwd);
} else {
header("location: ../login.php");
exit();
}
Anyone have any thoughts on how I can get the header to refresh on submission of a successful login form?
Since Sometimes Some Content Is Left On The Page After Reloading The Header, We Need To Use die() after Changing Location From Header.
TBH, Redirecting Using PHP Is Not Recommended, I Suggest You To Redirect The User Using An Inbuilt JavaScript Function, window.location.replace(path)
You Can Call It Inside A PHP Script Using
?>
<script>
window.location.replace(path)
</script>
<?php
Or Simply Just Create Your Own Function:
function redirect($path) {
?>
<script>
window.location.replace('<?php echo $path ?>')
</script>
<?php
}
And Use It: redirect("profile.php")
Always put a session_start() into every page I want to use $_SESSION variables.
Fixed.
Thanks for all your help!
Related
UPDATED: I have a variable in PHP mailuid that I want to show in my HTML. It displays the error the value of mailuid is undefined on the webpage. How can I show the value of height to html page?
index.php
<?php
require "header.php";
?>
<main>
<link rel="stylesheet" type="text/css" href="styl.css">
<div class="wrapper-main">
<section class="section-default">
<h2><?php echo "$mailuid" ?></h2>
<?php
?>
</section>
</div>
</main>
<?php
require "footer.php";
?>
loginbackend.php
<?php
if(isset($_POST['login-submit'])) {
require 'db.php';
$mailuid = $_POST['mailuid'];
$password = $_POST['pwd'];
if (empty($mailuid) || empty($password)) {
header("Location: ./index.php?error=emptyfields");
exit();
} else {
$sql = "SELECT * FROM users WHERE uidUsers=? OR emailUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ./index.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $mailuid, $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if($pwdCheck == false) {
header("Location: ./index.php?error=wrongpwd");
exit();
} else if ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
$username = substr($mailuid, 0, strpos($mailuid, "#"));
header("Location: ./index.php?login=success".$username);
exit();
} else {
header("Location: ./index.php?error=wrongpwd");
exit();
}
} else {
header("Location: ./index.php?error=nouser");
exit();
}
}
}
} else {
header("Location: ./signup.php");
exit();
}
As per your latest comment:
To get the mailuid from the URL (GET parameters) add the following code to your index.php
<?PHP
require "header.php";
$mailuid = !empty($_GET['mailuid']) ? $_GET['mailuid'] : null;
// You can also specify the default value to be used instead of `null` if the `mailuid` is not specified in the URL.
?>
<main>
<link rel="stylesheet" type="text/css" href="styl.css">
<div class="wrapper-main">
<section class="section-default">
<h2><?php echo "$mailuid"?></h2>
</section>
</div>
</main>
<?php
require "footer.php";
?>
From PHP7 you can use
$mailuid = $_GET['mailuid'] ?? null;
instead of
$mailuid = !empty($_GET['mailuid']) ? $_GET['mailuid'] : null;
The mistake you've made:
I think you're confusing forms and file including with how post works.
Let me explain:
A form sends data to the server, which is then pushed into the $_POST global variable. You can read this data and use this data easily by echoing or dumping it.
This is what you should do:
In this case, your data value will be empty as you're not passing anything to it.
You can solve this by creating a form and passing it to your PHP file.
You can also just require your php script.
Normally you would put data.php in your action, but since you wish to use the variable before you entered the form, you have to include it first.
index.html
<?php require 'data.php'; ?>
<form method="POST" action="">
<h1>Height: <?=$height?></h1>
<input type="text" placeholder="Enter the height..." name="height">
<input type="submit" name="submit" value="Submit">
</form>
data.php
<?php
if (!empty($_POST)) {
$height = $_POST['height'];
} else {
$height = 0; //Default height
}
My apologies if i didn't get your question properly.
===========================================
Option B, if this is what you mean, is just doing this:
index.html
<body>
<div class="container">
<?php
require 'data.php'; //Get the data.php file so we can use the contents
?>
<h1><?php echo $height; ?></h1>
</div>
</body>
data.php
<?php
$height = 100; //Height variable
I have the following line in my HTML file for my homepage. How come it won't print out the name of the current user when they log in? I have the line in the body section of the html file. I want to put it on all my pages too but it won't display. The user does exist as it logs in succesfully via my php echo mesage.
This line:
<div id="usernameDiv"><?php echo $_SESSION['username']; ?></div>
Here is the login page:
<?php
function SignIn() {
require_once("constants.php"); //Now constants will be accessible
session_start();
try {
$link = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$username = $_POST['username']; //no need to esaping as we will use prepared statements
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
//You need to define a new column named "id" which will be int auto_increment and it will be your primary key
$sql = "SELECT id, username, password FROM users where username = :username AND password = :password";
//Prepare your query
$stmt = $link->prepare($sql);
//Execute your query binding variables values
$stmt->execute(array(':username'=>$username, ':password'=>$password));
//Fetch the row that match the criteria
$row = $stmt->fetch();
if (!empty($row['username']) && !empty($row['password'])) {
$_SESSION['is_logged'] = true; //Now user is considered logged in
$_SESSION['username'] = $row['username'];
$_SESSION['id'] = $row['id'];
//Never store passwords in $_SESSION
echo "Welcome to your User Account for CSIT Conference. Click to go home: ";
echo ' Home Page . ';
echo "Or here to go to your assigned papers: ";
echo ' Assigned Papers . ';
} else {
echo "SORRY... YOU ENTERED WRONG ID AND PASSWORD... PLEASE RETRY...";
}
$link = null;
} else {
echo 'Please enter username and password.';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
if (isset($_POST['submit'])) {
SignIn();
}
?>
Here is the home page. Eventually I want it on all the pages.
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="import" href="navigation.html">
</head>
<body>
<center> <b>World Congress CS-IT Conferences 2016</center>
<div id="horizontalmenu">
<ul>
<li>Home<br/></li>
<ul> <li>General Information <ul>
<li>About</li>
<li> Conference Fee</li>
<li>Hotel</li> </ul>
<li>Keynote Speakers<br/></li>
<li>Call for Papers<br/></li>
<li>Important Dates<br/></li>
<li>Major Areas<br/></li>
<li>Paper Submission<br/></li>
<li>Login<br/></li>
<li>Registration<br/></li>
<li>Conference Program<br/></li>
<li>Guidelines<br/></li>
<li>Comments<br/></li>
</ul>
</nav></b>
<div id="usernameDiv"><?php echo $_SESSION['username']; ?></div>
<br><br>
<div class="zoom pic">
<center> <img src="images/technology.png" alt="portrait"> <center>
</div>
</body>
</html>
You are starting the session inside of your SignIn() function. Remove session_start(), and instead put the following at the top of your file to start your session:
if (!session_id()) #session_start();
You must also include the above line anywhere that you want to use the session data (for example, it should be the first line in your index file.)
* All of this assumes that you either have PHP setup to execute in a .html file, or your file is actually index.php instead of index.html
I've got a login script that does not close the session when the user goes to another site or returns to the login page. My question is, how do I destroy the session when they navigate away from the site or outside of the directory? Would I need to add a timeout argument when the user starts the session? Would I need to use cookies instead of session?
login.php
require("../includes/header.php");
if($_SERVER["REQUEST_METHOD"] == "POST"){
$p_num = $_POST["username"];
$pwd = $_POST["password"];
$query = "SELECT * FROM $user_table";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result)){
$user_id = "{$row['user_id']}";
$user_name = "{$row['user_name']}";
$password = "{$row['password']}";
$image = "{$row['image']}";
$email = "{$row['email']}";
$program = "{$row['program']}";
$role = "{$row['role']}";
if(($user_id == $p_num) && ($pwd == $password)){
$_SESSION["id"] = $user_id;
$_SESSION["user"] = $user_name;
$_SESSION["program"] = $program;
$_SESSION["pass"] = $password;
$_SESSION["image"] = $image;
$_SESSION["email"] = $email;
$_SESSION["role"] = $role;
header("Location: ../pages/instructor.php");
}
else{
header("Refresh: 1; URL=../index.php");
}
}
}
instructor.php
<?php require("../includes/header.php"); ?>
<title></title>
<link href="../css/style.css" rel="stylesheet/less" type="text/css">
<script src="../js/jquery.2.0.3.js"></script>
<script src="../js/script.js"></script>
<script src="../js/less-1.7.4.min.js"></script>
</head>
<body>
<div id="page">
<header>
<div id="logo" class="logo_bg"></div>
<div id="fsi_logo" class="logo_bg"></div>
</header>
<div id="main">
<div id="instructor">
<?php
echo "<img id=instructor_image src=" .$_SESSION["image"] .">";
echo "<h1>" .$_SESSION["user"] ."</h1>";
echo "<span><p>" .$_SESSION["program"] ."</p> - <h2>" .$_SESSION["role"] ."</h2></span>";
echo "" .$_SESSION["email"] ."";
?>
</div>
<div id="bleg">
<h1>BUILD SCENARIO</h1>
<h1>SEARCH SCENARIOS</h1>
<h1>VIEW SCENARIOS</h1>
</div>
<?php require("../includes/footer.html"); ?>
logout.php
session_start();
session_unset();
session_destroy();
script.js
$(window).on('beforeunload', function(e){
e.preventDefault();
ajax = new XMLHttpRequest();
ajax.open("../php/logout.php", "POST", true);
ajax.send();
})
Do it with javascript
window.onbeforeunload = function (e) {
e.preventDefault(); //Not even sure what the default action does, but oh well
ajax = new XMLHttpRequest();
ajax.open("killsession.php","POST",true);
ajax.send();
}
killsession.php will of course be where the session is killed
Write a jquery/JS event handler for unload doc and send a request to ExpireSession.php expiring the session
As said "It depends on what constitutes "leaving""
$count = $_SESSION['count'];
if($count === 1) {
unset ($_SESSION['count']);
}
else (empty($_SESSION['count'])) {
$_SESSION['count'] = 1;
}
I am new to php. Here is a code to check if the user is logged in using session and then allowing the user.
VALIDATION
<?php
session_start();
$uname = $_POST['uname'];
$pass = $_POST['pass'];
if($uname == "admin" && $pass == "admin")
{
$_SESSION['uname'] = $uname;
$_SESSION['auth'] = 1;
echo "Welcome Mr ".$uname.". You are now logged in ";
echo "<br>";
echo "<a href='TakeMeHome.html'>Click here to access the application </a>";
}
else
{
echo "Invalid username or password";
}
?>
Page
<?php
session_start();
if($_SESSION['auth'] != 1)
{
echo "You are not logged in! ";
echo "<a href = \"TakeMeHome.html\">";
echo "Access Application";
echo "</a>";
exit();
}
?>
<html>
You are now logged in
</html>
But the link tag is displaying
"; echo "Access Application"; echo ""; exit(); } ?>
along with the html data. No verification is done. I know there are many better ways to validate user is logged in or not. But i am learning sessions and hence i am using sessions.
Can you please tell me where i am going wrong?
regards.
use single quote in your echo codes like this:
<html>
<head>
</head>
<body>
<?php
echo "<a href='pageToGoTo.html' title='Page to go to' class='whatEver'>Anchor text</a>";
?>
</body>
</html>
What is told already, html should be put in the body...
I have no idea why #Andy has suggested you put your PHP in your head tags - it isn't javascript. You have 2 ways you can format your PHP and HTML, the first is to put all your PHP above your opening html tag, like so
<?php
session_start();
if($_SESSION['auth'] != 1) {
$message = 'You are not logged in! Access Application';
} else {
$message = 'You are logged in!';
}
?>
<html>
<head>
</head>
<body>
<?php echo $message; ?>
</body>
</html>
Or, place it in the body of your page, like so:
<?php
session_start();
?>
<html>
<head>
</head>
<body>
<?php
if($_SESSION['auth'] != 1) {
echo 'You are not logged in! Access Application';
} else {
echo 'You are logged in!';
}
?>
</body>
</html>
If you are still not getting the desired results then use var_dump($_SESSION); to print out your session array and make sure it holds the correct information.
The template file is .php and has those placeholders:
<ul>
<li><a href='a.php'>{{placeholder1}}</a></li>
{{placeholder2}}
</ul>
And this is the code which replaces them:
$file = file_get_contents($template);
$file = str_ireplace('{{placeholder1}}', count_messages(), $file);
$file = str_ireplace('{{placeholder2}}', show_link(), $file);
print $file;
Functions are nothing special ('functions.php'):
function count_messages()
{
ob_start();
if (preg_match('/^[A-Za-z0-9_]{3,40}$/', $_SESSION['username']))
{
$table = $_SESSION['username'];
}
else
{
header('Location: login.php');
exit();
}
try
{
$db = new PDO('sqlite:site.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $db->prepare("SELECT Count(*) FROM `$table` WHERE `isRead` = '0'");
$result->execute();
$count = $result->fetchColumn();
if ($count > 0)
{
print "<b style='color: #00ff00; text-decoration: blink;'>$count</b> <b style='font-size: 6pt; text-decoration: blink; text-transform: uppercase;'>unread</b> ";
}
unset($db);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
ob_end_flush();
}
function show_link()
{
ob_start();
if ($_SESSION['username'] == "admin")
{
print "<li><a href='admin_panel.php' target='main_iframe'><b style='color: #ffff00;'>Admin Panel</b></a></li>;
}
ob_end_flush();
}
First counts the messages and outputs number with some styling, the second adds to the menu 'Admin Panel' link if the username is 'admin.
The problems are (no errors in php log):
count_messages() works but outputs 'n unread' above all elements on the page.
show_link() doesn't output the link.
The file $template is readable and named template.php:
<?php
session_start();
if(!$_SESSION['islogged'])
{
header('Location: login.php');
exit();
}
require_once('functions.php');
?>
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="description" content="Documents" />
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Documents</title>
</head>
<body>
<div id="main">
<iframe src="documents.php" name="main_iframe" id="main_iframe">
</iframe>
</div>
<div id="main_menu">
<ul id="menu_list">
<li>{{placeholder1}}Messages</li>
{{placeholder2}}
<li>Log out</li>
</ul>
</div>
</body>
</html>
The index.php:
<?php
session_start();
require_once('functions.php');
$template = 'template.php';
if (file_exists($template))
{
if (is_readable($template))
{
if(!$_SESSION['islogged'])
{
session_destroy();
header('Location: login.php');
exit();
}
}
else
{
print "Template file cannot be opened";
}
}
else
{
print "Template file doesn't exist";
}
$file = file_get_contents($template);
$file = str_ireplace('{{placeholder1}}', count_messages(), $file);
$file = str_ireplace('{{placeholder2}}', show_link(), $file);
print $file;
?>
I hope someone here knows what causes this behaviour ...
You are using the functions’ result values in the str_ireplace function call but the functions don’t return anything, they are missing a return statement.
You probably meant to use return ob_get_clean(); instead of ob_end_flush(); in your code.