$_SESSION Variable Validation Leads to Blank PHP Page / No Content - php

Successful login on my login page should direct to a homepage (which it does - I double checked to see is the variables are set and they are when a correct username/password is entered). Otherwise, the login page should be private.
LOGIN PHP (works fine)
<?php
session_start();
require_once("../inc_files/Lesson_5_DB_Connection.php");
error_reporting(E_ALL);
ini_set('display_errors', 1);
$error_message= "";
$user_name = "";
$user_password= "";
$_SESSION['username']="";
$_SESSION['employeeNumber']="";
if (isset($_POST['submit'])) {
$user_name = $_POST['user'];
$user_password= $_POST['pass'];
// ADD QUERY TO CHECK IF USER/PASS COMBO IS CORRECT
if(!empty($user_name) && !empty($user_password)) {
$query = "SELECT * FROM employees WHERE username='$user_name' and password='$user_password'";
$result = mysqli_query($dbc, $query)
or die ('Error querying username/password request');
if(mysqli_num_rows($result) == 1) {
while ($row = mysqli_fetch_array($result)) {
$_SESSION['username'] = $row['username'];
$_SESSION['employeeNumber'] = $row['employeeNumber'];
}
header("Location: /LESSON5/3%20-%20HOMEPAGE%20:%20WELCOME.php");
exit;
} // end if rows
else {
$error_message = "You were not able to log in";
} // end else
// Direct to other webpage
} // end query
} // end isset
?>
The homepage should only be visible if the $_SESSION variables are set. If the user is not logged in (session variables not set) then the homepage should redirect to the login page. Now, I added a validation to see if variables are not set (!isset). This validation keeps the page from showing any content. When I delete this validation the HTML shows up fine. When I delete the validation and echo the variable values I get the values returned.
It's just the if(!isset($_SESSION['username']) && !isset($_SESSION['employeeNumber']) keeping from showing any content on the page.
HOMEPAGE
<?php
session_start();
require_once("../inc_files/Lesson_5_DB_Connection.php");
if(!isset($_SESSION['username']) && !isset($_SESSION['employeeNumber']) {
header("Location: /LESSON5/1%20-%20LOGIN.php");
}
?>
<!DOCTYPE html>
<head>
<title></title>
<meta charset="utf-8">
<link type="text/css" rel="stylesheet" href="/LESSON5/5_Signup_CSS.css">
</head>
<body>
<p><span id="logout">Logout</span></p>
<hr>
<h1>Welcome to my homepage! <br> You have successfully logged in.</h1>
<?php
mysqli_close($dbc);
?>
</body>
</html>
Is there any reason why that validation is keeping the PHP from showing the HTML(if user login is correct) or redirect the page(if user not logged in)?

Basically error is in your php if condition. One parenthesis is missing. change like this:-
if(!isset($_SESSION['username']) && !isset($_SESSION['employeeNumber']))
Note:- try to add error_reporing at the top of your all php pages so that you can get php errors if happen. check the manual of error_reporing on php site. Thanks.
If you are working on local server you can change your php.ini settings for this.
You can get how to change php.ini setting on google easily.
ini_set is function of php is for this purpose if you want to do it programmatically not with php.ini directly.

Related

My session is not passing to the different page

The session is not passing and I want to restrict the users from viewing the login page while they are logged in for that I tried many things, but it didn't work:
My login page
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('connect.php');
extract($_POST);
$result = mysqli_query($link, "SELECT * FROM users ");
$row = mysqli_fetch_assoc($result);
//var_dump($row['username']);
//var_dump($row['password']);
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
if ($username == $row['username'] && $password == $row['password']){
session_start();
$_SESSION['nID'] = true;
//echo"Login";
header('Location: home.php');
} else {
echo"Login failed";
}
}
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title>Login page</title>
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<body>
<div id="frm">
<form action="login.php" method="POST" style="width: 232px; padding-left: 490px;">
<h1> Login</h1>
<p>
<label>Username</label>
<input type="text" id="username" name="username" />
</p>
<p>
<label>password</label>
<input type="password" id="password" name="password"/>
</p>
<p>
<input type="submit" id="btn" value="login" name="login" style="border-radius: 30%; background-color: gold; box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);"/>
</p>
<p>
Not yet a member Register here
</form>
</div>
</body>
</html>
My home page
<?php
session_start();
if ($_SESSION['nID'] == false) {
header("Location: login.php");
die();
} elseif ($_SESSION['nID'] == true) {
header("Location: Home.php");
die();
} else {
echo"cant connect";
}
?>
<html>
<head>
<link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<ul class="nav nav-pills">
<li role="presentation" class="active">Home</li>
<li role="presentation">Information</li>
<li>Logout
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</body>
</html>
The session is not passing and it doesn't prevent the user from viewing the homepage while they aren't logged in.
I have tried many different things, but nothing seems to work.
Some thoughts on this question:
1) Stop using extract(). You simply don't need it.
Warning Do not use extract() on untrusted data, like user input (i.e. $_POST, $_FILES, etc.). If you do, for example if you want to temporarily run old code that relied on register_globals, make sure you use one of the non-overwriting flags values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.
From the Manual.
2) As noted in another answer Your SQL query is far too vague; you're returning the first answer of a search of the whole DB rather than searching for any specific criteria.
SELECT password FROM users WHERE username=username_here LIMIT 1
And then take this row and compare with the given password:
if($password === $row['password'])
3) Your password system used on MySQL / PHP is NOT GOOD ENOUGH. Stop using md5() and employ password_hash and password_verify PHP functions. Please read how to do it properly and this comment.
4) Every time you use header("Location: ...") to redirect the user it is highly recommended you add a die or exit command immediately afterwards in order to cease the code execution on the current page. For example:
header("Location: this_page_will_never_load.php");
header("Location: this_page_will_always_load_instead.php");
5) require and include functions do not require brackets.
NOTE
Re the numerous answers here referencing session_start(); if session_start() is called after output is sent to the browser, then there will be an error notice generated. OP has not reported an error notice even with:
error_reporting(E_ALL);
ini_set('display_errors',1);
So session_start() placement in the code is not an issue in this specific situation.
However:It is best practise to put your session_start() as early as possible in your code and before such debug things as var_dump which would cause session_start not to load becase var_dump has already thrown data out to the browser.
Finally, an answer to your problem:
I want to restrict the users from viewing the login page while they are logged in for that I tried many things but it didn't work:
Your code in login.php:
if(isset($_POST['login'])){
///session stuff etc.
}
The above code on your login.php page will only execute if the page is being given POSTed data. What you have is that once someone is logged in correctly and they then return to the login.php page, they are not resubmitting the POSTed data so this code block is simply not running.
Because this code block contains all your $_SESSION references this is why it looks like $_SESSION is not running.
Instead you want to do this (simplified) in login.php:
session_start();
if(isset($_POST['login'])){
// setup session values,
// once POSTed login data is checked and authorised in the database
$_SESSION['nID'] = true;
}
elseif ($_SESSION['nID'] === true){
// is already logged in so redirect to the index page.
header("Location: index.php");
exit;
}
else {
// this fires if no POSTed data is sent and no valid
// session is found.
}
Try this condition in your home.php file:
session_start();
if (!isset($_SESSION['nID']) || empty($_SESSION['nId'])) {
header("Location: login.php");
die();
}
You try this code:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('connect.php');
extract($_POST);
$result = mysqli_query($link, "SELECT * FROM users ");
$row = mysqli_fetch_assoc($result);
//var_dump($row['username']);
//var_dump($row['password']);
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
if ($username == $row['username'] && $password == $row['password']){
//session_start(); removed it
$_SESSION['nID'] = true;
//echo"Login";
header('Location: home.php');
} else {
echo"Login failed";
}
}
?>
On every page, you need to add session_start() in the page heading.
First: First of all, your query is wrong. You're always checking the value with the first user in the table. You need to a query with the where clause.
SELECT * FROM users WHERE username=username_here AND password=hash_password_here
Second: Your If statement should be like the following.
<?php
session_start();
if (!isset($_SESSION['nID'])) {
header("Location: login.php");
die();
}
?>
Third: Try to use prepared statements to avoid an SQL injection.
$stmt = $link->prepare("SELECT * FROM users where username=? and password=?");
$stmt->bind_param('ss', $username, md5($password));
$stmt->execute();
$get_result = $stmt->get_result();
$row_count = $get_result->num_rows;
if ($row_count > 0) {
session_start();
$_SESSION['nID'] = true;
header('Location: home.php');
die();
}
else {
echo"Login failed";
}
4th: Don't use Md5() for passwords. Try to use password_hash() and password_verify(). Reference link.
While registrating, use password_hash() to hash the password and store it in the database and while logging in, use password_verify() to verify the password like this. Reference link.
You have to call the session_start() function in the file where you are trying to use a session variable.
You need to add session_start(); on every page to get the session variables.

