Reputation: 83
I have created the session at
LOGIN PAGE
<?php
session_start();
include 'dbconfig.php';
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM login WHERE username = '$username' AND password= '$password' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$_SESSION["userid"] = $row['user'];
echo $_SESSION["userid"];
}
} else {
echo "wrong";
}
$conn->close();
?>
FETCHING LOGIN
function login() {
var username = $("#username").val();
var password = $("#password").val();
if (username == "" || username == null || username == undefined || password == "" || password == null || password == undefined) {
$('#foremptyvalue').show();
} else {
$('#foremptyvalue').hide();
$('#loader').show();
jQuery.ajax({
url: baseurl + "login.php"
, data: 'username=' + username + '&password=' + password
, type: "POST"
, success: function (response) {
response = $.trim(response);
if (response == "wrong") {
$('#loader').hide();
$('#forwronginput').show();
$("#username").val('');
$("#password").val('');
} else {
$('#loader').hide();
$('#forwronginput').hide();
location.href = "account.php?id=" + response;
}
}
, error: function () {}
});
}
}
HEADER.PHP
In this page the session variable is not working. I have used below code:
<?php
session_start();
echo session_id();
$session = $_SESSION["userid"];
?>
RESULT IS BELOW
ptarbkn67poq1gkch2dh6fvqc3 Notice: Undefined index: userid in C:\xampp\htdocs\feescounter\header.php on line 4
I have also check whether the session save path is writable or not and it is writable. it is saving the session in C:\xampp\tmp
Upvotes: 4
Views: 627
Reputation: 6539
Your header.php file should be:-
<?php
if (!session_id()) {
session_start();
}
if(!empty($_SESSION['userid'])){
echo $_SESSION['userid'];
}else{
echo 'guest user';
}
Upvotes: 1
Reputation: 7617
You must start the Session before using it. It doesn't seem that way from your code... Try putting the code below at the very top of each of your Files and see how it goes:
<?php
// THIS SHOULD BE THE VERY FIRST LINES OF CODE IN YOUR SCRIPTS
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
Upvotes: 2