i am developing a log in form with session. When i log in and try to change page in the same domain and get back to login page, i am logged out and credentials needed. Bellow is the code.
mysky.php (login page)
<?php
session_start();
$pageTitle = 'MySky Login';
include 'header.php';
?>
<div id="cloud_box">
<div id="cloud_title">My<span>Sky</span> Login</div>
<form action="myskyweb.php" name="form" method="POST"
onsubmit="return IsEmpty();">
<div id="msg"><?php if(isset($msg)) { echo $msg; }?></div>
<div id="u">
<div id="user1">U</div>
<input type="text" id="user" name="user"/>
<div id="error_u"></div>
</div>
<div id="p">
<div id="pass1">P</div>
<input type="password" id="pass" name="pass"/>
<div id="error_p"></div>
</div>
<button id="btn" type="submit">Login</button>
</form>
</div>
<?php include 'footer.php';?>
myskyweb.php (after successfull login)
<?php
session_start();
if(!isset($_SESSION['id']))
{
header("Location: mysky.php");
}
$pageTitle = sprintf('MySky - %s', $_POST['user']);
include 'header.php';
include 'login.php';
?>
<?php
print_r($_SESSION);
?>
<div id="logout">Logout</div>
<?php include 'footer.php';?>
page1.php (one page of my domain)
<?php
session_start();
$pageTitle = 'page1';
include 'header.php';
?>
<?php
print_r($_SESSION);
?>
<div id="structure">
<?php include 'footer.php';?>
page2.php (another page)
<?php
session_start();
$pageTitle = 'page2';
include 'header.php';
?>
<?php
print_r($_SESSION);
?>
<div class="slides">
<?php include 'footer.php';?>
login.php (checking if credentials are correct & give value to session)
<?php
include 'db_info.php';
$username = $password = $encrypted = $msg = '';
//connect to db
$conn = new mysqli($dbServer, $dbUser, $dbPass, $dbName)
or die($conn);
//get values
$username = $_POST['user'];
$password = $_POST['pass'];
//prevent mysql injection
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);
//encrypt pass
$encrypted = md5($password);
//search
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$encrypted'";
$result = mysqli_query($conn, $sql) or die("Failed to query database ".mysqli_error($conn));
//compare
$row = mysqli_fetch_array($result);
if (($row['username'] == $username) && ($row['password'] == $encrypted)){
$_SESSION['id'] = $row['id'];
$_SESSION['user'] = $row['username'];
$_SESSION['logged_in'] = time();
} else {
$msg = 'Credentials mismatch';
header("Location: /mysky.php");
die();
}
mysqli_close($conn);
?>
I used the function print_r() at all of the pages to understand if the problem is the session. Session is not the problem, because after log in every page shows the sessions var. So session keep the values after changing a page. I cannot undestand why i see login form in login page again rather to see successfull login page.
Any help is appreciated!
You'll need to assign a $_SESSION variable when they are logged in. Take a look at my example below
Login.php
//login code
.....
//
//if successful
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
header( "Location: /protected.php" );
die();
And then at the top of your subsequent pages for example..
home.php
<?php
session_start();
if(isset($_SESSION['user_id']) || isset($_SESSION['logged in'])){
echo 'blah'
?>
if you want to remove the login button or redirect if they try to
access the login page you'd need to do some handling to implement
this.
Change login button -> logout button
<?php if(isset($_SESSION['user_id']) || isset($_SESSION['logged in'])){
?>
<li> <a href="logout.php"> Logout | <?php echo
$_SESSION['user_id'] ?> </a></li>
<?php }else{ ?>
<li> <a href="loginpage.php" >login</a></li>
<?php } ?>
Protected.php
<?php
session_start();
if(!isset($_SESSION['user_id']) || !isset($_SESSION['logged_in'])){
echo "Oops, you're not supposed to be here\n";
echo 'You\'ll be redirected in 5 seconds. If not, click here.';
header( "refresh:5;url=index.php" );
exit;
}
echo 'Congratulations! You are logged in!';
echo 'You\'ll be redirected in 5 seconds. If not, click here.';
header( "refresh:5;url=index.php" );
die();
?>
I believe this is everything you want to achieve, just change variables as required
EDIT 1
I can successful login but if then click to menu page1.php and then
click to mysky.php, i see the login form again and not the
myskyweb.php (authorized page)
OK - this is important. So your issue is not logging in, right? But, after authenticating, if you go back to log in page, you see the login form and you are not redirected. You want to automatically be redirected to the landing page if you are already authenticated. Is that right?
If so, then my question is, where in mysky.php (login page) are you checking if the user is logged in? I don't see that check anywhere.
You need to:
<?php
session_start();
// If the user is already logged in, redirect them to the landing page.
if (isset($_SESSION['id'])) {
header("Location: myskyweb.php");
}
You are only calling login.php after checking if the session variable id is set. That is why it is redirecting you back to the login page. Move that include up, directly under session_start(). The only reason that it sometimes works is that there is an existing session - see my next point.
myskyweb.php (after successfull login)
<?php
session_start();
// Move this include up here before the check.
include 'login.php';
if(!isset($_SESSION['id']))
{
header("Location: mysky.php");
}
$pageTitle = sprintf('MySky - %s', $_POST['user']);
include 'header.php';
...
?>
Also, for debugging purposes, clear the session each time you hit the log in screen. That way you'll not be confused about stale session data keeping you logged in
mysky.php (login page)
<?php
// Always clear the session when hitting the log in page.
session_destroy();
$_SESSION = [];
...
You're wide open to SQL Injection attacks - look up parameterized queries.
You need to call die; after issuing a header call - https://stackoverflow.com/a/768472/296555
#waterloomatt & #Isaac thanks for your time and responses! After so many hours, finally i found the code that works. If you see anything wrong, i would be happy to know!
Will i have problems with SQL Injection attacks?
login.php
<?php
session_start();
include 'db_info.php';
//connect to db
$conn = new mysqli($dbServer, $dbUser, $dbPass, $dbName)
or die($conn);
//get values
if ((isset($_POST['user'])) && (isset($_POST['user']))){
$username = $_POST['user'];
$password = $_POST['pass'];
} else {
$username = null;
$password = null;
}
//prevent mysql injection
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);
//encrypt pass
$encrypted = hash('sha256', $password);
//search
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$encrypted'";
$result = mysqli_query($conn, $sql) or die("Failed to query database ".mysqli_error($conn));
//compare
$row = mysqli_fetch_array($result);
if (($row['username'] != $username) || ($row['password'] != $encrypted)){
if ((isset($_POST['user'])) && (isset($_POST['pass']))){
$_SESSION['msg'] = 'Credentials mismatch';}
} else {
$_SESSION['id'] = $row['id'];
$_SESSION['user'] = $row['username'];
}
mysqli_close($conn);
?>
mysky.php
<?php
include 'login.php';
if ((isset($_SESSION['id'])) && (isset($_SESSION['user'])))
{
include 'sky_auth.php';
}
else
{
include 'sky_login.php';
}
include 'footer.php';
?>
sky_login.php
<?php
$pageTitle = 'MySky Login';
include 'header.php';
?>
<div id="cloud_box">
<div id="cloud_title">My<span>Sky</span> Login</div>
<form action="" name="form" method="POST" onsubmit="return IsEmpty();">
<div id="msg"><?php if (isset($_SESSION['msg'])){
echo $_SESSION['msg'];
unset($_SESSION);
session_destroy();} ?>
</div>
<div id="u">
<div id="user1">U</div>
<input type="text" id="user" name="user"/>
<div id="error_u"></div>
</div>
<div id="p">
<div id="pass1">P</div>
<input type="password" id="pass" name="pass"/>
<div id="error_p"></div>
</div>
<button id="btn" type="submit">Login</button>
</form>
</div>
sky_auth.php
<?php
if(!isset($_SESSION['id']))
{
header("Location: mysky.php");
die();
}
$pageTitle = sprintf('MySky - %s', $_SESSION['user']);
include 'header.php';
?>
<div id="sky_contain">
<div id="logout">Logout</div>
</div>
</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'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.
So this is the code for page index.php: the $_SESSION["username"] variable seems to be not setted and I dunno why becuase in the login page I am using the isset control and the login is successful if I'm entering the right values;it is not if I am entering wrong username and password. I know I should "code" the password with md5 but right now that is not my problem :(
As you can see I'm redirecting to the index page after the login. From the index page I'm redirecting to the "home.php" page if the user already logged in. The problem is that after been doing the login,it keeps showing the login form and it is not redirecting me to home.php..
<?php session_start();
require_once "dbConn.php"; dbconnect();
if(isset($_SESSION["username"])){
echo $_SESSION["username"]; // TEST it never enters THERE!!!
echo'<p>Trasferimento alla home page</p>';
header("Refresh: 2; URL = home.php");
}
else{
echo'<div id=\"container\">';
echo'
<div id=\"content\">
<h2> You need to login :</h2>
<br/>
<form id="form1" name="form1" method="post" action="login.php">
<input type="text" name="username" id="username" />
<input type="password" name="password" id="password" />
<input type="submit" name="accedi" id="accedi" value="Accedi" />
</form>
<br/>
</div>';
include 'Footer.php';
echo'</div>';
}?>
And this is the login.php page:
<?php
require_once "dbConn.php"; dbconnect();
if(isset($_POST['username']) && isset($_POST['password'])) {
$username=mysql_real_escape_string($_POST['username']);
$pwd = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT * FROM user WHERE username='$username' AND password ='$pwd';");
if(mysql_num_rows($query) == 1){
$sessione =mysql_fetch_array($query);
$_SESSION["username"] = $sessione["username"];
echo $_SESSION["username"]; //TEST - it prints what I want: my username
$_SESSION["logged"] = true;
echo'Login effettuato con successo!';
header("Refresh: 2; URL = index.php");
}
else if((mysql_num_rows($query) == 0)){
echo'Utente non registrato o password errata';
header("Refresh: 2; URL = index.php");
}
}
?>
Thx all ;)
You forgot to call session_start() on your login page
<?php
require_once "dbConn.php"; dbconnect();
should be
<?php
session_start()
require_once "dbConn.php"; dbconnect();
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>