Unable to detect $_SESSION['username'] on index/auth page - php

I am unable to display $_SESSION['username'] on my index.html/auth.php page after logging in. It's strange because it's able to detect $_SESSION['username'] on other pages after logging in, just not my index/auth page.
EDIT: When logging in correctly, login.php goes to index.html. index.html is then displaying the 'login' button from auth.php, as ' Login '
login.php, where the user will enter the username and password to login and $_SESSION['username'] is created.
<?php session_start();
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username'
and password='".md5($password)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
// Redirect user to index.html
header("Location: ../index.html");
}else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="login.css" />
</head>
<body>
<div class="form">
<h1>Log In</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required style="text-align: center;"/>
<input type="password" name="password" placeholder="Password" required style="text-align: center;"/>
<input name="submit" type="submit" value="Login" />
</form>
<a href='resetpassword.php'>Forgotten Password?</a>
<br/><a href='registration.php'>Register Here</a>
</div>
<?php } ?>
</body>
</html>
index.html, where the auth.php page is called (the rest of my index.html page is not important to this issue, replaced with 'blah blah blah').
EDIT: My server is configured so that index.html can run php.
<?php session_start(); ?>
<?php require('login/auth.php'); ?>
<?php include('login/checkadmin.php'); ?>
<?php include('login/getoutages.php'); ?>
<!doctype html>
<html>
blah blah blah
</html>
auth.php, where the database is used and where $_SESSION['username'] is meant to show but doesn't!
<?php session_start();
ob_end_clean();
if(isset($_SESSION['username'])) {
?>
<table id="signedin">
<tr>
<td colspan="5">
Welcome, <?php echo $_SESSION['username']; ?>!
</td>
</tr>
<tr>
<td align="right">
<a id="logouts" href="login/logout.php">Sign Out</a>
</td>
<td align="right">
</td>
<td align="left">
<a id="profiles" href="login/profile.php">Profile</a>
</td>
</tr>
</table>
<?php } else if(!isset($_SESSION['username'])) { ?>
<div id="notsignedin"><a id="logins" href="/login/login.php">Login</a></div>
<?php } ?>
Any information is helpful! Thank you!
EDIT: I have updated my code to run session_start(); before anything else.
Still unable to detect $_SESSION['username'].
EDIT2: Switched $username = $_SESSION['username']; in login.php to $_SESSION['username'] = $username; Still not showing on auth.php

You should start the session in every file before anything else
<?php session_start(); ?>
At least if you are calling every page separately

You need to call session_start() before checking the issest($_Session['username'])

