I'm just creating a simple login script to check the username/password, if there's a match with the database then it'll login. I think I have most of it, it opens up the database, grabs username/pw from the login. I think I set up my query right also that it grabs the username and pw. How would I go about comparing it? I've been stuck on this for quite a while. My fetch isn't working correctly also, it gives me an error. I'm very new to SQLite/Databases so this may seem very bad code but I'm trying my best.
<?php
//opens database
class MyDB extends SQLite3
{
function __construct()
{
$this->open('UserAccounts.db');
}
}
$db = new MyDB();
//username and pw from index.html
$user = $_REQUEST['myusername'] ;
$pw = $_REQUEST['mypassword'] ;
//if there is a database, it opens.
if(!$db){
echo $db->lastErrorMsg();
} else {
//Test to see if things are working correctly.
echo "Opened database successfully\n";
echo "$user";
echo "$pw";
}
$result = $db->query("SELECT * FROM login WHERE user = '$user' AND password = '$pw'");
if ($result->fetchColumn() == $user) {
$_SESSION['loggedin'] = true;
echo "Success";
};
if(!$_SESSION['loggedin']){
echo "Didn't Work";
exit;
};
Probably looks like this:
$fromDB = $result->fetchArray();
if ($fromDB['user'] == $user) {
Related
I am trying to user prepared statements to find a user record and store the users ID in a php variable to use later on. I would like to echo the variable contents. How do I check the result using Prepared statements?
My CODE:
if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {
$overridePasswordInput = $_POST['overridePassword'];
$overrideUsernameInput = $_POST['overrideUsername'];
$roleID = '154';
$overrideUniqueID = $_POST['overrideUniqueID'];
//Not sure how to properly compare stored passwords vs password given by user...
$overridePassword = mysqli_real_escape_string($overridePasswordInput);
$overrideUsername = mysqli_real_escape_string($overrideUsernameInput);
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql1 = "SELECT users.id FROM users WHERE (users.login = ?) AND (users.password = ?)";
$stmt1 = $conn->prepare($sql1);
$stmt1->bind_param('ss', $overrideUsername, $overridePassword);
$stmt1->execute();
$stmt1->bind_result($userID);
$stmt1->get_result();
if ($stmt1->get_result()) {
echo $userID;
} else {
echo 'User credentials incorrect. Please try again';
}
$stmt1->close();
//Close the Database connection.
$conn->close();
}//End If statement
Further more, this is the pre-existing code the original programmer used to authenticate users into the program:
if(!defined("noStartup")){
$scriptname = basename($_SERVER["PHP_SELF"]);
$phpbmsSession = new phpbmsSession;
//Testing for API login
if(strpos($scriptname,"api_")!==false){
if(isset($_POST["phpbmsusername"]) && isset($_POST["phpbmspassword"])){
$phpbmsSession->loadDBSettings();
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
include_once("common_functions.php");
$phpbmsSession->loadSettings($sqlEncoding);
$phpbms = new phpbms($db);
if(!$phpbmsSession->verifyAPILogin($_POST["phpbmsusername"],$_POST["phpbmspassword"],ENCRYPTION_SEED))
$error = new appError(-700,"","Login credentials incorrect",true,true,true,"json");
} else
$error= new appError(-710,"","No login credentials passed",true,true,true,"json");
} else {
$phpbmsSession->loadDBSettings($sqlEncoding);
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
$phpbmsSession->loadSettings($sqlEncoding);
include_once("common_functions.php");
$phpbms = new phpbms($db);
if(!isset($noSession))
$phpbmsSession->startSession();
if (!isset($_SESSION["userinfo"]) && $scriptname != "index.php") {
if(isset($loginNoKick)){
if(!isset($loginNoDisplayError))
exit();
} else{
goURL(APP_PATH."index.php");
}
}
}
$db->stopOnError=true;
}//end if
And the verifying function:
function verifyAPIlogin($user,$pass){
$thereturn=false;
$this->db->stopOnError = false;
$querystatement = "SELECT id, firstname, lastname, email, phone, department, employeenumber, admin, usertype
FROM users
WHERE login!=\"Scheduler\" AND login=\"".mysql_real_escape_string($user)."\"
AND password=ENCODE(\"".mysql_real_escape_string($pass)."\",\"".mysql_real_escape_string(ENCRYPTION_SEED)."\")
AND revoked=0 AND portalaccess=1";
$queryresult = $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-720,"","Error retrieving user record",true,true,true,"json");
return false;
}
if($this->db->numRows($queryresult)){
//We found a record that matches in the database
// populate the session and go in
$_SESSION["userinfo"]=$this->db->fetchArray($queryresult);
$querystatement="UPDATE users SET modifieddate=modifieddate, lastlogin=Now() WHERE id = ".$_SESSION["userinfo"]["id"];
$queryresult=# $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-730,"","Error Updating User Login Time",true,true,true,"json");
} else
$thereturn=true;
}
return $thereturn;
}
}//end loginSession class
NOTE: I have already tested that my $_POST() values are successfully coming through to my script.
EDIT:: added more code to give a better overall picture of what I'm attempting to do. Any shared tuturials on password encryption/authenticating users would be greatly appreciated.
Thank you!
As I mentioned in the comment, PHP now has a couple built in methods to handle encryption and decryption of passwords that you might find helps solve your problem:
password_hash and
password_verify
I use CI 2.2 to build a simple login system. But I get problem when I try to generate session. Of course I have properly set up libraries (database, session) and User_M. When I retrieve data from database (without session), that's work fine. This is my Controller code:
public function verify()
{
// Define variable
$user = $this->input->post('username');
$pass = $this->input->post('password');
// Check input data
if (!empty($user) AND !empty($pass))
{
// Check match data from db
$checks = $this->User_M->check_user($user, $pass);
if($checks->num_rows() == 1)
{
foreach ($checks->result() as $check)
{
$sess = array (
'username' => $check->username,
'logged_in' => TRUE
);
$rest = $this->session->set_userdata($sess);
if ($rest)
{
echo "working";
} else {
echo "not working";
}
}
} else {
echo "Not found";
}
} else {
echo "You've empty field";
}
}
Additional explain, I check the result with if ($rest)...bla..bla..bla, that's echoing Not Working. Please let me know where's my mistakes?
Thank in advance
I think the problem is with this statement
$rest = $this->session->set_userdata($sess);
the set_userdata() does not return anything, so according to your condition it will always execute the else part.
Try to change your condition like this
if (!empty($this->session->userdata("username"))){
echo "Working";
}else{
echo "Not Working";
}
I am new in PHP and need help with my below code. When I am entering wrong userid instead of giving the message "userid does not exist" it is showing "password/id mismatch. Please guide me where I am wrong.
<?php
session_start();
$id = $_POST['userid'];
$pwd = $_POST['paswd'];
$con = mysqli_connect("localhost", "????", "????", "??????");
if ($con) {
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
if ($result) {
$row = mysql_fetch_array($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist !!!";
}
} else {
echo "Connection failed - ".mysqli_error()." -- ".mysqli_errno();
}
?>
The main problem you have is that you're mixing up between the mysqli and mysql functions. These two libraries are not compatible with each other; you must only use one or the other.
In other words, the following line is wrong:
$row=mysql_fetch_array($result);
It needs to be changed to use mysqli_.
While I'm here, going off-topic for a moment I would also point out a few other mistakes you're making:
You aren't escaping your SQL input. It would be extremely easy to hack your code simply by posting a malicious value to $_POST['userid']. You must use proper escaping or parameter binding. (since you're using mysqli, I recommend the latter; it's a better technique).
Your password checking is poor -- you don't appear to be doing any kind of hashing, so I guess your passwords are stored as plain text in the database. If this is the case, then your database is extremely vulnerable. You should always hash your passwords, and never store the actual password value in the database.
I've gone off topic, so I won't go any further into explaining those points; if you need help with either of these points I suggest asking separate questions (or searching here; I'm sure there's plenty of existing advice available too).
else
{
echo "ID/Password Mismatch";
}
is connected with the
if($row["userid"]==$id && $row["paswd"]==$pwd)
{
So since you are giving a wrong id. It echo's: ID/Password Mismatch
Also the else at if ($result) { wont ever show since
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
You need some additionnal checks:
select * return 1 row (not 0, and not more)
you need to protect the datas entered by the html form (for example someone could enter 1 or 1 to return all rows
<?php
session_start();
$con = mysqli_connect("localhost", "????", "????", "??????");
$id = mysqli_real_escape_string($_POST['userid']);
$pwd = mysqli_real_escape_string($_POST['paswd']);
if ($con) {
// don't even do the query if data are incomplete
if (empty($id) || empty($pwd)
$result = false;
else
{
// optionnal : if userid is supposed to be a number
// $id = (int)$id;
$result = mysqli_query($con, "SELECT * FROM users WHERE userid='$id'");
}
if (mysqli_num_rows($result) != 1)
$result = false;
if ($result) {
$row = mysqli_fetch_assoc($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist, or incomplete input";
}
} else {
echo "Connection failed - " . mysqli_error() . " -- " . mysqli_errno();
}
?>
Try with isset() method while you are checking if $result empty or not.
that is in line
if ($result) {.......}
use
if (isset($result)) { .......}
$result is always true, because mysqli_query() only returns false if query failed.
You could check if $result has actual content with empty() for example.
You can use this sql compare password as well with userid
$sql= "SELECT * FROM users WHERE userid='".$id.", and password='".$pwd."'";
I am creating a web based application using HTML5, it is connected to a mySQL database. I am trying to use PHP to connect the two.
I am trying to create a login page that checks the number and password against that in the database to see if it is a valid login.
Hard coding the number and password works fine but when trying to apply it to the database I always get a 'Logged in' message even though the login credentials are invalid. I tried using both $_POST and $dbRow but to no avail.
<?php
session_start();
$s_number = $_POST["snumber"];
$s_pass = $_POST["passwd"];
//$s_number = "12345";
//$s_pass = "qwerty";
//$s_permission = "manager";
include ("dbConnect.php");
$dbQuery = "SELECT * FROM staff_details WHERE staff_number='$s_number' AND password='$s_pass'";
$dbResult = mysql_query($dbQuery);
$dbRow=mysql_fetch_array($dbResult);
if ($_POST["snumber"]==$s_number) {
if ($_POST["passwd"]==$s_pass) {
echo "<p>Logged in!</p>";
} else {
echo "<p>Wrong Password</p>";
}
}
else echo "<p>Bad username and password</p>";
/*if ($dbRow["username"]==$s_number) {
if ($dbRow["password"]==$s_pass) {
echo "<p>Logged in!</p>";
}
else {
echo "<p>Wrong Password</p>";
}
} else {
echo "<p>Bad username and password</p>";
}*/
?>
I am very new to PHP. I have searched for other examples but there seems to be many different ways to do this that I dont understand. Any help would be much appreciated!
Try this:
<?php
include ("dbConnect.php");
if(isset($_POST["snumber"]))
{
$s_number = mysql_real_escape_string($_POST["snumber"]);
$s_pass = mysql_real_escape_string($_POST["passwd"]);
$dbQuery = "SELECT * FROM staff_details WHERE staff_number='$s_number' AND password='$s_pass'";
$dbResult = mysql_query($dbQuery);
$dbRow=mysql_fetch_assoc($dbResult);
if ($dbRow["staff_number"]==$s_number && $dbRow["password"]==$s_pass) {
echo "<p>Logged in!</p>";
}
else {
echo "<p>Wrong Password</p>";
}
}
else {
echo "<p>Bad username and password</p>";
}
?>
PS: Go for mysqli or PDO ;) ; you can try a count or a mysql_num_rows to see if the match result is zero.
Saludos .
Adrian and Robert have addressed parts of the problem.
If you're just learning PHP then all the more reason that you should start writing your code to use the mysqli API rather than the deprecated mysql_ functions. They are almost the same - but the latter will disappear at some point in the future.
If you're writing a login page then you're presumably concerned about security - however without properly escaping your code it's trivial to bypass the control mechanism (and in some cases exposes your database to serious vandalism / disclosure issues).
Further even by fixing the SQL injection problem, it's easy to get past the authentication using session fixation.
The next mistake is that you never check if the interactions with the database are successful or not.
Hence this looks like a duplicate of this question - although I've not flagged it as such due the poor quality of the answers / discussion on that post.
Further, since you've only SELECTed rows from the database matching the username / password, why do you then compare the username and password with the data you retrieved?
It's generally considered good security practice, to NOT explain why the login failed when some provided authentication details.
So trying again....
<?php
session_start();
include ("dbConnect.php");
function auth($user, $pass)
{
$user=mysqli_real_escape_string($user);
$pass=mysqli_real_escape_string($pass);
$qry="SELECT SUM(1) AS matches
FROM YOURDB.staff_details
WHERE staff_number='$user'
AND password='$pass'";
$res=mysqli_query($qry) || die "Sorry - not available";
$r=mysql_fetch_assoc($res);
return $r['matches'];
}
if (auth($_POST["snumber"], $_POST["passwd"])) {
session_regenerate_id();
echo "<p>Logged in!</p>";
} else {
echo "<p>Sorry - invalid authentication</p>";
}
You need to use $dbRow instead of $_POST.
As currently you are just comparing $_POST with $_POST.
It's always going to be the same.
Secondly, you've specified different field names in your query and array key.
Try this.
<?php
session_start();
$s_number = $_POST["snumber"];
$s_pass = $_POST["passwd"];
//$s_number = "12345";
//$s_pass = "qwerty";
//$s_permission = "manager";
include ("dbConnect.php");
$dbQuery = "SELECT * FROM staff_details WHERE staff_number='$s_number' AND password='$s_pass'";
$dbResult = mysql_query($dbQuery);
$dbRow=mysql_fetch_array($dbResult);
if ($_POST["snumber"]==$dbRow['staff_number']) {
if ($_POST["passwd"]==$dbRow['password']) {
echo "<p>Logged in!</p>";
} else {
echo "<p>Wrong Password</p>";
}
}
else echo "<p>Bad username and password</p>";
/*if ($dbRow["username"]==$s_number) {
if ($dbRow["password"]==$s_pass) {
echo "<p>Logged in!</p>";
}
else {
echo "<p>Wrong Password</p>";
}
} else {
echo "<p>Bad username and password</p>";
}*/
?>
EDIT: Although you don't really need to do the If Statement after.
If you're getting a result from your DB query with the Username/Password matching, the credentials are correct.
So you could do,
if (!empty($dbRow)){
echo "<p>Logged in!</p>";
} else {
echo "<p>Wrong Password</p>";
}
}
I am trying to create two separate sessions- one for if the user is admin and another if the user is author. $type stored type as enum (can be either author or admin). But my code is creating author session even for admin. I am new to PHP and MySQL . can somebody tell me where the error is in my code.
<?php
include("dbconnect.php");
$con= new dbconnect();
$con->connect();
//create and issue the query
$sql = "SELECT type FROM users WHERE username = '".$_POST["username"]."' AND password = PASSWORD('".$_POST["password"]."')";
$result = mysql_query($sql);
//get the number of rows in the result set; should be 1 if a match
if (mysql_num_rows($result) == 1) {
$type_num=0;
//if authorized, get the values
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
}
if($type == "admin")
{
$_SESSION['type']=1;
$u = 'welcome.php';
header('Location: '.$u);
}
else
{
$_SESSION['type']=$type_num;
$u = 'welcome.php';
header('Location: '.$u);
}
}
else {
//redirect back to loginfailed.html form if not in the table
header("Location: loginfailed.html");
exit;
}
?>
My welcome.php is as below
<?php
session_start();
?>
<html>
<body>
<h2>Welcome.</h2>
<?
if($_SESSION['type']==1){
echo "You are of the usertype Admin and your session id is ";
echo session_id();
}
else {
echo "You are of the usertype Author and your session id is ";
echo session_id();
}
?>
</body>
</html>
Thank You so much in advance.
Try to use roles for your permissions.
In general you have just one session. I mean you don't have two variables called _SESSION.
With the concept of roles you can simply check if a user has the permission to do something.
You have to call session_start() in the first part of the code, before register the var $_SESSION['type'] in the session
No your code seams fine, I think.
I don't see where you are calling the database
And what you have in there
So here is how you trouble shoot
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
echo $type . '<br />';
}
OR
echo '<pre>';
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
print_r($info);
}
echo '</pre>';
If you never see admin in there, and it must be 'admin' not Admin or ADMIN; then the problem is in your database. You don't have admin as admin defined, or spelled right.
By the way. see how nicely I formatted that. It's easier to read that way.
Coders wont look at your code if you don't do that.
Try using session_regenerate_id(); method to create different session ids.