I have a problem with my code. Or rather don't know how to implement what I would like to have.
I would like; Also in this code, check if the username have a 1 in active column. and if so the proceed to login protected page else return to login page.
<?php
session_start();
function validateUser(){
session_regenerate_id ();
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
}
$username = $_POST['username'];
$password = > $_POST['password'];
require('config.inc.php');
$db = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$stmt = $db->prepare("SELECT password_hash FROM users WHERE username =:username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR,32);
$stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC);
$db=null;
$dbhash = $result['password_hash'];
if ($dbhash == crypt($password, $dbhash)){
validateUser();
header('Location: ../main.php');
}else{
header('Location: ../index.php?invalidcreds=1');
die();
}
?>
So what you guys think? I have tried everything but can't get it to work.
Also I would like to have a admin column no/0 or yes/1 so I can protect certain links or text in my page. But first thing first.
You can add an is_active column in your db then use:
SELECT is_active, password_hash FROM users where username=:username
In your php just use:
if($result['is_active'])
{
//Send to restricted login
}
else
{
//Send to normal login
}
Also, like I said in a comment, you have a stray > when you initialize your password variable. It may be a reason why your code isn't working.
Okay so this is the code and it work perfect. And the > was just a typo sorry. Thanks Bun for your super easy code.
Does this look okay? Or just plain wrong. I'm a bit unsure of the if code or is this the way to go!?
<?php
session_start();
function validateUser(){
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
}
$username = $_POST['username'];
$password = $_POST['password'];
require('config.inc.php');
$db = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$stmt = $db->prepare("SELECT active, password_hash FROM users WHERE username = :username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR, 32);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$db =null;
if($result['active']){
$dbhash = $result['password_hash'];
if ($dbhash == crypt($password, $dbhash))
validateUser();
header('Location: ../main.php');
}
else{
header('Location: ../index.php?invalidcreds=1');
die();
}
?>
But now if I would like to do a admin column too and try to implement this here, how would I do this? I know there needs to be added perhaps a bit more code in other places also. Nothing pretty or advanced. It's just a simple login so. Any advice where I should direct my eyes at, private/public classes (I've tried this but I got lost in the code totaly)
Related
I have used a login system on my website using sessions.
This is how it looks,
<?php
session_start();
ob_start();
include 'includes/db.php';
$idadm=$_POST['idadm'];
$passadm=$_POST['passadm'];
$idadm = stripslashes($idadm);
$passadm = stripslashes($passadm);
$idadm = mysql_real_escape_string($idadm);
$passadm = mysql_real_escape_string($passadm);
$sql="SELECT * FROM admin WHERE aid='$idadm' and password='$passadm'";
$result = $conn->query($sql);
$count = $result->num_rows;
if($count == 1) {
$_SESSION['idadm'] = $idadm;
$_SESSION['passadm'] = $passadm;
if ($_SESSION['idadm'] == 'admin') {
header("location:admin/index.php");
} else {
header("location:subadmin/index.php");
}
} else {
header("location:index.php");
}
ob_end_flush();
?>
db.php has the database credentials.
This is the code that is on top of the protected pages,
<?php
session_start();
if (!isset($_SESSION['idadm'])) {
header('location:/index.php');
die;
}
?>
The login script works fine except for one problem, logged in users can access both admin and subadmin pages.
There is only one admin user and the ID for that user in the database is 'admin'. Admin should be able to access only 'admin/index.php' and other users should be able to access 'subadmin/index.php'.
How do I modify the script to make this happen?
So, first up, get the $_SESSION["idadm"] and $_SESSION['passadm']...
So firstly in your admin page would be this:
<?php
session_start();
if (!isset($_SESSION['idadm'])) {
header('location:/index.php');
die;
} else {
$username = $_SESSION["idadm"];
$password = $_SESSION['passadm']; // Also storing passwords in session vars is not a good idea. :/
Then open up a DB connection:
$pdo = new PDO($dsn, $DBUsername, $DBPass):
// or
$mysqli = mysqli_connect($host, $DBUsername, $DBPass, "admin")
Then check if current username and password is there in the DB...
I am doing it in PDO:
$sth = $pdo->prepare("SELECT COUNT(*) AS number_of_users FROM table_name WHERE aid = :username AND password = :password");
$sth->bindParam(":username", $username, PDO::PARAM_STR);
$sth->bindParam(":password", hash("YOUR_HASHING_ALGO", $password), PDO::PARAM_STR); // If you have not hashed the password you can remove the hash method, but not hashing a password is a horrible idea
$result = $sth->fetch(PDO::FETCH_ASSOC);
if( (int) $result["number_of_users"] >= 1 ) {
// yay he is an admin, do somethin'
} else {
// nope, he is not allowed to enter, what to do with him?
}
And at last close the else block with :
}
In the connection string's you have to use your own specific credentials and DB.
Hope it helps you!
So a couple days ago i had trouble creating a login, one person on that thread recommended me using prepared statements instead.
So I started looking up prepared statements using PDO and I've managed to create the register script with it. However, my login redirects me back to index.php everytime.
file1.php:
<?php
$username=$_POST['username'];
$password=$_POST['password'];
$db = new PDO('mysql:host=localhost;dbname=ismsite', 'db_username', 'db_password'); //this works
$result = $db->prepare("SELECT * FROM users WHERE username=:username AND password=:password");
$result->bindParam(':username', $username);
$result->bindParam(':password', $password);
$result->execute();
$row = $result->fetch(PDO::FETCH_NUM);
if($row > 0) {
session_start();
$_SESSION['userid'] = $row['user_id']; // Initializing Session
$_SESSION['voornaam'] = $row['Voornaam']; // Initializing Session
$_SESSION['achternaam'] = $row['Achternaam'];
$_SESSION['adres'] = $row['adres'];
$_SESSION['email'] = $row['email'];
$_SESSION['username'] = $row['username'];
$_SESSION['password'] = $row['password'];
}
header("location: profile.php");
exit();
?>
On profile.php i have a small bit of code checking if the session with user_id exists. if it doesn't you'll be reverted back to index.php. This would indicate my userid session not being set while i am setting it right there. Either selecting doesn't work the same way as inserting or i have a stupid error.
Can anyone help?
Looks like i made the mistake of using FETCH_NUM instead of using FETCH_ASSOC in:
$row = $result->fetch(PDO::FETCH_ASSOC);
used to be
$row = $result->fetch(PDO::FETCH_NUM);
I've been trying to create a login for my project, but i don't know what i'm doing wrong.
This is what i use to check if the button is pressed:
if(isset($_POST['login'])){
//Get Vars
$username = $_POST['username'];
$password = md5($_POST['password']);
if(login($username, $password)){
echo 'You have been logged in';
} else {
echo 'Wrong username and password';
}
}
This is my login function:
function login($username, $password){
$db = new Database();
$query=("SELECT * FROM user
WHERE username = $username
AND password = $password");
//Bind Values
$row = $db->select($query);
-----------------------------------------
$count = mysqli_num_rows($row);
//Check Rows
if($count == 1){
setUserData($row);
return true;
} else {
return false;
}
-------------------------------------
I BELIEVE THIS IS THE PART OF THE ERROR
}
And here is my setUserData function:
function setUserData($row){
$_SESSION['is_logged_in'] = true;
$_SESSION['user_id'] = $row['id'];
$_SESSION['username'] = $row['id'];
$_SESSION['name'] = $row['name'];
}
I don't know if i need to start a session for this, and if i need to, where do i put the code.
Also how can i initialize it in the code to check, lets say, if $count works, because when i simply type echo $count, it just says Unidentified variable : count
For education purposes, I will list a referente to rewrite your code:
Sanitize $_POST with filter_input
Store pass as md5 hash it's a security flaw
See session_start and session_regenerate_id
Prefer to use PDO against direct mysql native functions
Well i found my error, its was the form that was making the problems, i forgot to put in method="POST" and action="login.php".
Silly me. Thank you all for helping me.
I guess your query should be:
$query=("SELECT * FROM user
WHERE username = '$username'
AND password = '$password'");
For some reason inputs in my login page don't seem to be getting processes correctly. Correct user inputs are getting returned as invalid (wrong password) having had a look through, I can't see anything particularly obvious. But I can only assume the username or password isn't getting passed for some reason. Would someone more experienced be able to take a look and suggest how I can put it right. Thanks guys. P.S My form is OK, so not included.
function logcon($user, $password )
{
$user = mysqli_real_escape_string($this->conn, $user);
$esc_password = mysqli_real_escape_string($this->conn,$password);
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$password}'";
$result = mysqli_query($this->conn, $sql);
$row = mysqli_fetch_array($result);
return $row;
}
Login page.
if(isset($_POST['submit'])){
$user=$_POST['user'];
$password=$_POST['password'];
//To ensure that none of the fields are blank when submitting the form if
if(isset($_POST['user']) && isset($_POST['password']))
{
$user = stripslashes($user);
$password = stripslashes($password);
$db1=new dbmember();
$db1->openDB();
$row=$db1->logcon($user, $password);
if($row[0]==1)
{
session_start();
$_SESSION['user'] = $user;
$_SESSION['password'] = $password;
$_SESSION['loggedin'] = "true";
header("location:index.php");
}
else
{
print ('<div id="error">Acess denied, wrong username or password?</div>');
}
}
else
{
print ('<div id="error">Enter something!</div>');
}
}
It appears you are using the wrong variable name in your query. I would also suggest you look into doing some sort of hashing and salting of your passwords instead of saving them as plain text.
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$password}'";
should be
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$esc_password}'";
And your conditional check seems off, you are checking to see if the first field in the results is = 1 instead of seeing if there is a return.
if($row[0]==1)
Should probably be
if($row)
I have to make a login system on my website, but my users don't have the same things on their sites so I will $_GET my users' customers_id (from database) in the URL when they are logged in.
But I cannot see how.
my login code is this.
<?php
$email = $_POST['user'];
$password= $_POST['pass'];
$login = $_POST['login'];
$user_custermers_id = $_GET['id'];
if($login == 'Login' || isset($login))
{
global $wpdb;
$get = mysql_query("SELECT * FROM das_custermer_users WHERE email = '$email' AND password ='" . md5($password)."'") or die(mysql_error());
$result = mysql_num_rows($get);
if($result == 0)
{
$msg = "Wrong E-mail or Password";
}
else
{
session_start();
$_SESSION['email'] = $email;
header("location: http://dashboard.tg.com");
}
}
?>
You're writing really bad and dangerous code. What if I catch $_POST['email'] and change it to '--;DELETE your_data_base; ?
You don't check what data you have and SQL injection is possible in your example.
if($login == 'Login' || isset($login))
this condition is without sense because if there is $login== 'login' then isset is TRUE so second OR condition is unneccesary
session_start();
you should move it to 1st line.
global is an old PHP syntax avoid it.
$user_custermers_id = $_GET['id']; this is really bad. You should cast to to int or use intval()
If I were you I would use PDO connection. PDO has PDOStatement::rowCount you can use this property to check if there are any rows.
PDO throws exceptions so mysql_errror() is not needed. mysql_num_rows() is deprecated as of PHP 5.5.0, and will be removed in the future so avoid it.
I found this sample in internet. This code should be also in try catch block to handle exceptions
$login = mysql_escape_string(trim($_POST['login']));
$pass = mysql_escape_string(trim($_POST['pass']));
$dbh = new PDO('mysql:host=localhost;dbname=mydatabase', 'user', 'pass');
$sth = $dbh->prepare("SELECT * FROM table WHERE login = ? AND pass = ?");
$sth->bindParam(1, $login);
$sth->bindParam(2, md5($pass));
$sth->execute();
if ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
}