You need to put session_start(); before it calls $_SESSION variables on that page, therefore if(isset($_SESSION['username']) will not be "set" until the session is started, just move it to above in the page, it's good practice to call it in first. I usually put it in my config page along with my DB connection and include it in every page :)
Hope this helps

Related

Session in PHP not getting registerd

I am trying to develop a simple login page once login login.php it should show index.php
Below files are in the web directory:
> https://www.myowndomain.com/test/status/login.php
> https://www.myowndomain.com/test/status/auth.php
> https://www.myowndomain.com/test/status/index.php
So when the user enters index.php it checks if the session is created if so it will show index.php if not redirect it to login.php.
If I log in using a valid username and password and click login the PHP file is returning to login.php, not to index.php (Session is created in login.php but when accessing the same on indext.php or auth, session it is blank?
In index.php if I don't include auth.php - The login works fine but doesn't get the session.
login.php:
<?php
include("db.php");
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username']))
{
$username = stripslashes($_REQUEST['username']); // removes backslashes
$username = mysqli_real_escape_string($con,$username); //escapes special characters in a string
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking if user existing in the database or not
$query = "SELECT * FROM users WHERE username='$username' and password='".md5($password)."'";
$result = mysqli_query($con,$query) or die(mysqli_error());
$rows = mysqli_num_rows($result);
echo $rows;
if($rows==1)
{
$_SESSION['username'] = $username;
echo "User in session:" . $username;
header("Location: index.php"); // Redirect user to index.php
}
else
{
echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
}
else
{
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<h1>Log In</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
<p>Not registered yet? <a href='registration.php'>Register Here</a></p>
</div>
</body>
</html>
auth.php:
<?php
include("db.php");
session_start();
$user_check=$_SESSION['username'];
$ses_sql = mysqli_query($con, "SELECT username FROM users where username='$user_check'");
$row=mysqli_fetch_array($ses_sql);
$login_session=$row['username'];
if(!isset($login_session))
{
header("Location:login.php");
}
?>
What could be wrong here? I have check every bit still issue. Probably someone can recheck my code and tell me the issue? Could it be an issue with the web directory? The files are inside a folder/subfolder/?
Other than the obvious security implications of your code, I don't see anything wrong with it. You could try manually setting the session save location. I've found with some hosting that the session path needs to be explicitly set for sessions to work...
session_save_path("/location/to/save/sessions/");
To find out what your session save path should be, contact your hosting provider. If you are using localhost - a quick google will do it.

php is not showing the else-block

i'm trying to learn about session_start() but when i run the file, it only show what is inside the
if (isset($_SESSION['username'])&& isset($_SESSION['password'])==$password) {
?>
log out
<?php } ?>
and not showing else{...} and even after i click log out, it won't print anything in else statement and only print inside the if statement. I use another file to do the log out proses but i don't know the right code for session_destroy()
here's the logout.php code below:
<?php
session_start();
session_destroy();
header("location: home.php");
?>
here's the full code:
<?php
session_start();
include("DB/db.php");
$_SESSION['username']=$username;
$_SESSION['password']=$password;
$_SESSION['is_log_in'] = true;
?><!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/css.css">
</head>
<body>
<div id="blank"></div>
<div id="panel">
<nav id="bar">
<div id="submen">
<form id="sir">
<input type="Search" name="search" placeholder="Search.." id="search">
</form>
Walpaper
Art
Photos
Image
<?php
if (isset($_SESSION['username'])&& isset($_SESSION['password'])==$password) {?>
<?php echo $username?>
log out
</div>
</nav>
</div>
</table>
<?php } else {
?>
login
register
</div>
</nav>
</div>
</table>
<?php } ?>
</body>
</html>
UPDATE for log in script
<?php
session_start();
include("DB/db.php");
if ($_GET['log']=='out'){
session_destroy();
}
if ($_POST['user']){
$sql = "Select password from user where username = '".$_POST['user']."' ";
$result = mysqli_query($koneksi, $sql);
if (mysqli_num_rows($result)){
$row = mysqli_fetch_assoc($result);
if ($row['password'] == md5($_POST['pass'])) {
$_SESSION['login'] = TRUE;
$_SESSION['username'] = $user;
$_SESSION['password'] = $pass;
}else{
$pesan = "Username and password mismatch";
}
}else{
$pesan = "please register";
}
}
?><!DOCTYPE html>
<html>
<head>
<title>Log in</title>
</head>
<body>
<?php
if ($_SESSION['login']) {
echo "text";
}else{
?>
<h1>Login</h1>
<form method="post" action="rahasia.php">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" name="" value="Login">
</form>
<form method="post" action="register.php">
<input type="submit" name="register" value="register">
</form>
<?php
}
echo $pesan;
?>
</body>
</html>
where have i gone wrong
Your $_SESSION vars are always set, and $password always equals $_SESSION['password'].
$_SESSION['username']=$username; // null, plus notice in error_log
$_SESSION['password']=$password; // null, plus notice in error_log
Unless those two vars are set in include("DB/db.php");, in which case that is bad practice. Can you paste db.php to see what is happening inside?
UPDATE.
Okay so the vars are being set. This now means:
$_SESSION['username']=$username; // a
$_SESSION['password']=$password; // 123456789
Therefore they will still match. You need to refactor these lines to function properly. Are you sure the mysql credentials is what you want for your logged in user
?

php log in not working online but works perfectly fine offline

I have created a log in page in php ('login.php) that works fine offline. But when i take it online, the log in fails. However the other pages connect seamlessly to the same database from where I pull in the log in details. Here's the code on the log in page:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="css/admin_style.css">
<body>
<div id="login_style">
<div class="login_head">
<img src="images/admin_logo.png" alt="Parlour Products">
<img src="images/admin_panel.png" width="200" height="75" alt="Admin Panel" class="adminPanel">
</div>
<br><br>
<h3>
<?php echo #$_GET['false_admin']; ?>
</h3>
<h3>
<?php echo #$_GET['logged_out']; ?>
</h3>
<h1> Admin Section</h1><br>
<form method="post">
User Id: <input type="text" name="name" placeholder="Enter User ID" required="required" />
Password: <input type="password" name="pass" placeholder="Password" required="required" /><br><br>
<button type="submit" name="login">Log In</button>
</form>
</div>
</body>
</html>
<?php
session_start();
include ("includes/db.php");
if(isset($_POST['login'])){
$name = mysql_real_escape_string($_POST['name']);
$pass = mysql_real_escape_string($_POST['pass']);
$sel_user = "select * from admin where admin_name='$email' AND admin_pass='$pass'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user==0 ){
echo "<script>alert('Login Failed. Please Try Again!')</script>";
}
else {
$_SESSION['user_email']=$email;
echo "<script>window.open('index.php?logged_in=Sucessfully Logged In!','_self')</script>";
}
}
?>
But every time I try to enter with the correct user name and password, I get the login error message. Initially I thought it was a database error, so I created this 'test.php' page with the following code:
<form action="test.php" method= "post" >
<table>
<tr>
<td colspan="4" align="left"><h1>Insert New User</h1></td>
</tr>
<tr>
<td><input type="text" name="user_name"/></td>
<td><input type="text" name="user_pass"/></td>
<td><input type="submit" name="add_user" value="Add User" /></td>
</tr>
</table>
</form>
<?php
include("includes/db.php");
if(isset($_POST['add_user'])){
$new_name = $_POST['user_name'];
$new_pass = $_POST['user_pass'];
$insert_user = "insert into admin (admin_name,admin_pass) values ('$new_name', '$new_pass')";
$run_user = mysqli_query($con,$insert_user);
if($run_user){
echo "<script>alert('New User Added!')</script>";
echo "<script>window.open('test.php','_self')</script>";
}
}
?>
This 'test.php' page connects fine and even inserts the data into the table. The table structure is same both online and offline. Other user login pages are all working fine too!
First of all use the error reporting function when you're not sure of the error:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
Probably the start session function is creating the problem here. try moving the
session_start();
function to the top of the page, before any other text is outputted. Hopefully, this should solve it.

How to disallow the user to access my home page when not logged in

I've searched on many ways to prevent direct url access but none of it, fitted my code. I tried to put
if ( !isset($_SESSION['logged-in']) || $_SESSION['logged-in'] !== true) {
// not logged in, move to login page
header('Location: login.php');
exit;
}
that code to verify and to change the page when the user try to access the home page when not logged in. The home page cannot be accessed when not logged in but the problem is even when the username and password is correct, it still goes to login page. What is the problem with the code?
Home page:
<?php
require 'user.php';
session_start();
if ( !isset($_SESSION['logged-in']) || empty($_SESSION['logged-in'])){
header('Location:index.php');
exit;
}
?>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<p>
You have successfully logged in
<?php
session_start();
$user = $_SESSION['current_user'];
echo $user->firstname.' '.$user->lastname.'.';
?>
</p>
<p>This is your home page.</p>
<p>Click <a href='update_user.php?username=<?php echo $user->username ?>'>[here]</a> to update user profile.</p>
<p>Click <a href='list_user.php'>[here]</a> to see the list of users.</p>
</body>
</html>
login page
<html>
<head>
<title>Login Page</title>
</head>
<body>
<p>Enter Username and Password to Login:</p>
<form action='login_process.php' method='post'>
<table border='1'>
<tr>
<td>Username:</td>
<td><input type='text' name='username'></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password'></td>
</tr>
<tr>
<td>&nbsp</td>
<td><input type='submit' value='Login'></td>
</tr>
</table>
</form>
</body>
</html>
login process
<?php
require 'user.php';
?>
<?php
$user = new User();
$user->username = $_REQUEST['username'];
$user->password = $_REQUEST['password'];
$found = $user->checkLogin();
if ($found){//redirect to home page
session_start();
$_SESSION['current_user']=$user;
header("Location: home.php");
exit;
}
else{//invalid username and password
echo "Invalid username/password. Click <a href='index.php'>[here]</a> to login again.";
}
?>
index.php
<?php
session_start();
require('user.php'); ?><html>
<head>
<title>Home Page</title>
</head>
<body>
<p><?php
// You are either logged in or not. If not, let user know to login.
if(!isset($_SESSION['username'])) { ?>
You must be logged in to view this content
Click to login
<?php }
else {
$user = $_SESSION['current_user'];
echo $user->firstname.' '.$user->lastname.'.'; ?></p>
<p>This is your home page.</p>
<p>Click <a href='update_user.php?username=<?php echo $user->username ?>'>[here]</a> to update user profile.</p>
<p>Click <a href='list_user.php'>[here]</a> to see the list of users.</p>
<?php } ?>
</body>
</html>
process login
<?php
session_start();
require('user.php');
$user = new User();
$user->username = $_REQUEST['username'];
$user->password = $_REQUEST['password'];
// Validate user
$found = $user->checkLogin();
if($found == true) {
//redirect to home page
$_SESSION['current_user'] = $user;
// Assign username to session for check on homepage and elsewhere
// If not logged in, this session variable should not be set
// Should be destroyed if user logs out.
$_SESSION['username'] = $_POST['username'];
header("Location: home.php");
exit;
}
//invalid username and password, redirect with login error
else
header("Location: login.php?error=login"); ?>
login.php
<html>
<head>
<title>Login Page</title>
</head>
<body>
<!-- If error, let user know their login failed-->
<p><?php echo (isset($_GET['error']) && $_GET['error'] == 'login')? '<span style="color: red;">Invalid Username/Password.</span> Please try again.':"Enter Username and Password to Login:"; ?></p>
<form action='login_process.php' method='post'>
<table border='1'>
<tr>
<td>Username:</td>
<td><input type='text' name='username'></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password'></td>
</tr>
<tr>
<td>&nbsp</td>
<td><input type='submit' value='Login'></td>
</tr>
</table>
</form>
</body>
</html>
session_start()
If Session["user"] == null, redirect to the login page
In the login page, get password using form
Post this form to the login page
Check your authentication service (e.g. a table in mysql) wether the user is authorized
If yes, Session["user"] = $userName, redirect the user to the page.
If no, prompt for password again
1) You dont seem to be assigning any value to $_SESSION['logged_in'], hence your first assertion mighr be returning true. why not check if the 'current_user' is set instead?
2) You are using an exact equality operator (read: !==) at this line:
$_SESSION['logged-in'] !== true
If it is not (of type boolean and true) or ($_SESSION does not exist) the assertion will always be true, leading to the login page.
3) Have you done a session_start before checking the $_SESSION superglobal? If not the $_SESSION variable will not be populated with anything.

correct username and password doesn't have any effect PHP

I have some problem in php. Here is my code:
if (isset($_POST['submit'])) { // Form has been submitte
echo "Submitted";
$username = trim($_POST['username']);
$password = trim($_POST['password']);
// Check database to see if username/password exist.
$found_user = User::authenticate($username, $password);
if ($found_user) {
$session->login($found_user);
redirect_to("index.php");
}
} else { // Form has not been submitted.
$username = "";
$password = "";
}
?>
<html>
<head>
<title>Photo Gallery</title>
<link href="../stylesheets/main.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1>Photo Gallery</h1>
</div>
<div id="main">
<h2>Staff Login</h2>
<form action="login.php" method="post">
<table style="float: left;">
<tr>
<td>Username:</td>
<td>
<input type="text" name="username" maxlength="30" value="
<?php echo htmlentities($username); ?>" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" maxlength="30" value="
<?php echo htmlentities($password); ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Login" />
</td>
</tr>
</table>
</form>
</div>
<div id="footer">Copyright <?php echo date("Y", time()); ?>, Gio baramidze</div>
</body>
</html>
My problem is that when i try to log in with incorrect user everything works fine and message "submitted" comes on the screen. But when i write correct username and password and click "Log in" it doesn't even show me the message ("submitted"). It means that "if (isset($_POST['submit']))" this condition isn't true. Despite the fact that I've clicked Submit. Thanks.
My guess is above code is index.php. When a user is found it redirects to the same page (quickly) and thus no $_POST is set since it is reloaded.
if ($found_user) {
$session->login($found_user);
redirect_to("index.php"); //If user found redirect without $_POST information.
}
You should make use of the $_SESSION array. This is a server side array, you can fill it with a user ID once a user logs in. On every page where you need to check a login you should include a script that checks for the this ID. You can also use this to store a users name or other stuff you need frequent access to:
$_SESSION['USER_ID'] = //Some ID
$_SESSION['USERNAME'] = $username
To make $_SESSION work you need something like this:
<?php
session_start();
//other code...
if ($found_user) {
$session->login($found_user);
//give the user an ID
$_SESSION['USER_ID'] = //some id, usually fetched from a database
//Let's give a name too
$_SESSION['USERNAME'] = $username;
//Now redirect
redirect_to("index.php"); //If user found redirect without $_POST information.
}
//Other code...
?>
Now from index.php we start again with session_start(); and we can use php to retrieve his ID and name. Put this on top and you see that $_SESSION gets carried over to other pages on the server.
<?php
session_start();
echo $_SESSION['USER_ID'];
echo $_SESSION['USERNAME'];
//or something nicer
if (isset($_SESSION['USER_ID']))
{
echo "User ".$_SESSION['USERNAME']." has logged in and has user id [".$_SESSION['USER_ID']."].";
}
else
{
echo "Not logged on."
}
?>
For testing purpose you can store the above code in whatever.php and redirect to whatever.php inside your login.php. It should pass the if statement if a user is found on login.php and thus show the username and ID.
You might change isset($_POST['submit']) by
if(isset($_POST['username']) && isset($_POST['password'])){
//do your stuff here
}

Categories