PHP Session not recognizing variable when heading to another page - php

So I'm making a Login - Successful Login page with PHP, and using MySQL Database. My code successfully checked the Username and Password and only allowed me to head to the next page once they are correct.
However, I cannot print out the Username on Successful Login page. So I'm not sure if my session is running properly or not.
login.php
<!DOCTYPE HTML>
<html>
<?php
session_start();
?>
<head>
<title>Login</title>
</head>
<body>
<!--<form action ="SuccessfulLogin.php" method = "get"> --> // If I put this in my code, the whole program stops checking Username and Password, and just put me to the next page
<?php
//define variables and set to empty values
$nameErr = $loginErr = "";
$Username = $website = $Password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Username"])) {
$nameErr = "Name is required";
} else {
$Username = test_input($_POST["Username"]);
}
if (empty($_POST["Password"])) {
$passErr = "Password is required";
} else {
$Password = test_input($_POST["Password"]);
}
//continues to target page if all validation is passed
if ( $unameErr ==""&& $passErr ==""){
// check if exists in database
$dbc=mysqli_connect('localhost','testuser','password','Project')
or die("Could not Connect!\n");
$hashpass=hash('sha256',$Password);
$sql="SELECT * from Members WHERE Username ='$Username' AND Password='$hashpass';";
$result =mysqli_Query($dbc,$sql) or die (" Error querying database");
$a=mysqli_num_rows($result);
if ($a===0){
$loginErr="Invalid username or password";
}else{
$_SESSION["Username"]=$Username;
header('Location: /SuccessfulLogin.php');
}
}
}
// clears spaces etc to prep data for testing
function test_input($data){
$data=trim ($data); // gets rid of extra spaces befor and after
$data=stripslashes($data); //gets rid of any slashes
$data=htmlspecialchars($data); //converts any symbols usch as < and > to special characters
return $data;
}
?>
<h2 style="color:yellow" align="center"> Login </h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" align="center" style="color:#40ff00">
User Name: <input type="text" name="Username" value="<?php echo $Username;?>"/>
<span class="error">* <?php echo $unameErr;?></span>
<br/><br/>
Password:
<input type="text" name="Password" value=""/>
<span class="error">* <?php echo $passErr;?></span>
<br/><br/>
<span class="error">* <?php echo $loginErr;?></span>
<input type="submit" name="submit" value="Login"/> 
</form>
<!--</form>--> // closing tag of form action SuccessfulLogin.php
</html>
SuccessfulLogin.php
<!doctype html>
<html>
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
<head>
<meta charset="utf-8">
<title>Login Form</title>
<link rel="stylesheet" href="RegisterLogin.css">
</head>
<body>
<!--<form action ="MemberMenu.php" method = "get">-->
<h2><?php echo "User $Username LOGGED IN"; ?></h2> // Doesn't print out the $Username
<p align="center"> Click here to be redirected to the menu page </p>
<!--</form>-->
</footer>
</body>
</html>

you need to check session isset or not.
Change
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
With
<?php
session_start();
if (isset($_SESSION['Username'])) {
$Username=$_SESSION['Username'];
echo $Username;
}
?>

You're using $_GET["Username"] which will be empty in this example, and then setting $_SESSION["Username"] to the empty variable.
Also this is a very odd way to do user auth.

Change this line of code
<?php
session_start();
$Username=$_SESSION['Username'];
$_SESSION['Username']=$Username;
?>
Into:
<?php
session_start();
$Username=$_SESSION['Username'];
?>
Read more about PHP session here

Related

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
?

Why i cannot display the error message in the login page?

i want to display my error message in the login form by getting the result from the login.php ,here is the sample code that i have use.The first part is the index.php
<?
include("login.php");?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<h1>Hup Seng</h1>
<div id="login">
<h2>Login Form</h2>
<form action="login.php" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text" required>
<br>
<br>
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password" required>
<br>
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
</body>
</html>
Here is the login.php i have put the error message under the else statement in order to pass the information to the login form
<?php
include("dbconfig.php");
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
//if (isset($_POST['submit'])) {
if (isset($_POST['username']) || isset($_POST['password'])) {
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
$pw = encode($password);
$sql = "SELECT count(ID) as cid FROM tblUser WHERE UserId = '$username' and Password1 = '$pw'";
$rs = odbc_exec($link_mssql,$sql);
while (odbc_fetch_row($rs)) {
$count=odbc_result($rs,"cid");
}
if ($count == 1) {
$_SESSION['username']=$username; // Initializing Session
header("location: homepage.php"); // Redirecting To Other Page
} else {
$error="username/passwod combination incorrect";
header("location: index.php");
}
odbc_close($link_mssql); // Closing Connection
}
//}
?>
No need to add header you already including login.php file in index.php
$error="username/passwod combination incorrect";
//header("location: index.php");//remove this line
session_start();
$_SESSION['error']="username/passwod combination incorrect";
and in login form check
session_start();
if(isset($_SESSION['error'])){
echo $_SESSION['error'];
}
//header("location: index.php");
Remove this or you can redirect the page after some time if you want like this.
header( "refresh:5;url=index.php" ); // page redirect after 5sec

This webpage has a redirect loop - PHP Login