STARTING a LOGIN SESSION in PHP

I have created a login script and it works fine, however, I would like to implement sessions.. I am currently having some trouble with it because my session script is only partially executed. Below is my login script and the test page I'd like it to redirect to, IF the user is logged in.. I want it to display the test page, if not, then I want it to redirect back to the login page (or in this case, the index.php file) and ask the user to login... see code below:
loginconfig.php:
<?php
// Create a connection
include("dbconfig.php");
if (isset($_POST['submit'])) {
if (empty($_POST['username']) or empty($_POST['password'])) {
header("location:index.php?msg0=Please complete the required fields.");
}
elseif (!empty($_POST['username']) && !empty($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = mysqli_query($conn, "SELECT * FROM logininformation WHERE username = '$username' and password = '$password'") or die(mysqli_error($conn));
$login = ($sql) ? mysqli_fetch_assoc($sql) : false;
if (($login) == 0) {
header("location:index.php?msg1=Invalid username or password, please try again.");
}
elseif (($login) > 0) {
session_start();
$_SESSION['login'] = $_POST['username'];
//header("location:index.php?bid=$username&msg2=You are unable to log in at this time. Website is under construction.");
header("location:test.php?bid=$sessionwork");
}
}
}
?>
test.php:
<?php
session_start();
include("dbconfig.php");
$username = $_GET['bid'];
var_dump($_SESSION['login'];
// If user is logged in:
if(!empty($_SESSION['login'])){
echo "Welcome $username";
}
// If user is not logged in:
elseif(!isset($_SESSION['login'])){
header("location:index.php?msg4=You need to be logged in!");
}
?>
<html>
<head>
<title> user page </title>
</head>
<body>
<form name="logout" method="post" action="logout.php">
<input type="submit" name="logout" value="logout">
</form>
</body>
</html>
logout.php
<?php
session_start();
if(!empty($_SESSION['login'])){
session_destroy();
?>
<html>
Homepage
</html>
Now if you look at the test.php file.. I have sort of told it to check if a user is logged in. But unfortunately, the script only manages to execute the script where it says if the user is not logged in.. redirect to index.php... even if the user enters the correct login credentials and actually logs in. What could be the issue?
Any help will be much appreciated.
It should be like this in test.php:
if(isset($_SESSION['login'])){
echo "Welcome $_SESSION['login']";
}
else{
header("location:index.php?msg4=You need to be logged in!");
}
The same error is repeated in loginconfig.php.
Initially, I did not have a logout.php file.. therefore I was making the mistake of not destroying my session. The change I had to make to my initial scripting was to create a logout.php file. But when I did, the problem was still present.. in order for it to work.. I made the following changes to the logout.php file.. see below:
BEFORE:
<?php
session_start();
if(!empty($_SESSION['login'])){
session_destroy();
?>
<html>
Homepage
</html>
AFTER:
<?php
session_start();
session_destroy();
header("location:index.php");
exit();
?>
Thank you for those who helped, especially #Epodax for the GREAT support.

PHP Checking if session is registered

I am creating a simple login script, I have set everything up but I am having trouble with sessions.
At the end of the login check page I have the following code:
$count = mysql_num_rows($result);
if($count == 1){
$_SESSION["username"] = 'username';
$_SESSION["password"] = 'password';
header("location:success.php");
}else{
echo "Wrong username or password";
}
And on the success.php page I have the following:
<?php
session_start();
if (!isset($_SESSION['username'])) {
header ("Location: wrong.php");
}
?>
<html>
<body>
Login Successful
</body>
</html>
The problem is that when a correct user and pass is entered it takes you to wrong.php, whereas it needs to redirect to wrong.php when someone visits success.php without logging in.
I am quite new to sessions and would appreciate any help. Thanks.
You must make sure session_start() is present at the top of any document that requires using sessions..
So at the top of your login check page you need to include session_start();

php login script not executing correctly

Hey guys I'm creating a simple login script. When I enter a valid username and password, the function calls login_success.php but nothing happens. I've used the following links for resources:
http://www.phpeasystep.com/phptu/6.html
http://forum.codecall.net/topic/44787-creating-loginregistration-forms-with-php/#axzz2DwhIYfzj
http://frozenade.wordpress.com/2007/11/24/how-to-create-login-page-in-php-and-mysql-with-session/
I've also searched a number of posts on this site as well. Your help is always appreciated. Here's the code:
login.php
<?php
ob_start();
include 'connect.php';
$usernamefield = $_POST['usernamefield'];
$passwordfield = $_POST['passwordfield'];
$sql = "SELECT * FROM login WHERE username = '$usernamefield' and password = '$passwordfield'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1) {
session_register("usernamefield");
session_register("passwordfield");
header("Location: login_success.php");
} else {
echo "Invalid username or password";
}
exit();
?>
login_success.php
<?php
session_start();
if(!session_is_registered(myusername)){
header("Location: login.php");
}
?>
<html>
<body>
Login Successful
</body>
</html>
Put session_start(); at the top of your login.php file.
Set session variables using $_SESSION['variable']='value';.
Check access using if(isset($_SESSION['variable'])){ and that should get it done.
The session_register('variable'); is deprecated and should not be used, along with session_is_registered('variable'): http://php.net/manual/en/function.session-register.php
If you are trying to get this to work in a new PHP installation, you could possibly be using 5.4.x, and those functions have been removed, so they do not work.

php header command isn't working

I'm having a problem getting this code to work on the website that I'd like to launch soon. In particular when I sign in the header won't redirect after a successful login. I have used this code before many times and I've never had a problem with it. The only difference now is that I'm using a different server and a different database. Here's the code that is giving me trouble:
<?php
/*set all the variables*/
$email = $_POST['email'];
$password = sha1($_POST['password']); /* hash the password*/
$conn = mysqli_connect ('servername', 'username', 'password', 'databasename') or die('Error connecting to MySQL server');
/*select the id from the users table that match the conditions*/
$sql = "SELECT id FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
$count = mysqli_num_rows($result);
if ($count == 1) {
echo 'Logged in Successfully.';
$row = mysqli_fetch_array($result);
session_start();
$_SESSION['user_id'] = $row['id'];
/*If true head over to the users table*/
header('location: users_table.php');
}
/*If invalid prompt them to adjust the previous entry*/
else {
echo '<h2>Invalid Login</h2><br />';
echo '<h2>Click HERE to go back and adjust your entry.</h2>';
}
mysqli_close($conn);
?>
It's not a matter of it connecting properly because I get the message 'successful Login' but it won't redirect at all.
Thanks for all the answers, I tried removing the echo but all I get now is a blank page, I thought maybe it was the browser I was using so I switched to another and I still just get a blank page, any other suggestions?
You cannot echo anything before your header statement.
echo 'Logged in Successfully.';
This is causing the header call to not work.
if ($count == 1) {
echo 'Logged in Successfully.';
//this statement is creating problem
$row = mysqli_fetch_array($result);
session_start();
$_SESSION['user_id'] = $row['id'];
/*If true head over to the users table*/
header('location: users_table.php');
}
This is because you are echoing something berfore header
You should use ob_start() at start and ob_end_flush() at the end of the document..
or do not echo before header().As we found you haven't turned on the error.So turn it ON.
You can't be posting the header after the echo... if this actually worked you'd never see the text (it would simply redirect). (To fix remove/comment out the echo line)
Also the location header requires an absolute/full URL (although many browsers seem to cope with relative URLs).
If you want to do it this way (show some sort of status before hand), use an HTML or Javascript redirect that triggers after a couple of seconds.
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Logged in Successfully.</title>
<meta http-equiv="REFRESH"
content="5;url=http://www.example.com/users_table.php"></HEAD>
<BODY>
Logged in Successfully.
</BODY>
</HTML>
Javascript
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>Logged in Successfully.</title>
</HEAD>
<BODY onLoad="setTimeout(function() {
window.location='http://www.example.com/users_table.php'},5000)">
Logged in Successfully.
</BODY>
</HTML>
Better yet, allow the users_table.php page to display a successful login message and use the header-location redirect.

Categories