Display welcome message with the username in php & mysql - php

I am creating a form for log in and log out .
My problem is when a user submit their username and password then display welcome message with that username.Files are given below.
include.php
<?php
session_start();
$host = "VKSolutions";
$username = "VKSolutions";
$password = "VKSolutions#1";
$db = "VKSolutions";
#mysql_connect($host,$username,$password) or die ("error");
#mysql_select_db($db) or die("error");
?>
login.php
<?php
require_once('include.php');
$error = '';
$form = $_POST['submit'];
$user = $_POST['user'];
$password = $_POST['password'];
if( isset($form) ) {
if( isset($user) && isset($password) && $user !== '' && $password !== '' ) {
$sql = mysql_query("SELECT * FROM `accounts` WHERE user='$user' and
password='$password';");
if( mysql_num_rows($sql) != 0 ) { //success
$_SESSION['logged-in'] = true;
header('Location: members.php');
exit;
} else { $error = "Incorrect login info"; }
} else { $error = 'All information is not filled out correctly';}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Login</title>
</head>
<body>
<table width="80%" border="0"><form action="<?php $PHP_SELF; ?>" method="post" >
<tr>
<td><label>Employee Name:</label></td>
<td><input name="user" placeholder="Enter Name" type="text" value="<?php echo "$user";?>" /></td>
</tr>
<tr>
<td><label>Password:</label></td>
<td><input name="password" placeholder="Enter Password" type="password" /></td>
</tr>
<tr>
<td> </td>
<td><input valin="right" name="submit" type="submit" value="Log In" /></td>
</tr></form>
</table>
<?php
echo "<br /><span style=\"color:red\">$error</span>";
?>
</body>
</html>
members.php
<?php
require_once('include.php');
if ( !isset($_SESSION['logged-in']) || $_SESSION['logged-in'] !== true) {
header('Location: login.php');
exit;
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Staff Area</title>
</head>
<body>
<div style="margin-top:50px; color:#00F; margin-left:50px; font-size:18px; position:absolute">Welcome<?php echo "$user";?></div>
</body>
</html>
logout.php
<?php
session_start();
// if the user is logged in, unset the session
if (isset($_SESSION['logged-in'])) {
unset($_SESSION['logged-in']);
}
// now that the user is logged out,
// go to login page
header('Location: login.php');
?>
In my members.php it is log in but not display with username. I need that username.
Please find out what is wrong.
Thanks.

You need to create $_session variable since HTTP is a stateless protocol. Your variables defined in login.php is not available to members.php unless you store them in session.
first in the login.php
session_start();
$_SESSION['user'] = $_POST['user'];
then in your members.php file
session_start();
$user = $_SESSION['user'];
will allow you to access it.

Just use a session variable like $_SESSION['user']= $_POST['user']; and then display it using echo $_SESSION['user'].
Also make sure that you add session_start(); at the beginning of the php file.

You need to register your session username like this
session_start();
$_SESSION['user'] = $_POST['user'];
then retrieve your session username to display username message
echo $_SESSION['user'];

Related

PHP Session not recognizing variable when heading to another page

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

Undefined index: email in C:\Apache24\htdocs\checkup.php on line 10

i am new in php and i m creating a login system in my website every thing is working fine but 2 error are appearing in top of my website in every page,
Undefined index: email in C:\Apache24\htdocs\checkup.php on line 10
i have checked my mysql schema and coding but unable to find error please suggest me something to solve this error.
This is checkup.php page codding
<?php
include('dbconn.php');
if(!isset($_SESSION))
{
session_start();
}
$user_check= $_SESSION['email'];
$sql = mysqli_query($db,"SELECT fullname, email FROM register WHERE email='$user_check' ");
$row=mysqli_fetch_array($sql,MYSQLI_ASSOC);
$login_user = $row['email'];
$msguser = $row['fullname'];
?>
and this is login.php & loginconn.php page
<html>
<head>
<title>online shopping</title>
<?php
include 'header.php';
include 'dbconn.php';
include 'loginconn.php';
if ((isset($_SESSION['email']) != ''))
{
header('Location: index.php');
}
?>
<body>
<br>
<fieldset class="login_div">
<legend>User Login</legend>
<form method="POST" action="" >
<table border="0" cellspacing="10" >
<tr>
<td><?php echo $error; ?></td>
</tr>
<tr>
<td width="279"><center>            <label>Email:</label></td>
<td width="385"><input type="text" id="email" name="email" placeholder="email"></td>
</tr>
<tr>
<td><center>           <label>Password:</label></td>
<td><input type="password" name="password" placeholder="password"/></td>
</tr>
<tr>
<td colspan="2"><input class="loginbtn" type="submit" name="submit" value="Login" /></td>
</tr>
</table>
</form>
</fieldset>
</body>
</html>
<?php
include("dbconn.php");
$error = "";
if(isset($_POST["submit"]))
{
if(empty($_POST["email"]) || empty($_POST["password"]))
{
$error = "Both fields are required.";
}else
{
$email=$_POST['email'];
$password=$_POST['password'];
$email = stripslashes($email);
$password = stripslashes($password);
$email = mysqli_real_escape_string($db,$email);
$password = mysqli_real_escape_string($db,$password);
$password = md5($password);
$sql="SELECT id FROM register WHERE email='$_POST[$email]' and password='$_POST[$password]'";
$result= mysqli_query($db,$sql);
$row= mysqli_fetch_array($result, MYSQLI_ASSOC);
if( mysqli_num_rows($result) == 1)
{
$_SESSION['email'] = $email;
header("location: index.php");
}
else
{
$error = "Incorrect username or password.";
}
}
}
?>
you missed session_start() function call in file loginconn.php. Add the same code as in checkup.php:
if(!isset($_SESSION))
{
session_start();
}
How do you call checkup.php php page ?
Add the action: <form method="POST" action="checkup.php" > on your login page.
And test before any other test that the form has been submitted :
if(isset($_POST["submit"])) { // other tests }
More important, you've forgotten the session_start at the beginning of the page :
session_start();
This will maintain the session and the variables of it.

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'];

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'];

php mysql + session problems

i am creating a simple login and logout script using php and mysql but when i try to enter the login.php or the index file i get an error message that say :
**The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept
cookies.**
i do not know how to solve or what is the error if anyone help me i will be appreciate
index.php
<?php
require_once('connect.php');
ob_start();
session_start();
//checked wether the user is loged in or not
$user = $_SESSION['username'];
if(!isset($_SESSION['username']))
{
$user = $_SESSION['username'];
header("Location: index.php");
exit();
}
else
{
header("Location: home.php");
}
// login script
if(isset($_POST['username'])&& isset($_POST['password']))
{
$user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['username']);
$user_password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['password']);
$md5password = md5($user_password);
$sql = mysql_query("SELECT id FROM members WHERE username = '".$user_login."' AND password = '".$user_password."'") or die ("could not select from database");
$userCount = mysql_num_rows($sql);
if($userCount ==1)
{
while($row = mysql_fetch_array($sql))
{
$id = $row['id'];
}
$_SESSION['id'] = $id;
$_SESSION['username'] = $user_login;
$_SESSION['password'] = $user_password;
header("Location: index.php");
exit();
}
else
{
echo "that info is incorrect";
exit();
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="login.php" method="post">
<input name="username" type="text" value="username" size="32" />
<input name="pass" type="password" value="password" size="32" />
<input name="login" type="submit" value="login" />
</form>
</body>
</html>
<?php ob_end_flush(); ?>
home.php
<?php
//home.php
session_start();
$user = $_SESSION['username'];
if(!isset($_SESSION['username']))
{
header("Location: index.php");
exit();
}
else
{
echo "hi $user you are loged in //Welcome to our website Logout";
}
?>
logout.php
<?php
session_start();
session_destroy();
header("Location: index.php");
?>
In index.php you need to put this if condition on top after 'session_start();'
if($_SESSION['username'])
{
header("Location: home.php");
exit();
}
In while loop it should be header("Location: home.php"); instead of header("Location: index.php");
In home.php page you should put on top after opening php tag
ob_start();
session_start();
Hope it will work.
++++++++++++++++++++++++++++++++++++++++++
Use this code
index.php
<?php
require_once('connect.php');
ob_start();
session_start();
//checked wether the user is loged in or not
$user = $_SESSION['username'];
if($_SESSION['username'])
{
$user = $_SESSION['username'];
header("Location: home.php");
exit();
}
// login script
if(isset($_POST['username'])&& isset($_POST['password']))
{
$user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['username']);
$user_password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST['password']);
$md5password = md5($user_password);
$sql = mysql_query("SELECT id FROM members WHERE username = '".$user_login."' AND password = '".$user_password."'") or die ("could not select from database");
$userCount = mysql_num_rows($sql);
if($userCount ==1)
{
while($row = mysql_fetch_array($sql))
{
$id = $row['id'];
}
$_SESSION['id'] = $id;
$_SESSION['username'] = $user_login;
$_SESSION['password'] = $user_password;
header("Location: home.php");
exit();
}
else
{
echo "that info is incorrect";
exit();
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="login.php" method="post">
<input name="username" type="text" value="username" size="32" />
<input name="pass" type="password" value="password" size="32" />
<input name="login" type="submit" value="login" />
</form>
</body>
</html>
<?php ob_end_flush(); ?>
home.php
<?php
ob_start();
session_start();
//home.php
$user = $_SESSION['username'];
if(!isset($_SESSION['username']))
{
header("Location: index.php");
exit();
}
else
{
echo "hi $user you are loged in //Welcome to our website Logout";
}
?>
logout.php is correct
First, in index.php you don't need to "//checked wether the user is loged in or not", we should check that in home.php.
This code is causing your error : "The page isn't redirecting properly Firefox has detected that the server is redirecting the request for this address in a way that will never complete". You made a repetition (The session is not created but it is checked ...).
Second, in home.php, You have to write session_start() method, this is the code require when using session.
Refer my code:
index.php
<?php
ob_start();
session_start();
//check session is existed
if (isset($_SESSION['username'])) {
header("Location: home.php");
}
if (isset($_POST['username']) && isset($_POST['password'])) {
$user_login = $_POST['username'];
$user_password = $_POST['password'];
if ($user_login == 'namluu' && $user_password =='123456') {
$_SESSION['username'] = $user_login;
$_SESSION['password'] = $user_password;
header("Location: home.php");
exit();
} else {
echo 'Infor not correct';
exit();
}
}
?>
<html>
<head></head>
<body>
<form action="index.php" method="post">
<input type="text" name="username" />
<input type="text" name="password" />
<input type="submit" name="login" value="login" />
</form>
</body>
</html>
<?php
ob_end_flush();
?>
home.php
<?php
session_start();
//home.php
$user = $_SESSION['username'];
if(!isset($_SESSION['username']))
{
header("Location: index.php");
exit();
}
else
{
echo "hi $user you are loged in //Welcome to our website Logout";
}
?>
You haven't got session_start() at the top of home.php, which means you will have created an infinite loop between home.php and index.php.
Currently what is happening is when you access index.php, it recognises the session and redirects the user to home.php. As there is no session_start() in home.php, it doesn't recognise the session and redirects the user back to index.php. Thus you have an infinite loop.

Categories