I'm trying out a login page example in php. I get the error: This webpage has a redirect loop
Details say: Error code: ERR_TOO_MANY_REDIRECTS
Here's my code:
index.php
<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
login.php
<?php
session_start();
$error='';
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
$username=$_POST['username'];
$password=$_POST['password'];
$connection = mysql_connect("localhost", "root", "");
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$db = mysql_select_db("rjtest", $connection);
$query = mysql_query("select * from login where myPassword='$password' AND myUserName='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username;
header("location: profile.php");
} else {
$error = "Username or Password is invalid";
}
}
}
?>
profile.php
<?php
include('session.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>
<b id="logout">Log Out</b>
</div>
</body>
</html>
session.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("rjtest", $connection);
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql=mysql_query("select myUsername from login where myUsername='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
header('Location: index.php');
}
?>
And logout.php
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
I can't seem figure out why. The site where I got this code is now inactive, so that's why Im asking this here. Hope you guys could help me out. Sorry for the long post though.
Comment to answer:
What I think is going on is that your code is erroring out and you're not seeing it, causing it to fight against what it should be showing you as an error.
You have $login_session =$row['username']; using the "username" as the row, but you're not selecting it in your query select myUsername from login where myUsername.
So, I'm thinking that if that row doesn't in fact exist, you'd need to do
$login_session =$row['myUsername'];

stop repeat the actions on the page after submit the form

Stop repeat the actions on the page after submit the form
I made this "sign in" form and made a error messages to appear if the fields is empty and other error messages.
my request is:
After the "sign in" fails how to stop the fields from resubmit the values again when hit F5 or reload the page.
<?php
ob_start();
session_start();
include "config/config.php";
include "includes/functions/check.php";
$userName = $passWord = "";
$userNameErr = $passWordErr = $loginErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['user_name'])) {
$userNameErr = "User name is required";
} else {
$userName = check_input($_POST['user_name']);
if (!preg_match("/^[a-zA-Z ]*$/", $userName)) {
$userNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST['password'])) {
$passWordErr = "Password is required";
} else {
$passWord = check_input($_POST['password']);
}
$loginUser = $db->prepare("SELECT * FROM hired_person_info WHERE user_name=? AND password=?");
$loginUser->bind_param('ss', $userName, $passWord);
if ($loginUser->execute()) {
$results = $loginUser->get_result();
if ($results->num_rows == 1) {
$row = $results->fetch_object();
$_SESSION['name'] = $row->full_name;
$_SESSION['log'] = 1;
print_r($_SESSION);
header("Location:?pid=4");
} elseif (!empty($_POST['user_name']) && !empty($_POST['password'])) {
$loginErr = "Invalid Login Information";
}
}
}
ob_flush()
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Administration Panel</title>
<link href="../css/adminStyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 id="head" class="header_height"></h1>
<div class="contentLogin">
<div class="login_bg">
<div id="header">
<p>login</p>
</div>
<div id="form">
<?php
echo $loginErr;
?>
<form action="<?php htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label for="user_name" class="text_login">User name</label>
<input type="text" name="user_name" id="user_name" value="<?php echo $userName ?>">
<?php echo $userNameErr; ?>
<br/><br/>
<label for="password" class="text_login">Password</label>
<input type="password" name="password" id="password">
<?php echo $passWordErr; ?>
<br/>
<div id="submit">
<input type="submit" value="Sign in" name="submit" id="submit" class="btn">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Instead of using if($_SERVER["REQUEST_METHOD"] == "POST"){ try using the post name of your submit button. So the condition will be as follows,
if(isset($_POST['submit'])) {
}
Within this you can put all your codes. I am not telling that the condition you have used is wrong, but it may create conflict when you will put another form in the same page.
And after your operation completed, success or fail, does not matter just unset the post variable.
unset($_POST);
To completely avoid the resend functionality you need to redirect your page to the same page once. For that just save your error message in session and redirect to login page again. Then checking if session value for message exists then display your message.

Passing php variable from this.php to that.php

So I need to pass a variable from one php to another php page but I dont know how to do it. I got this piece of code "$realname= $row['name'];" that stores the real name of the person to display it in another page after they successfully login, but when I try to use $realname variable in the other page it wont display it. How can I make this posible??? thanks in advance
page one login.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
include 'functions.php';
if(loggedin())
{
header("Location: userarea.php");
exit();
}
if(isset($_POST['login']))
{
//get data
$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = $_POST['rememberme'];
//validate
if($username&&$password)
{
$login = mysql_query("SELECT * FROM users WHERE username='$username'");
if(mysql_num_rows($login) == 1)
{
while($row = mysql_fetch_assoc($login))
{
$db_password = $row['password'];
if($password == $db_password)
$loginok= TRUE;
else
$loginok = FALSE;
if($loginok==TRUE)
{
$realname= $row['name'];
if($rememberme == "on")
setcookie("username", $username, time() + 7200);
else if ($rememberme == "")
$_SESSION['username'] = $username;
header("Location: userarea.php");
exit();
}
else
die("Incorrect username or password. Please try again or contact your local admin.");
}
}die("Incorrect username or password. Please try again or contact your local admin.gdfgdfgdfg");
}
else
die("Please enter a username and password.");
}
?>
<h>Welcome!</h>
<form action="login.php" method="POST">
Username:<br />
<input type="text" name="username"><p />
Password:<br />
<input type="password" name="password"><p / >
<input type="checkbox" name="rememberme"> Remember me<br />
<input type="submit" name="login" value="Log in">
</form>
</body>
</html>
Page 2 userarea.php (as you can see I declared $realname variable but I cant use it)
<html>
<body>
<?php
include 'functions.php';
if(!loggedin())
{
header("Location: login.php");
exit();
}
echo "Hello $realname";
?>
<h>Access Granted! Yeiy! </h>
Log out
</body>
</html>
This is exactly what sessions are for:
Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data.
page one login.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
...
$_SESSION['realname'] = $row['name'];
Page 2 userarea.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
...
echo "Hello $_SESSION['realname']";
First pass $_SESSION['var_name']; on login page and then
start session_start() on the top of the userarea page and echo your session variable
echo $_SESSION['var_name'];

Categories