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'];
Related
I'm was doing this tutorialHow to create a login system in PHP
I'm trying to use an IF statement to check if to set the session id. The current allows a user to log in and echos the current session id. When I purposely enter a wrong password, the code should echo a message, but it doesn't do anything. In addition, I am unable to use the logout button to kill the session.
Here is my login page
<?php
session_start();
//include 'dbh.php';
//probably do not need this can write connection in this file too
$conn = new PDO('mysql:host=localhost;dbname=testtable', 'root', '');
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
if(!$conn){
die("Connection is fubar yo!!! ");
}
$uid = $_REQUEST['uid'];
$pwd = $_REQUEST['pwd'];
$sql = "SELECT * from user WHERE uid='$uid' AND pwd='$pwd'";
$result = $conn->prepare($sql);
$result->execute();
if(!$row = $result->fetch(PDO::FETCH_ASSOC)){
echo("Your username or Password is wrong");
} else {
echo("hey man..it works");
$_SESSION['id'] = $row['id'];
}
header("Location: fakelogin.php");
?>
Here is my logout page.
<?php
session_start();
session_destroy();
header("Location: fakelogin.php");
?>
here is the main page that contains login, signup and logout buttons.
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Look ma, no hands!</title>
</head>
<body>
<form action="login.php" method="POST">
<input type="text" name="uid" placeholder="Enter username"><br>
<input type="password" name="pwd" placeholder="Enter password"><br>
<button type="submit" id="login">LOGIN</button>
</form>
<?php
echo("testing");
if(isset($_SESSION['id'])){
echo($_SESSION['id']);
} else {
echo("You are not logged in");
}
?>
<br><br><br>
<form action="signup.php" method="POST">
<input type="text" name="first" placeholder="Enter first name"><br>
<input type="text" name="last" placeholder="Enter last name"><br>
<input type="text" name="uid" placeholder="Enter username"><br>
<input type="password" name="pwd" placeholder="Enter password"><br>
<button type="submit" id="sbt">SIGN UP HERE YO!</button>
</form>
<br><br><br>
<form>
<button action="logout.php">LOG OUT</button>
</form>
</body>
</html>
Based on the code you have provided, you will always return to the login page.
When logged in, the string below login button will say testing followed by your user account id.
Otherwise, it will show testingYou are not logged in.
You cannot add a message on login.php and expect it to appear on fakelogin.php auto-magically.
There are a lot of ways to share information between pages and the session variable is one of it.
By using the method below, you can set the session variable id as "Your username or Password is wrong" and since fakelogin.php will print it out if there's a value, this should show the error message.
login.php
<?php
session_start();
//include 'dbh.php';
//probably do not need this can write connection in this file too
$conn = new PDO('mysql:host=localhost;dbname=testtable', 'root', '');
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
if(!$conn){
die("Connection is fubar yo!!! ");
}
$uid = $_REQUEST['uid'];
$pwd = $_REQUEST['pwd'];
$sql = "SELECT * from user WHERE uid='$uid' AND pwd='$pwd'";
$result = $conn->prepare($sql);
$result->execute();
if(!$row = $result->fetch(PDO::FETCH_ASSOC)){
echo("Your username or Password is wrong");
$_SESSION['id'] = "Your username or Password is wrong";
} else {
echo("hey man..it works");
$_SESSION['id'] = $row['id'];
}
header("Location: fakelogin.php");
?>
So when you attempt to login with wrong details, you will see testingYour username or Password is wrong.
For problem with your logout button, there's a problem with your HTML. action attribute should be in the form tag and not the button tag like so.
<form action="logout.php">
<button>LOG OUT</button>
</form>
After logging in, my code isn't redirecting me to the next page.
<?php
$con = mysqli_connect("localhost","myusername","mypassword","mydatabase");
include ("connection.php");
session_start();
if(isset($_POST['login']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$check = "SELECT * FROM admin WHERE username='$username' and password='$password'";
$queryString = mysqli_query($db, $check) or die('ERROR:' . mysqli_error($db));
if (mysqli_num_rows($queryString) > 0)
{
$admin = mysqli_fetch_assoc($queryString);
$_SESSION['username'] = $admin['username'];
session_write_close();
header("location: http://mywebsite.com/home.php");
die();
}
else
{
echo '<div class="popup-position">
<div id="popup-wrapper">
<h3>Invalid user name or password.</h3><br/>OK
</div>
</div>';
}
}
mysqli_close($con);
This is the authentication of the next page after login:
<?php
session_start();
if (!isset($_SESSION['username']))
{
header("location: login.php");
exit();
}
try this
/send user to index. if he is login/
<?php
require_once("inc/ header.inc.php");
if(isset($_SESSION['id']))
{ header("Location: index.php");
exit(); }
<div class="container">
<div class="form-container">
<p class="heading text-center">Login</p>
<form action=" <?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<div class="form-group">
<input type="text" name="username" placeholder="Enter your Username" class="form-control">
</div>
<div class="form-group">
<input type="password" name="password" placeholder="Enter your Password" class="form-control">
</div>
<input type="submit" value="Login" class="btn btn-primary" name="login">
</form>
<?php
//login script
if(isset($_POST['login'])){
$username = trim( htmlspecialchars ($_POST['username']));
$password = trim( htmlspecialchars ($_POST['password']));
//if username or password is empty
if(empty($username) || empty($password)){
echo "<div class='alert alert-danger'>Fill in all the fields</div>";
exit();
}
//check username and password match the db record
$q = mysqli_query($con,"SELECT id FROM `user` WHERE username='$username' AND password='$password'");
if(mysqli_num_rows($q) != 1){
echo "<div class='alert alert-danger'>Invalid username or password</div>";
exit();
}
//fetch the if of the logged in user start the session
$row = mysqli_fetch_assoc($q);
//set the session with logged in user id
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $username;
header("Location: index.php");
exit();
}
?>
</div>
</div>
Let me help you with logging in.
login.php
<html>
<head>
<title>Hospital Login</title>
<link href="login.css" rel="stylesheet" type="text/css">
</head>
<body>
<form name="form1" method="post" action="process_login.php">
<fieldset class="formDisplay">
<legend><strong>Member Login </strong></legend>
<strong>Username</strong></br></br> <input name="myusername" type="text" id="myusername">
</br></br>
<strong>Password</strong></br></br><input name="mypassword" type="password" id="mypassword">
</br></br>
<input type="submit" name="Submit" value="Login">
</br></br>
<?php
echo $message;
?>
</fieldset>
</form>
</body>
</html>
The code above is literally what should be in your login script, forget about the fieldset thing, I'm just using it for something else :)
Now we want a pure PHP file to handle the input for logging into our system as so.
process_login.php
<?php
include('database_connection.php');
$myusername = mysqli_real_escape_string($DBConn, $_POST['myusername']);
$mypassword = mysqli_real_escape_string($DBConn, $_POST['mypassword']);
$query="SELECT * FROM $doctor_table WHERE username='$myusername' AND passwd='$mypassword'";
$result=mysqli_query($DBConn, $query);
if(!$result){
echo "<p>
There was an error with the query.<br />\n" .
"The error was " .
htmlspecialchars(mysqli_error($DBConn), ENT_QUOTES) .
".<br />\nThe query was '" .
htmlspecialchars($query, ENT_QUOTES ) .
"'</P>\n";
}
else if (!mysqli_num_rows($result)){
$message = "<p>Failed to Log In. Please check your username/password</p>\n";
include 'login.php';
}
else{
$count=mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_start();
$_SESSION['myusername'] = $myusername;
$_SESSION['mypassword'] = $mypassword;
header("Location: login_success.php");
}
}
?>
Now when your authentication has been successful, you should then display your main page.
Note that you must 'clean' every entry by a user in order to avoid SQL injection (helps stop ppl from stealing data from your database)
These full codes work perfectly, I'd encourage you to use the code i've supplied, and feel free to tweak it for your own use :)
This seems like it should be simple, but I've tried it every which way and can't seem to get it to work.
I have this login script which I adapted from an online tutorial. What I'd like to do is have users sign in with a username and password, and if these are correct, have it go after their lab results in another table (same database) and display them. I can get it to sign in, but that's it. Here's the login code:
<?php //Start the Session
session_start();
require('connect.php');
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['username'] = $username;
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo "Invalid Login Credentials.";
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "! ";
echo "This is the results of your inquiry.<br><br>";
/*This is where I'm assuming the new query needs to go.
Query a different table named "data" and pick out information according to
$username which was put in earlier */
echo "<br><a href='logout.php'>Logout</a>";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
<!DOCTYPE html>
<html>
<head>
<title>Lab Sign In Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="" method="post">
<p><label>User Name :</label> <input id="username" type="text" name="username" placeholder=
"username"></p>
<p><label>Password :</label> <input id="password" type="password" name="password"
placeholder="password"></p><a class="btn" href="register.php">Signup</a> <input class=
"btn register" type="submit" name="submit" value="Login">
</form>
</div><?php }
?>
</body>
</html>
A "Join" is what I get when I google it but that doesn't seem right. Could someone help?
You can just use a different query for making it easy:
$sql = mysql_query("SELECT * FROM data WHERE user = '" . mysql_real_escape_string($username) . "'");
Then you can process with this.
Please note that you should not use MySQL driver as it is deprecated, use MySQLi(mproved) instead. And you should escape the POSTed values, this is very important!
Your last else statement is trying to echo the HTML.
You should be using mysqli or PDO since mysql is deprecated.
<?php //Start the Session
session_start();
// require('connect.php');
// Establish connection with database
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM `people` WHERE username='$username' and password='$password'";
$result = mysqli_query($con,$query) or die(mysqli_error());
$count = mysqli_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['username'] = $username;
echo "Valid";
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo "Invalid Login Credentials.";
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "! ";
echo "This is the results of your inquiry.<br><br>";
echo "Username: $username";
echo "Session Username:".$_SESSION['username'];
// This is where I'm assuming the new query needs to go.
// Query a different table named "data" and pick out information according to $username which was put in earlier
echo "
Logout";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Lab Sign In Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="test.php" method="post">
<p><label>User Name :</label> <input id="username" type="text" name="username" placeholder=
"username"></p>
<p><label>Password :</label> <input id="password" type="password" name="password"
placeholder="password"></p><a class="btn" href="register.php">Signup</a> <input class=
"btn register" type="submit" name="submit" value="Login">
</form>
</div>
</body>
</html>
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 {
}
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>