This problem is really giving me a hard time. I have 4 files, one for DB config, the other for login page, 3rd for login-processing and lsat one for the redirect after successful login)
This is my db-connect.php:
<?php
$servername = "localhost";
$username = "dbroot";
$password = "dbpassword";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
the form in my user-login.php:
<form action="includes/login-process.php" id="login" class="formoid-metro-black" style="background-color:transparent;font-size:14px;font-family:'Open Sans','Helvetica Neue','Helvetica',Arial,Verdana,sans-serif;color:#FFFFFF;max-width:400px;min-width:150px; float:right;" method="post" enctype="multipart/form-data"><div class="title"><h2>Log In</h2></div>
<div class="element-input"><label class="title">Username<span class="required">*</span></label><input class="large" type="text" name="username" required="required"/></div>
<div class="element-password"><label class="title">Password<span class="required">*</span></label><input class="large" type="password" name="password" value="" required="required"/></div>
<div class="submit"><input type="submit" name="submit" value="Log In"/></div></form><script type="text/javascript" src="forms/sign-up-form_files/formoid1/formoid-metro-black.js"></script>
The login-process.php:
<?php include ("db-connect.php");
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$encrypt = md5($password);
$userquery = "SELECT * FROM user WHERE `user-username`='$username' AND `user-password`='$password'";
$run = mysqli_query($conn,$userquery);
if(mysqli_num_rows($run)>0){
$_SESSION['username']=$username;
?>
<script>alert('Login successful.')</script>
<script>window.open('../user-profile.php','_self')</script>
<?php
}
else {
?>
<script>alert('Username or Password Incorrect.','_self')</script>
<script>window.open('../user-login.php','_self')</script>
<?php
}
}
?>
And in my login page, after i successfully log in, proven by the script alert being successful, however, as the user-profile.php opens (where I put a session_start() on top), it directly runs the condition inside the if statement, ignoring the fact that i already successfully logged in.
This is my user-profile.php:
<!DOCTYPE html>
<?php
session_start();
if(!isset($_SESSION['username'])){
?>
<script> alert('Please Log-in first.','_self')</script>
<?php include_once('user-login.php');
}
else {
$first_name= $_SESSION['fname'];
$first_name= ucfirst($first_name);
?>
//rest of my code
The code above should run what's inside the else statement, but instead i keep getting the alert to login first. (Just ignore the $firstname codes, I want to get it for output below). Does any of you have any idea about this? If so, pleeeease help me. Thank you!
In your login-process.php, you must session_start() first before setting values to session variables.
you are accessing session directly without declaring the session. User session_start() before accessing session variables and you may use session_close() once you are done accessing them.
Related
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>
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'];
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'm trying to confirm if a user submitted valid credentials.
HTML
<form action="assets/php/account/login_user.php" method="post" id="login" class="center">
<div id="register_errorloc"></div>
<div class="form-group">
<input type="text" name="login_username" id="login_username" class="form-control" placeholder="Username" />
</div>
<div class="form-group">
<input type="password" name="login_password" id="login_password" class="form-control" placeholder="Password" />
</div>
<div class="form-group">
<input type="submit" value="login" id="submit_login" class="btn btn-success form-control"/>
</div>
</form>
PHP
$username = trim($_POST['login_username']);
$password = hash('sha512',trim($_POST['login_password']));
//to check if values are correct by myself
echo '<br>' . $username . '<br>' . $password . '<br>';
include_once '../../../assets/php/DB/DBConnect.php';
//check if valid credentials are entered
$stmt = $conn->prepare("SELECT * FROM tbl_users WHERE username = ?");
echo $stmt->bind_param('s', $username);
echo $stmt->execute();
echo $stmt->store_result();
if($stmt->num_rows == 1){
echo 'Good Creds';
}else{
echo 'Bad Creds';
}
When I'm doing this it always shows 0 results. When I change the querystring to
$stmt = $conn->prepare('SELECT * FROM tbl_users WHERE username = "abc"');
I get the result I'm looking for. I'm confused because I'm using the same approach on a different page and it's working like a charm.
Screenshots
Login form
Submitted form
Row I'm looking for
Edit: Added all code.
Edit2: Added screenshots
Edit3: Added Form HTML
Edit4:
Nothing is wrong with the form submit. When I'm hardcoding the variable like this:
$username ='abc';
It still doesn't work
I'm sorry but you posted screenshots that don't help us.
In order to avoid further commenting, am submitting the following.
Your form and its related elements may be failing and require a POST method and that name attributes exist for each of them.
I.e.:
<form method="post" action="???">
<input type="text" name="login_username">
...
Edit:
Try the following, comments are getting too extensive:
$check = $conn->prepare("SELECT * FROM tbl_users WHERE username=?");
$check->bind_param("s", $username);
$check->execute();
$check->store_result();
$row_chqry = $check->num_rows;
if($row_chqry > 0 ) {
echo "Exists";
$check->close();
$conn->close();
}
Edit #2:
OP posted an answer stating that they were using the same variable for their db connection.
Something I would have spotted right away and causing a conflict, had full code been posted. I've seen that happen quite a few times before, and remember posting answers for them too. As to where they are exactly, it would take some time for me to find them; but I do remember posting answers for related questions.
Oh well, problem solved.
Solutions:
Use a different variable for your username(s).
Use unique variables.
I finally found the error:
When connecting to my DB I use:
$servername = "";
$username = "";
$password = "";
$db = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
In my submission script I also use $username. Including the DBconnection file caused my local variable ($username that I get from the form) to be overwritten with the username found in the DBconnect.
i have problem with login validation. The problem is when i try to login using admin, the page stop on checklogin.php and won't tell if it is succeed or not. Here is my code.
Index.html
<body>
<section class="container">
<div class="login">
<h1>Aplikasi Pengelola Data Pelatihan dan Seminar</h1>
<form method="post" action="checklogin.php">
<p><input type="text" name="username" value="" placeholder="Username or Email"></p>
<p><input type="password" name="password" value="" placeholder="Password"></p>
<p class="remember_me">
<label>
<input type="checkbox" name="remember_me" id="remember_me">
Remember me on this computer
</label>
</p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
</div>
<div class="login-help">
<p>Forgot your password? Click here to reset it.</p>
</div>
</section>
</body>
checklogin.php
<?php
if (isset($_POST['login']))
{
if(isset($_POST['username']))
{
$username=$_POST['username'];
}
if(isset($_POST['password']))
{
$password=$_POST['password'];
}
// Connect to database.
$host="localhost"; // Host name.
$db_user="root"; // MySQL username.
$db_password=""; // MySQL password.
$db="seminardanpelatihan"; // Database.
$con = mysqli_connect($host,$db_user,$db_password,$db);
if(mysqli_connect_errno())
{
echo "Failed to connect : " . mysqli_connect_error();
}
else
{
mysqli_select_db($con, $db);
$result = mysqli_query($con, "SELECT * FROM login WHERE username='$username' and password='$password'");
$count=mysqli_num_rows($result);
if($count==1)
{
$_SESSION['username']= "username";
$_SESSION['password']= "password";
header("login_success.php"); // Re-direct to login_success.php
}
else
{
echo "Something wrong";
}
mysqli_close($con);
}
}
?>
Thank you for your help.
change
if (isset($_POST['login']))
to
if (isset($_POST['commit']))
I tested.
Edit
Also Change (Dont skip previous changes)
$_SESSION['username']= "username";
$_SESSION['password']= "password";
header("login_success.php");
To
$_SESSION['username']= $username;
$_SESSION['password']= $password;
header("Location: login_success.php"); //Proper Redirect Method
1)You need Location: prefix for redirect
2)You used "username" instead of $username
First of all change the first line of your code:
<?php
if (isset($_POST['login']))
to
<?php
if (isset($_POST['username']))
this will give you the option to execute all the code of the page if the user will post at least the username. I'd prefer to go for something even more strict:
<?php
if (isset($_POST['username'])&&isset($_POST['password'])
so you won't run the code if the user doesn't submit both the values. (only username or only password will anyway fail the validation!)
Then: your issue is that you don't retrieve the values from the query.
mysqli_select_db($con, $db);
$result = mysqli_query($con, "SELECT * FROM login WHERE username='$username' and password='$password'");
$count=mysqli_num_rows($result);
if($count==1)
{
is ok to check if you have one and only one result but then you have to add after those lines:
$row=mysqli_fetch_array($result);
$username = $row['username'];
$password = $row['password'];
session_start();
and then edit the following two this way:
$_SESSION['username']= $username;
$_SESSION['password']= $password;
Also note that I wouldn't store the password in $_SESSION array or in any other value in my code and that I'd suggest you to use some encryption method on the password.