I am trying to add a welcome to user in a restricted area using PHP login system. I used this code to transfer usernale from first user login page to restricted page but it didnt work
if ( (isset($_POST['username'])) || (isset($_POST['password'])) {
$user = $_SESSION['username'];
}
Here are the files that I am using, Can you please take a look at them and let me know what I am doing wrong?
<form id="login-form" method="post" action="includes/login.inc.php">
<fieldset>
<legend>Login to Web Site</legend>
<label for="username">
<input type="text" name="username" id="username" />Username:
</label>
<label for="password">
<input type="password" name="password" id="password" />Password:
</label>
<label for="submit">
<input type="submit" name="submit" id="submit" value="Login" />
</label>
</fieldset>
I have a php login file which is like this:
<?php
require_once('config.inc.php');
require_once('functions.inc.php');
// Start session
session_start();
// Check if user is already logged in
if ($_SESSION['logged_in'] == true) {
// If user is already logged in, redirect to main page
redirect('../index.php');
} else {
// Make sure that user submitted a username/password and username only consists of alphanumeric chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
(!ctype_alnum($_POST['username'])) ) {
redirect('../login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
if (mysqli_connect_errno()) {
printf("Unable to connect to database: %s", mysqli_connect_error());
exit();
}
// Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// Construct SQL statement for query & execute
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . md5($password) . "'";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// Set session variable for login status to true
$_SESSION['logged_in'] = true;
redirect('../index.php');
} else {
// If number of rows returned is not one, redirect back to login screen
redirect('../login.php');
}
}
?>
and on my restricted page I have:
<?php
// Start session
session_start();
if ( (isset($_POST['username'])) || (isset($_POST['password'])) {
$user = $_SESSION['username'];
}
require_once('includes/functions.inc.php');
if (check_login_status() == false) {
redirect('login.php');
}
?>
<!DOCTYPE html>
<html>
<body>
<div id="page">
<a class="welcome">
Welcome: <?php echo $user; ?>
</a>
</div>
use
$_SESSION['username'] = $_POST['username'];
and then echo out $_SESSION['username']
EDIT
<?php
// Start session
session_start();
if (isset($_POST['username']) || isset($_POST['password'])) {
require_once('includes/functions.inc.php');
if (check_login_status() == false) {
redirect('login.php');
}
$_SESSION['username'] = $_POST['username'];
}
?>
<!DOCTYPE html>
<html>
<body>
<div id="page">
<a class="welcome">
Welcome: <?php echo $_SESSION['username']; ?>
</a>
</div>
Related
I wanted to show the variable username into another page. These are the codes I've used. This is the first page where the username is inserted.
<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<div id="login" align="center">
<h2>Welcome!</h2>
<form action="" method="post">
<label>Username :</label>
<input id="name" name="username" placeholder="username" type="text"><br>
<label>Password :</label>
<input id="password" name="password" placeholder="**********"
type="password">
<br><br>
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</body>
</html>
Then in this page I wanted to show the username that was inserted
<?php include 'database.php'; ?>
<?php session_start(); ?>
<?php
function visualizza($file) {
$f = fopen($file, "r"); // apro il file in lettura
return fread($f, filesize($file));
fclose($f);
}
?>
<html>
<main>
<div class="container">
<h2> Quiz Completato!</h2>
<p> Congratulations <?php
$username = $_POST['username'];
echo $username;
?>
! You completed the test</p>
<p>Final Score:<?php echo $_SESSION['score']; ?> </p>
</div>
</main>
I can't put form action="final.php", because this is the final page of a quiz, while the submit button has to send me to another page
Do you know how to do this please?
This is where the user and password are processed (login.php)
<?php
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// mysqli_connect() function opens a new connection to the MySQL server.
$conn = mysqli_connect("localhost", "root", "", "quizzer");
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT username, password from login where username=? AND
password=? LIMIT 1";
// To protect MySQL injection for Security purpose
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->fetch()) //fetching the contents of the row
{
$_SESSION['login_user'] = $username; // Initializing Session
header("location: quizzer.php"); // Redirecting To Profile Page
}
else {
$error = "Username o Password sbagliate";
}
mysqli_close($conn); // Closing Connection
}
}
?>
In your form element, the action attribute needs to go to another page submitting all the $_POST[] requests.
<form action="page2.php" method="post">
Now the $_POST['username'] can now be seen in the second page.
As soon as you login u may store the username in session as follows
$_SESSION['username'] = $_POST['username'];
And echo it on any page by starting starting session
echo $_SESSION['username'];
First and foremost, I have looked throughout the site and haven't been able to find a solution that works for my program.
Saying this, I am trying to create an authentication page that starts a session, and will save a username from a login page as a session variable. Then, I want my thrid page to retrieve the username session variable.
This is my Form:
<html>
<head>
<title>Form Test</title>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<h1 align="center">Log in with your username and</h1>
<form class="form-horizontal" method="POST" action="formauth.php">
<div class="form-group">
<div class="control-label col-sm-3">
<label for="card">Username:</label>
</div>
<div class="col-sm-5">
<input type="text" name="username" placeholder="enter username here">
</div>
</div>
<div class="form-group">
<div class="form-group">
<div class="control-label col-sm-3">
<label for="card">Password:</label>
</div>
<div class="col-sm-5">
<input type="text" name="password" placeholder="enter password here">
</div>
</div>
<div class="form-group">
<div class="control-label col-sm-3">
<div name="buttons" class="col-sm-offset-3">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</body>
</html>
Here is my authentication page. For some reason, I can't get this to save the username that is input into the form as a session variable.
<?php
session_start();
$_SESSION['username'] =$user_name;
if (isset($_POST['username']) &&
isset($_POST['password']))
{
$user = $_POST['username'];
$pwd = $_POST['password'];
require_once "login.php";
$conn = new mysqli($hn, $un, $pwd, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "Select Password from Users where Username = '$user'";
$result = $conn->query($query);
if (!$result) {
$result->close();
$conn->close();
header('Location: http://localhost/FormAuth/loginForm.html');
}
else {
$rows = $result->num_rows;
$result->data_seek(0);
$p=$result->fetch_assoc()['password'];
if ($p == $password) {
header("Location: http://localhost/FormAuth/afterlogin.php");
}
else {
$result->close();
$conn->close();
$result->close();
$conn->close();
header('Location: http://localhost/loginForm.html');
}
}
$result->close();
$conn->close();
}
else
{
$result->close();
$conn->close();
header('Location: http://localhost/loginForm.html');
}
?>
Now for my third page, I can't retrieve the username session variable.
session_start();
if (!isset($_SESSION['username'])) {
echo "Username is: ".$_user_name['username'] . "<br>";
echo "Test, I made it here!";
}else{
echo "You not logged in.";
}
?>
<html>
<head>
</head>
<body>
</body>
</html>
This results in:
Username is:
Test, I made it here!
You need to set username in session after check username and password in your database.
<?php
session_start();
if (isset($_POST['username']) &&
isset($_POST['password']))
{
$user = $_POST['username'];
$pwd = $_POST['password'];
require_once "login.php";
$conn = new mysqli($hn, $un, $pwd, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "Select Password from Users where Username = '$user'";
$result = $conn->query($query);
if (!$result) {
$result->close();
$conn->close();
header('Location: http://localhost/FormAuth/loginForm.html');
}
else {
$rows = $result->num_rows;
$result->data_seek(0);
$p=$result->fetch_assoc()['password'];
if ($p == $pwd) { // use $pwd instead of $password
$_SESSION['username'] = $user; // set username here
header("Location: http://localhost/FormAuth/afterlogin.php");
}
else {
$result->close();
$conn->close();
$result->close();
$conn->close();
header('Location: http://localhost/loginForm.html');
}
}
$result->close();
$conn->close();
}
else
{
$result->close();
$conn->close();
header('Location: http://localhost/loginForm.html');
}
?>
And In your third part, check if your username is set in session before try to display it:
if (isset($_SESSION['username'])) {
echo "Username is: ".$_SESSION['username'] . "<br>";
}
You need to first check whether the posted values are set or not.
<?php
session_start();
if (isset($_POST['username'], $_POST['password'])){
...
Then, only when the passwords match, set the session variable $_POST['username'] before redirecting.
if ($p == $password) {
$_SESSION['username'] =$user;
header("Location: http://localhost/FormAuth/afterlogin.php");
}
Then you can access your set session variable $_SESSION['username'] on any page provided you use session_start();. Take the third page for instance,
session_start();
if(isset($_POST['username']) && !empty($_POST['username'])){
// proceed to account dashboard / your required page
} else {
// redirect to login page / index
}
Your problem comes from this line :
<?php
session_start();
$_SESSION['username'] = $user_name;
if (isset($_POST['username']) &&
isset($_POST['password']))
{
$user = $_POST['username'];
Do this one instead:
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
$user = $_POST['username'];
$_SESSION['username'] = $user;
EDIT: The third page:
session_start();
if (isset($_SESSION['username'])) {
echo "Username is: ".$_SESSION['username'] . "<br>";
echo "Test, I made it here!";
} else {
echo "You not logged in.";
}
?>
Good luck.
I created a simple login form. When I enter the correct username and password, it is always displaying the access denied message.
verify.php:
<?php
session_start();
$conn = mysqli_connect('localhost','root','') or die(mysqli_error());
mysqli_select_db($conn,'maindata') or die(mysqli_error($conn));
$uname=$_POST['username'];
$pass=$_POST['password'];
$password = md5($pass);
$result = mysqli_query($conn,"select * from users where username='$uname' and password='$password'")
or die("Could not execute the select query.");
$row = mysqli_fetch_assoc($result);
if(is_array($row) && !empty($row))
{
$validuser = $row['username'];
$_SESSION['valid'] = $validuser;
}
else
{
echo "<center></h1>Access Denied</h1></center>"."<br />";
echo "<center></h6>Please wait while you are redirected in 3 seconds</h6></center>"."<br />";
header('Refresh: 3; url=login.html');
}
if(isset($_SESSION['valid']))
{
header("Location:index.html");
}
login.html:
<?php
session_start();
if(isset($_SESSION['valid'])){
header("Location:index.html");
}
else
{
header("location:login.html");
}
?>
<form method="post" action="verify.php" class="login" class="contact_form">
<p>
<label for="login">Email:</label>
<input type="text" name="username" placeholder = "Enter Username Here...">
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" placeholder = "*******">
</p>
<p class="login-submit">
<button type="submit" class="login-button">Login</button>
</p>
<p class="forgot-password">Forgot your password?</p>
</form>
You'r code loops it self, Login.html checks if a user is logged in ( which they arrent because they cant login ) and redirects them from Login.html to Login.html meaning that you never enter your php code. You should not check if the user is already logged in when trying to access the login page.
Also you should consider making a file to check if the user is logged in, it could be something like this:
checkloggedin.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if($_SESSION['loggedin'] == false)
{
die(header("Location: ./index.php"));
}
?>
When you need to check if a user is logged in you can just start your pages off with:
<?php
include"checkloggedin.php"
?>
I've been looking at my code for days, but can't seem to find the problem. I'm new in PHP, so I'm not really familiar with all of it.
Below is my code. No errors. No registered session variable values.
db-config.php
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'mcsh';
$conn = mysqli_connect($host, $user, $pass, $db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
login.php
<form id="user-login" action="index.php" method="POST">
<h1>Administrator Login</h1>
<input type="text" name="username" placeholder="Username" required/>
<input type="password" name="password" placeholder="Password" required/>
<button type="submit">Login</button>
Forgot your password?
</form>
<?php
if (!empty($_POST)) {
if (!empty($_SESSION['username'])) {
header("Location: index.php");
}
$username = $_POST['username'];
$password = $_POST['password'];
include("../config/db-config.php");
$sql = "SELECT `userid`, `password` FROM users WHERE userid = '" . $username . "' AND userlevel = '99'";
$result = mysqli_query($conn, $sql);
if ($row = mysqli_fetch_assoc($result)) {
if (password_verify($password, $row['password'])) {
$_SESSION['username'] = $row['userid'];
header("Location: index.php");
exit;
}
else {
?>
<p class="msg" id="error">Invalid username or password. Please try again.</p>
<?php
}
}
else {
?>
<p class="msg" id="error">Invalid username or password. Please try again.</p>
<?php
}
}
?>
index.php
<?php
session_start();
include("../config/config.php");
if (empty($_SESSION['username'])) {
header("Location: login.php");
}
else {
//the rest of the index page...
?>
Your form in login.php submits to index.php. In index.php, if the username is not yet in the session, you are redirected back to login.php. There you check if (!empty($_POST)) { at the beginning of your PHP code.
$_POST will be empty, because you have redirected to that page, not POSTed to it, so the PHP code will not be executed.
Remove the action="index.php" and that form will submit to itself (login.php). Also, move the HTML form code below the PHP code so that you will not have output before the redirect header if the login is successful.
I have a database table that holds a users username, password and other information as well as whether theyre and administrator or not. Its currently set to Char where A is for admin and U is for normal user.
I have the following code which checks if a user exists:
<?php
session_start(); // Starting Session
include_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$_SESSION['login_user']=$user;
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if(mysqli_num_rows($result) == 1) {
header("Location: home.php");
} else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>
</head>
<body>
<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span>
</div>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form action = "" id = "logregform" method = "POST">
<p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
<input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
<input type="password" placeholder="Password" name = "pass" required/>
<input type="submit" value="Log in" name = "submit" />
<br>
<br>
<p id ="bklg">Dont have an account? Sign up</p>
</form>
</div>
</html>
How would i check if Account_Type is A and if so direct the user to another page instead of the normal home.php page?
EDIT:
It works fine however the admin wont log in.
Ive given it test username of 456 and a password of 456 when i enter them into the two textboxes nothing happens, the screen just refreshes and im back on the login page:
new code below:
<?php
session_start(); // Starting Session
include_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if ($row = mysqli_fetch_array($result)) {
//set the session variables
$_SESSION['Username'] = $row['Username'];
$_SESSION['Account_Type'] = $row['Account_Type'];
if ($row['Account_Type'] === 'A') {
header ("location: adminHome.php");
exit;
} else {
header ("location: home.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>
</head>
<body>
<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span>
</div>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form action = "" id = "logregform" method = "POST">
<p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
<input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
<input type="password" placeholder="Password" name = "pass" required/>
<input type="submit" value="Log in" name = "submit" />
<br>
<br>
<p id ="bklg">Dont have an account? Sign up</p>
</form>
</div>
<script>
$('#toggle-login').click(function(){
$('#login').slideToggle('fast');
});
</script>
</html>
You are going about this the wrong way. Every page that requires the user to be authenticated should check at the very start if the user is authenticated and at what level. The way to do that is to use the session.
Right now you are setting the session variable before you even check whether the user / password combination is correct so you are effectively logging in anybody who enters a username.
You need to store the variables in the session only upon successful login and as mentioned you need to get a row from your result set to get the user information:
// Personally I would use a prepared statement here
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if ($row = mysqli_fetch_array($result)) {
// Now you can set the session variables
$_SESSION['Username'] = $row['Username'];
$_SESSION['Account_Type'] = $row['Account_Type'];
// Add any additional user information to the session that you might need later on
if ($row['Account_Type'] === 'A') {
header ("location: adminHome.php");
exit;
} else {
header ("location: home.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
Now in every page where a user is required you can do:
session_start();
if (isset($_SESSION['Username']))
{
// valid user, additional checks for user type?
}
else
{
// not a valid / logged in user
}
Note:
(unsalted...) md5 is unsafe to use for passwords, see Secure hash and salt for PHP passwords;
$row = mysqli_fetch_array($result);
if ($row['Account_Type'] === 'A') {
} elseif ($row['Account_Type'] === 'U') {
} else {
}