I successfully made the code for logging in...when user logs in, the time of logging in is written in database.
session_start();
$query = mysql_query("SELECT * FROM users");
$result = mysql_fetch_array($query);
if(!empty($_POST['username']) && !empty($_POST['password'])){
$username = ($_POST['username']);
$password = ($_POST['password']);
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$result = mysql_query("SELECT * FROM users WHERE username = '$username' AND status = '1'");
if(mysql_num_rows($result) == 1) {
mysql_query("INSERT INTO entry(id, username_id, entry_time) VALUES ('', 'bkrpan', NOW()) ");
header("Location: admin.php");
exit; }
$result = mysql_query("SELECT username FROM users WHERE username = '$username' AND password = '$password'");
if(mysql_num_rows($result) == 1) {
mysql_query("INSERT INTO entry(id, username_id, entry_time) VALUES ('', '$username', NOW()) ");
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header("Location: users.php");
exit; }
echo "Login failed! You will be redirected.";
echo "<meta http-equiv=\"refresh\" content=\"2;URL=index.php\">";
}
else {
echo "Login failed! You will be redirected.";
echo "<meta http-equiv=\"refresh\" content=\"2;URL=index.php\">";
}
session_destroy();
but...now I don't know how to make the code for logout.
This is something that I made, but it's not working.
<?php
mysql_connect("localhost", "root", "") or die("cannot connect");
mysql_select_db("zavrsni_rad") or die("cannot select DB");
session_start();
$username = $_SESSION['username'];
$sql = "SELECT * FROM users WHERE username = ".$username." AND password = ".$password;
$result = mysql_query($sql);
if(mysql_num_rows($result) == 1) {
$sql_2 = "INSERT INTO entry(username_id, entry_time) VALUES (".$username.", NOW() )";
mysql_query($sql_2);
}
session_destroy();
header("location: index.php");
?>
You forgot the single quotes in your queries and you're not getting the value of $password
$sql = "SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."'";
$sql_2 = "INSERT INTO entry(username_id, entry_time) VALUES ('".$username."', NOW())";
updated for clarity
<?php
session_start();
// check that the session exists first
if(isset($_SESSION['username'])) {
// you should put your db connection in a config.php file and use mysqli or PDO - what you're using is depreciated
mysql_connect("localhost", "root", "") or die("cannot connect");
mysql_select_db("zavrsni_rad") or die("cannot select DB");
// don't think I'd store password in a session...
// also, is username UNIQUE in your database?
// also, also, ALWAYS escape (sanitize) your database input to prevent agains SQL injection
$sql = "SELECT username, password
FROM
users
WHERE
username = '".mysql_real_escape_string($_SESSION['username'])."'
AND
password = '".mysql_real_escape_string($_SESSION['password'])."'";
$result = mysql_query($sql) or die('sql: '.mysql_error());
if(mysql_num_rows($result) > 0) {
$sql_2 = "INSERT INTO entry(username_id, entry_time) VALUES ('".mysql_real_escape_string($_SESSION['username'])."', NOW())";
mysql_query($sql_2) or die('sql2: '.mysql_error());
session_destroy();
header("location: index.php");
} else {
echo 'There was an error. You have not been logged out.';
}
}
Related
I'm quite new to PHP password_hash & password_verify.
My password_hash works like a charm. I store the hash in the database 'password'-Field, after successful registration.
But the main-problem seems to be the password_verify.
My Register.php:
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_REQUEST['username'])){
$username = stripslashes($_REQUEST['username']); // removes backslashes
$username = mysqli_real_escape_string($con,$username); //escapes special characters in a string
$email = stripslashes($_REQUEST['email']);
$email = mysqli_real_escape_string($con,$email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$hashedpw = password_hash($password, PASSWORD_BCRYPT, ['cost' => 11]);
$ipaddress = $_SERVER['REMOTE_ADDR'];
$reg_date = date("Y-m-d H:i:s");
$query = "INSERT into `user` (username, password, email, reg_date, ip) VALUES ('$username', '$hashedpw', '$email', '$reg_date', '$ipaddress')";
$result = mysqli_query($con,$query);
if($result){
header("Location: regsuccess.php");
}
}else{
?>
My Login.php:
<?php
require('db.php');
function redirect($DoDie = true) {
header('Location: success.php');
if ($DoDie)
die();
}
session_start();
if(isset($_SESSION['username'])) {
redirect();
}
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
$username = stripslashes($_REQUEST['username']); // removes backslashes
$username = mysqli_real_escape_string($con,$username); //escapes special characters in a string
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$hash_query = "SELECT password FROM `user` WHERE username='$username'";
$hash_result = mysqli_query($con,$hash_query) or die(mysql_error());
$ipaddress = $_SERVER['REMOTE_ADDR'];
//Checking is user existing in the database or not
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
if (password_verify($password, $hash_result)) {
$_SESSION['username'] = $username;
$trn_date = date("Y-m-d H:i:s");
$query = "UPDATE `user` SET `ip` = '$ipaddress', `last_login` = '$trn_date' WHERE `username` = '$username'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
header("Location: success.php"); // Redirect user to index.php
}
else {
header("Location: error.php");
}
}
else {
header("Location: error.php");
}
}
else {
?>
So, the problem is that the password_verify doesn't really work here. I enter my password, and it redirects me to the error.php where it says that my username or password is incorrect.
What am I doing wrong? :/ Thanks in advice!
This is my login.php code. User is logged in even "status" is set to "yes". How can I verify if the user is banned and can I add more statuses like "suspend", "deactivated"?
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'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("DBname", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from users where password='$password' AND username='$username' AND", $connection);
$rows = mysql_num_rows($query);
if($row[‘status’]==’yes’){
header("banned.php");
} else if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
$sql = mysql_query("INSERT INTO logs (`uniqueId`, `fileAccessed`, `action`, `userIp`, `userPort`, `serverIp`, `fullPath`, `protocol`, `serverVersion`, `timestamp`) VALUES ('$username', '$filename', 'Logged In', '$usrip', '$usrport', '$servip', '$scriptpath', '$servprotocol', '$servver', '$timestamp')", $connection);
header("location: ../pages/profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
Firstly don't use mySQL anymore, it is deprecated and insecure. You should look into using mySQLi or PDO instead.
The problem you are having is because $row has no value.
You are missing:
$row = mysql_fetch_assoc($result)
So it would read like this:
$query = mysql_query("select * from users where password='$password' AND username='$username' AND", $connection);
$rows = mysql_num_rows($query);
$row = mysql_fetch_assoc($result);
if($row[‘status’]==’yes’){
header("banned.php");
}
Here it is rewritten as mySQLi, use this version instead and research the difference:
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'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "root", "");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
// Selecting Database
$db = mysqli_select_db($connection, "DBname");
// SQL query to fetch information of registerd users and finds user match.
$query = "select * from users where password='$password' AND username='$username'";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$rows = mysql_num_rows($query);
if($row[‘status’]==’yes’){
header("banned.php");
} else if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
$query = "INSERT INTO logs (`uniqueId`, `fileAccessed`, `action`, `userIp`, `userPort`, `serverIp`, `fullPath`, `protocol`, `serverVersion`, `timestamp`) VALUES ('$username', '$filename', 'Logged In', '$usrip', '$usrport', '$servip', '$scriptpath', '$servprotocol', '$servver', '$timestamp')";
$result = mysqli_query($connection, $query);
header("location: ../pages/profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
}
}
i tried to put username & password dynamically but
It doesnt work with stored username & password in DB and stays on same page....
really depressed.
<?php include "../db/db_connection.php";
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
if($_REQUEST['txt_username'] == $username && $_REQUEST['txt_pwd'] == $pwd){
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
header("Location:dashboard.php");
}
else{
header("Location:index.php");
}
?>`
Those lines doesn't nothing..
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
maybe:
$_SESSION['txt_username'] = $user;
$_SESSION['txt_pwd'] = ...;
?
You can try this, I am not sure if this is exactly what you are looking for...
<?php session_start();
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
header("Location:index.php"); // if it stays on the same page remove this line
?>
I restructured your code to look more clean.
Also I suggest you to avoid using mysql and start using mysqli (or PDO) to avoid SQL injection attacks.
<?php session_start();
if(isset($_SESSION['txt_username']) && !empty($_SESSION['txt_username'])) {
//If we enter here the user has already logged in
header("Location:dashboard.php");
exit;
}
if(!isset($_POST['txt_username'])) {
header("location:index.php?err_msg=1");
exit;
}
else if(!isset($_POST["txt_pwd"])) {
header("location:index.php?err_msg=2");
exit;
}
$username = $_POST['txt_username'];
$pwd = $_POST["txt_pwd"];
//We use MYSQL with prepared statements BECAUSE MYSQL IS DEPRECATED
$mysqli = new mysqli('localhost', 'my_bd_user', 'mi_bd_password', 'my_bd');
$sql = "SELECT 1 FROM users WHERE username= ? and password = ?";
$stmt = $mysql->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
if(!empty($result)) {
//IF we enter here user exists with that username and password
$_SESSION['txt_username'] = $username;
header("location:dashboard.php");
exit;
}
else{
header("location:index.php?err_msg=3");
}
Try it.
I checked your code and found everything is correct .I wold like you to add connection file on this.
Like
$username = "root";
$password = "password";//your db password
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("db name",$dbhandle)
or die("Could not select Database");
Thanks
Try below code :
i have reviewed and changed your code :
<?php session_start();
mysqli_connect("locahost","username","password");
mysqli_select_db("database_name");
$username = trim($_POST['txt_username']);
$pwd = trim($_POST["txt_pwd"]);
if($username == ''){
header("location:index.php?err_msg=1");
exit;
}
if($pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT `username`,`password` FROM users WHERE `username`= '".$username."' and password= '".$pwd."'";
$result = mysqli_query($sql);
if(mysqli_num_rows($result)>0){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
?>
How would I make this work, I asked before and didn't get a correct answer. This code is the user login, so when they log in I want username and avatar to be trackable through out the site. So far I just have username. I have tried methods and have failed every time.
$username = $_POST['username'];
$password = sha1($_POST['password']);
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
$count=mysqli_num_rows($result);
if ($count == 1)
{
$row = mysqli_fetch_array($result);
while ($_SESSION['username'] = $row['username'])
{
session_start();
header('Location: index.php');
}
}
else
{
echo 'Invalid Logins';
}
mysqli_close($conn);
?>
Supposing you have avatar stored in the avatar field in the database:
if ($count == 1)
{
session_start();
$row = mysqli_fetch_array($result);
$_SESSION['username'] = $row['username'];
$_SESSION['avatar'] = $row['avatar'];
header('Location: index.php');
}
else
{
echo 'Invalid Logins';
}
Okay, so I want to make a simple login page. I've created a register page successfully, but i can't get the login thing down.
login.php:
<?php
session_start();
include("mainmenu.php");
$usrname = mysql_real_escape_string($_POST['usrname']);
$password = md5($_POST['password']);
$con = mysql_connect("localhost", "root", "g00dfor#boy");
if(!$con){
die(mysql_error());
}
mysql_select_db("users", $con) or die(mysql_error());
$login = "SELECT * FROM `users` WHERE (usrname = '$usrname' AND password = '$password')";
$result = mysql_query($login);
if(mysql_num_rows($result) == 1 {
$_SESSION = true;
header('Location: indexlogin.php');
}
else {
echo = "Wrong username or password." ;
}
?>
indexlogin.php just echoes "Login successful." What am I doing wrong?
Oh, and just FYI- my database is "users" and my table is "data".
<?php
session_start();
include("mainmenu.php");
$usrname = mysql_real_escape_string($_POST['usrname']);
$password = md5($_POST['password']);
$con = mysql_connect("localhost", "root", "g00dfor#boy");
if (!$con) {
die(mysql_error());
}
mysql_select_db("users", $con) or die(mysql_error());
$login = "SELECT * FROM `users` WHERE (usrname = '$usrname' AND password = '$password')";
$result = mysql_query($login);
if (mysql_num_rows($result) == 1) {
$_SESSION['logged_in'] = true;
header('Location: indexlogin.php');
exit;
} else {
echo "Wrong username or password.";
}
?>
I added mysql_real_escape_string() to prevent SQL injection.
No, I didn't because you already had it.
I cleaned up the formatting of the code a bit.
I changed $_SESSION = true; (which doesn't make sense) into $_SESSION['logged_in'] = true;. Then, in indexlogin.php you can do something like if ($_SESSION['logged_in']) { echo $secret; }
I fixed echo = "Wrong username or password."; to echo "Wrong username or password.";
I added a closing bracket near mysql_num_rows($result) == 1.
You said:
my database is "users" and my table is
"data".
If this is correct, you will need to change SELECT * FROM users to SELECT * FROM data.
I don't think you can set $_SESSION = true, because $_SESSION is an array. Try $_SESSION['logged_in'] = true.