I already set a password for the user to log in, in phpMyAdmin. But I want to make sure that the password is deleted once the user uses it. Therefore, the user cannot login to the system twice. But I don't know how to make an SQL statement for that. I just want to delete the password without deleting the username. Can I combine the delete code with submit button?
<?php
if(isset($_POST['submit']))
{
include("config.php");
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['login_user'] = $username;
$query = mysqli_query($mysqli,"SELECT username from logins WHERE username='$username' and password='$password'");
if(mysqli_num_rows($query) !=0)
{
echo "<script language='javascript' type='text/javascript'>location.href='home.php'</script>";
}
else
{
echo "<script language='javascript' type='text/javascript'>alert('Username or Password invalid!')</script>";
}
}
?>
Thank you.
Add an SQL UPDATE statement before your redirect your user.
And do not save the password as plain text in your DB:
Best way to store passwords in MYSQL database
But an better idea is, that you will add an timestamp to your database with the last login. If the timestamp is NULL, than the user can login. If it is not empty the user can not login.
But here the example for the given code:
(Security manuel: https://www.php.net/manual/en/mysqli.real-escape-string.php)
if(isset($_POST['submit']))
{
include("config.php");
session_start();
$username = mysqli_real_escape_string($mysqli, $_POST['username']);// add a little bit security at this point
$password = mysqli_real_escape_string($mysqli, $_POST['password']); // add a little bit security at this point
$_SESSION['login_user'] = $username;
$query = mysqli_query($mysqli,"SELECT username from logins WHERE username='$username' and password='$password' and password IS NOT NULL"); // check that the password is not empty
if(mysqli_num_rows($query) !=0)
{
// update your DB row
// if you got an ID, than do it with the ID and not with the $username and $password
mysqli_query($mysqli,"UPDATE logins SET password = NULL WHERE username='$username' and password='$password'");
// to do it better use instead of JavaScript PHP for the redirect. In this case it is important, that nothing is printed out bevore the `header()`:
header("Location: home.php");
exit;
// try to not mix it up if you are on an pure PHP page
// echo "<script language='javascript' type='text/javascript'>location.href='home.php'</script>";
}
else
{
// same as above
header("Location: login.php?tag=login-invalid");
exit;
// echo "<script language='javascript' type='text/javascript'>alert('Username or Password invalid!')</script>";
}
}
If the "password" is not NULL able, than replace the NULL through = ""
Related
I'm trying to create a password protected area of a website.
I'd like to allow access by checking username and password from a MySql table, then start a session and allow access to a number of pages while the session is active. If someone tries to directly access one of these pages directly, I'd like to redirect them to login page.
My code for the login page is:
if (isset($_POST['submit']))
{
include("config.php");
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
$_SESSION["username"] = $user;
echo "<script language='javascript' type='text/javascript'> location.href='admin_view.php' </script>";
}else{
echo "<script type='text/javascript'>alert('User Name Or Password Invalid!')</script>";
}
}
It seems to work (correctly redirects if username and password matches, shows alert if not).
What I fail to do, is actually protect my pages from display if session is not active.
session_start();
if (!$_SESSION["username"]) {
header("Location: login.php");
}
I'm not a programmer or fully-educated web developer. I know HTML and CSS, and I'm barely able to use ready-to-use php and js scripts following readme files.
Any help would be greatly appreciated.
modify your login code as
if (isset($_POST['submit']))
{
include("config.php");
$username= $crud->escape_string($_POST['username']);
$password= $crud->escape_string($_POST['password']);
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND
password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
session_start();
$_SESSION["username"] = $user;
header("Location:admin_view.php");
}else{
$Message = urlencode("user name password invalid!");
header("Location:login.php?Message=".$Message);
}
}
if your values successfully stored in session then you can use like
session_start();
if(!isset($_SESSION['username']))
{
header("Location: login.php");
}
on everypage top
you must store name from query into session
I was working on a register/log in page with a database (first time)
Whenever I register my user, I get the following information in the database:
It is giving me something like a password, but it won't give me my username and email (and i guess password aswell)
Can anyone help me with this?
My php code looks like this:
<?php
session_start();
// connect to database
$db = mysqli_connect('localhost', 'root', '', 'toolsforever');
if (isset($_POST['login_btn'])) {
$username = $db->real_escape_string($username);
$password = $db->real_escape_string($password);
$password = md5($password); // hashed
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) == 1) {
$_SESSION['message'] = "You are now logged in";
$_SESSION['username'] = $username;
header("location: home.php"); //redirect to home page
}else{
$_SESSION['message'] = "Username/password combination incorrect";
}
}
?>
Thanks in advance
PS: Password2 = confirm password for registration password==password2 before they can register.
You are not getting the values from post array so do it like this:
$username = $db->real_escape_string($_POST['username']);
$password = $db->real_escape_string($_POST['password']);
I assume the form fields are names as username and password
It's not just related to retrieval, seems like you need to check the save operation as well. You are storing empty values during registration.
That one worked #danyal Sandeelo. I feel incredible stupid because i've tried an $_POST but i did it like: $username = $_POST['username']; $username = $db->real_escape_string;
When I coded my php login system (In MySQLi), I get an error that do not actually checks if username or password is wrong, idk what to do abot this. Please help me out here.
<?php
// If logged in
if(isset($_SESSION['user_id'])) {
header('Location: index.php');
}else {}
//error_reporting(0);
//MySQLi Login form
//Database connection
$con = mysqli_connect('localhost', 'root', '', 'console');
//Actual Login form
if(isset($_POST['login'])) {
session_start();
//Explainging details
$username = $_POST['username'];
$password = $_POST['password'];
//Fetching data
$result = $con->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$row = $result->fetch_array(MYSQLI_BOTH);
//Logging in
$_SESSION['user_id'] = $row['user_id'];
header('Location: index.php');
}else{
$wrong = 'Username or password is wrong';
}
?>
Also i got a check.php that redirects you to /notloggedin.php if not logged in, but IF the user is logged in it will display their User_ID, but when user logsIn with wrong details then go to check.php it does not show anything and it does not redirect the users to /notloggedin.php.
So what do I do with that? Is there something I forgot to add, or something i did wrong???Can you write a example if you have any ideas?? Thanks.
EDIT:
Now instead of using MySQLi I got an idea from #christoandrew, so i made everything into functions. What the functions tells the system to do is its gonna check for the username first, if the username exists its gonna make a $_SESSION()for the username. Then again using the $_SESSION() to find the User_ID to the username then its gonna look for the password for the same User_ID. Then when its checked everything it will destroy all 'Sessions' it made and create a $_SESSION() for all information like User_ID, Email, Username, Password, Etc... Thanks for all the help i got in my way!
if(isset($_POST['login'])) {
session_start();
//Explainging details
$username = $_POST['username'];
$password = $_POST['password'];
//Fetching data
$result = $con->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$row = $result->fetch_array(MYSQLI_BOTH);
// Try checking if there are actually rows that are returned
// If the rows are greater than zero then the user exists else the
// user supplied wrong credentials
if(mysqli_num_rows($row) > 0){
//Logging in
$_SESSION['user_id'] = $row['user_id'];
header('Location: index.php');
}else{
$wrong = 'Username or password is wrong';
}
// The else block below is not necessary and the validation is misplaced
}
you need start the session:
session_start();
I am quite new in php language..currently i am working on a login and registration system.but i dont know why the users still can login to the although the email and password insert is wrong,since i already make all the validation.So,guys,pls help me to see my code,see whether where the problem is.
here is my code
<?php
include('config.php');
session_start();
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$email = $_POST['email'];
$password = $_POST['password'];
if($email&&$password){
//declare variable
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='$email' Password=''$password");
$numrows = mysqli_num_rows($query);
//when user correct input,check the data
if($numrows !== 0) {
while($row=mysqli_fetch_assoc($query)){
$dbemail=$row['Email'];
$dbpassword=$row['Password'];
}
//if username and password match
if($dbemail=$email&&$dbpassword=$password)
{
$SESSION['$email']="$email";
header('Location:user.html');
}
else
{
$errors['notcorrect'] = "Email or password not correct";
}
}
//when insert wrong data
else{
$errors['notexists'] = "This email doesn't exists";
}
}
//when user didnt enter anything
else{
$errors['nothing'] = "Please enter your email and password";
}
}
?>
any idea?
Let's examine these in detail:
Password=''$password"
$SESSION
if($dbemail=$email&&$dbpassword=$password)
WHERE Email='$email' Password=''$password")
$_SESSION['$email']="$email";
$password is outside your quotes.
Then $SESSION is missing an underscore between the $ and SESSION.
This is also a superglobal.
Then you're "assigning" using 1x = sign instead of "comparing" with if($dbemail=$email&&$dbpassword=$password)
Use 2x == signs.
You're missing an AND for WHERE Email='$email' Password=''$password")
WHERE Email='$email' AND Password='$password'");
You should also, and is recommended to add exit; after header.
header('Location:user.html');
exit;
Otherwise, your code risks in continuing to execute.
$_SESSION['$email']="$email"; there is a dollar sign in ['$email']
It needs to read as ['email'].
Sidenote:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Footnote(s):
In regards to Location:user.html are you sure you want to use an .html file? If you're not instructing Apache to treat .html files as PHP and with no conditional statement to check if the session is set and equal to what you've assigned to it, then anyone can access that file.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
It is recommended to use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
As the chinese proverb goes: "Show a man how to fish, feed him for life."
Update this
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='$email' AND Password='$password' ");
And also correct the session super global from $SESSION to $_SESSION
You are doing an assignment here where you should be doing a comparison:
if($dbemail=$email&&$dbpassword=$password)
Should be
if($dbemail == $email && $dbpassword == $password)
Whitespace makes things more readable.
the error in select query you forgot and operator
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='{$email}' AND Password='{$password}' ");
And change the equle operator in if statment with === like this
if($dbemail===$email&&$dbpassword===$password)
I hope that works successfully
Update your code
<?php
include('config.php');
session_start();
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$email = $_POST['email'];
$password = $_POST['password'];
if($email&&$password){
//declare variable
$query = mysqli_query($con,"SELECT * FROM user WHERE Email='$email' AND Password='$password'");
$numrows = mysqli_num_rows($query);
//when user correct input,check the data
if($numrows !== 0) {
while($row=mysqli_fetch_assoc($query)){
$dbemail=$row['Email'];
$dbpassword=$row['Password'];
}
//if username and password match
if($dbemail==$email && $dbpassword==$password)
{
$_SESSION['$email']="$email";
header('Location:user.html');
die();
}
else
{
$errors['notcorrect'] = "Email or password not correct";
}
}
//when insert wrong data
else{
$errors['notexists'] = "This email doesn't exists";
}
}
//when user didnt enter anything
else{
$errors['nothing'] = "Please enter your email and password";
}
}
?>
So i'm writing a simple login script and I ran into some problems. I was able to create the login.php file that works with this dashboard.php file below. Let me describe the scenario: User come into the main page, which is the login page. Enters username and password. If entered correctly user will see the output "dashboard succesfull". If entered wrongly it will redirect them to loginfailed.php. Problem is that the browser does not remember that the user has already been logged in. If I re-enter this page, it will directly goes to loginfailed.php. So my obivous n00b question here is......is there a way to make the browser remember that the user has already been logged in?
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$dblink = mysql_connect("localhost", "root", "");
mysql_select_db("user",$dblink);
$sql = "select * from members where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
$count = 0;
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
echo "<a href='dashboard.php'>dashboard succesfull</a>";
} else {
$_SESSION['loggedIn'] = "false";
header("Location: loginfailed.php");
}
?>
Sure. You just need to put, at the top of the page but below session_start(), something like:
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == 'true') {
# do something. maybe redirect and then exit?
}
Also, I'd suggest using a session name and escaping the username and password before putting them in your SQL.