I am having problem when trying to change the password in my application. It keep showing current password is invalid. It might be problem from my PHP coding. But I can't find the problem. This is my code for PHP.
<?php
require ("config1.php");
if (!empty($_POST)) {
$lecID = $_GET['lecID'];
$query = "UPDATE lecturer SET lecPass= :lec_Pass WHERE lecID = '$lecID' ";
$query_params = array(':lec_Pass'=> $_POST['lecPass']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error1. Please try again";
die(json_encode($response));
}
$validate_info = false;
// Fetching rows from query
$row = $stmt->fetch();
if ($row) {
if ($_POST['lecPass'] === $row['lecPass']) {
$changePass_ok = true;
}
}
if ($changePass_ok) {
// UserLogin
$response['success'] = 1;
$response['message'] = "Password changed successfully";
die(json_encode($response));
}
else {
$response["success"] = 0;
$response["message"] = "Failure";
die(json_encode($response));
}
}
?>
Appreciate if someone can guide me. Thanks.
$row = $stmt->fetch();
if ($row){
if($_POST['lecPass'] === $row['lecPass']){
$changePass_ok=true;
}
}
This isn't going to work. Doing a fetch() on an UPDATE statement is never going to return anything, because UPDATE statements don't return rows. There is nothing to compare.
You have two options:
1) Simply check that the UPDATE statement succeeded. This should really be sufficient evidence that the password was successfully updated, without having to select the row out again.
2) The lengthier way, more similar to what you're trying now is that, following the UPDATE, you run a separate SELECT statement to fetch the same row again from the database and compare the value returned against the $_POST value.
N.B. As others have pointed out in the comments, storing your passwords in plain text and transmitting them over unencrypted HTTP is incredibly insecure and asking for trouble. You should switch to HTTPS and also store the passwords in your database using a one-way hash, so that anyone with access to the DB cannot immediately steal the passwords. Then when the user logs in, you hash the password value they supply using the same algorithm, and compare that with the value in the DB in order to validate the login.
Related
I am building a log in system and every other part works perfectly fine except for the portion that cross references the entered password with the password in the database. So when I checked to see if the passwords match I realized that the password from the database is coming back as null. May I ask what is happening?? (There is no issue with the "uidExists" method, it seems to just be in the "loginUser" method).
This is based of of this video https://www.youtube.com/watch?v=gCo6JqGMi30
I believe its around the hour and 40 minute mark he gets to the loginUser function.
function loginUser($conn,$username,$pwd){
$uidExists = uidExists($conn,$username,$username);
if($uidExists === false){
header("location: ../login.php?error=wrongslogin");
exit();
}
else{
echo $pwd;
if(is_null($uidExists["userPwd"])){
echo "Empty bruv";
}
else{
echo $uidExists["userPwd"];
}
}
function uidExists($conn,$username,$email){
$sql = "SELECT * FROM users WHERE userUid = ? OR userEmail = ?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)){
header("location: ../signup.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt,"ss",$username,$email);
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
if(mysqli_fetch_assoc($resultData)){
return $row;
}
else{
$result = false;
return $result;
}
mysqli_stmt_close($stmt);
}
This doesn't look right:
$uidExists = uidExists($conn,$username,$username);
Should this be:
$uidExists = uidExists($conn,$username,$userPwd);
Good morning,
I had some problems yesterday and got help, unfortunately, my app still not does 100% does what I want it to do, although only a small detail is missing.
Given a scenario where I want to do an SQL injection to drop a database, and when it happens, render a PHP page. Everything works fine until I want the render to happen - even though the injection executes and the DB is dropped when I check it MySQL, still no rendering. The problem is probably due to the incorrect usage of multi_query. More details in comments in the code.
<?php
include("/../../connection.php");
if(isset($_POST["button_one"])){
$username = $_POST['username'];
$password = $_POST['password'];
if($conn->multi_query("SELECT id FROM users WHERE username = '$username' OR password = '$password'")) // IF THE USER HAS A VALID USERNAME OR PASSWORD,
{
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) { // THEN ENABLE BUTTON TWO, WHICH HAS TO BE CLICKED TO DROP THE DATABASE
echo "
<script type=\"text/javascript\">
document.getElementById('button_two').disabled=false;
</script>
";
}
$result->free();
}
} while ($conn->next_result());
}
}
if(isset($_POST["button_two"])){
$username = $_POST['username']; // SQL INJECTION TO DROP THE DB HAPPENS HERE
$password = $_POST['password'];
if($conn->multi_query("SELECT id FROM users WHERE username = '$username' OR password = '$password'")) // SQL INJECTION SUCCEEDED
{
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) {
if ($result = $conn->query("SHOW DATABASES LIKE 'mydatabase'")) { // NO MORE DATABASE LIKE THAT, IT HAS BEEN DROPPED DUE TO THE INJECTION
if($result->num_rows == 0) {
include("another.php"); // THE PROBLEM IS HERE. EVEN THOUGH THE DB IS DROPPED, THIS PAGE IS NOT RENDERING
}
}
}
$result->free();
}
} while ($conn->next_result());
}
}
?>
Any helpful idea would be appreciated!
The code block to include another.php never runs, because the SHOW DATABASES query fails.
I tested your code and added some error reporting:
if ($result = $conn->query("SHOW DATABASES LIKE 'mydatabase'")) {
if($result->num_rows == 0) {
include("another.php");
}
} else {
echo "Error: {$conn->error}\n";
}
I got this:
Error: Commands out of sync; you can't run this command now
You can't run another SQL query while the one you already have executed still has results to fetch. Even though you have used store_result() to fetch the result set, that only fetches the current result set. You used mulit_query() which produces multiple result sets. You have to process all result sets until the end of the next_result() loop before you can start a new query.
Another lesson here is that you should always check for and report errors after you try to query() or multi_query() or prepare() or execute().
Here's an example: You have to wait until after the last result has been processed before you can run another query. This means after the loop on $conn->next_result() is done.
if(isset($_POST["button_two"])){
$username = $_POST['username'];
$password = $_POST['password'];
if($conn->multi_query("SELECT id FROM users WHERE username = '$username' OR password = '$password'"))
{
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) {
// DISPLAY RESULTS FROM QUERY
}
}
$result->free();
} while ($conn->next_result());
// CAN'T START ANOTHER QUERY UNTIL AFTER THE NEXT_RESULT LOOP IS DONE
if ($result = $conn->query("SHOW DATABASES LIKE 'mydatabase'")) {
if($result->num_rows == 0) {
include("another.php");
}
}
}
public function getLoginInfo($username,$password){
$conn=DB::connect();
session_start();
$sql="select * from owner where o_email='".mysql_real_escape_string($username)."' and o_password='".mysql_real_escape_string($password)."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$_SESSION['email']=$username;
$_SESSION['password']=$password;
}
header("location:../owner/owner_dashboard.php");
} else {
header("location:../owner/owner_login.php");
}
$conn->close();
}
i have added username and password to my session array but i also want to save id into session array which is stored into databse as "o_id"
You are over complicate the process than necessary. mysql_ extensions are also deprecated.Therefore, you should not use them. use prepare statements which prevent against sql injections. In additional, there is no need for you to store the password in the session. Your password should be stored in the database as hashed so storing it in session wont be reliable to you. Once you find a match against the username and password you searched for, you only need to store the username in the session. In your application, you can compare against the username of logged in area. I modified your code to a much cleaner solution. I had to made few assumptions such as your conn is a PDO.
public function getLoginInfo($username,$password)
{
//start the session only if it has not started somewhere else
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
//try to query the database
try {
$conn = DB::connect();
$sql = 'Select * from owner where o_email= :email and o_password = :password';
$conn->prepare($sql);
$res = $conn->execute(array(':email' => $username, ':password' => $password));
//check if the data exist. only true if result set is greater than 0
if ($res->rowCount() > 0)
{
$_SESSION['email']=$username;
header("location:../owner/owner_dashboard.php");
exit("login success, redirecting to dashboard...");
}
//doesnt exit so go back to login
header("location:../owner/owner_login.php");
exit('Invalid username or password. Redirecting back to lgoin...');
}
//Error is only output for debugging purpose. I would encourage turn this off in production
catch(Exception $e)
{
print_r($e->getMessage());
}
}
First of all, it must be clear that if you are querying for logging
in, then query will return only one row, so using while is
meaningless.
public function getLoginInfo($username,$password){
$conn=DB::connect();
session_start();
$sql="select * from owner where o_email='".mysql_real_escape_string($username)."' and o_password='".mysql_real_escape_string($password)."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Edited from here
// output data of each row
$row = $result->fetch_assoc();
$arraydata[$row['id']] = $row;
$_SESSION['user_info']=$arraydata;
$_SESSION['current_loggedin_id']=$row['id'];
header("location:../owner/owner_dashboard.php");
} else {
header("location:../owner/owner_login.php");
}
$conn->close();
}
I have coded a php script that will generate a pdf file from some results. My select statement needs to be filtered with a where condition. Basically, I want to test my php script to see if it works well or not. How can I assign the where condition in the link itself?
this is my php code :
$query = "
SELECT
user_id
FROM TahdirUsers
WHERE
username = ':username'
";
$query_params = array(
':username' => $_POST['username']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row)
{
if ($_POST['password'] === $row['password'])
{
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
}
else
{
$response["success"] = 0;
$response["message"] = "Invalid password!";
$pdf = new PDF(PDF_PAGE_ORIENTATION,PDF_UNIT,PDF_PAGE_FORMAT,true, 'UTF-8', true);
$pdf->SetFont('aefurat', '', 12, '', true);
// The first Parameter is localhost again unless you are retrieving data from a different server.
// The second parameter is your MySQL User ID.
// The third parameter is your password for MySQL. In many cases these would be the same as your OS ID and Password.
// The fourth parameter is the Database you'd like to run the report on.
$pdf->connect('xxxxxxxxx','xxxxxxx','xxxxxxxxx','xxxxxxxx');
// This is the title of the Report generated.
$attr=array('titleFontSize'=>24,'titleText'=>'THIS IS MY PDF FILE');
// This is your query. It should be a 'SELECT' query.
// Reports are run over 'SELECT' querires generally.
$pdf->mysql_report($query,false,$attr);
$pdf->Output('htmlout.pdf', 'I');
die(json_encode($response));
}
}
else
{
$response["success"] = 0;
$response["message"] = "this username in not in our database!";
die(json_encode($response));
}
To clarify my question. If my website link is www.testtesttest.com, how do I implement the where condition from the select statement in the URL
If my comment above is wrong, and your question is literally "how do I pass data from a URL to a PHP script", the answer is that you use the $_GET superglobal variable to access query strings in the standard format .../path/to/script.php?var1=value1&var2=value2...
So the URL http://amjad-test.site40.net/arabictest.php?username=imsop will execute 'arabictest.php' and populate the variable $_GET['username'] with the value 'imsop'. You then use that variable wherever you like in your code.
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."'";