Can't echo out something after a MySqli query? - php

Today, I have a question regarding PHP.
I know to be fact based on my setup that this function is being called. However, only the first requested 'echo' is being displayed (I used "cats", long story...).
I know that a lot of times this is something simple like a missed end quote, but my PHP doesn't throw me any errors. Anyting I'm doing wrong? I can't get anything after my code.
Before I do this:
$connection = new mysqli('localhost', 'root', 'root', 'VV_root') or die("There was an error connecting; " . mysqli_connect_error);
Then this is my function.
function knock_on() {
echo("cats");
// It is asssumed that from here, all information is to be kept as secure as possible in the transactions
// Get all the ingredients
$username = $_POST['username'];
$password = $_POST['password'];
// Now, we have all the ingredients
// Mix password !IMPORTANT!
// Now, run the query to see if we get any matches.
$query = $connection->query("select * from user where username = " . $username . " & password = " . $password) or die("Something went wrong");
echo("cats2");
}

You are running into scope issues. The $connection variable is not available inside your knock_on() function. Pass the $connection as a parameter to your function definition.
Like this..
function knock_on($connection) { //Forget the global keyword thing.

Firs of all turn on error displaying and then you have an error in your query:
$query = $connection->query("select * from user where username = " . $username . " & password = " . $password) or die("Something went wrong");
Here you need to use AND operator not an & as you did:
username = " . $username . " AND password = " . $password
Abnd the second : $connection variable is not available inside your knock_on() function as
Shankar Damodaran mentioned.

Note this code is not tested.
$connection = new mysqli('localhost', 'root', 'root', 'VV_root') or die("There was an error connecting; " . mysqli_connect_error);
function knock_on() {
global $connection;
echo("cats");
// It is asssumed that from here, all information is to be kept as secure as possible in the transactions
// Get all the ingredients
$username = $_POST['username'];
$password = $_POST['password'];
// Now, we have all the ingredients
// Mix password !IMPORTANT!
// Now, run the query to see if we get any matches.
$query = $connection->query("select * from user where username = " . $username . " & password = " . $password) or die("Something went wrong");
if($query) {
return true;
} else {
return false;
}
}

There were several things that I had to fix, so here's my new working code
$connection = new mysqli("localhost", "root", "root", "VV_root");
The actual function:
function knock_on() {
echo("cats");
// It is asssumed that from here, all information is to be kept as secure as possible in the transactions
// Get all the ingredients
$username = $_POST['username'];
$password = $_POST['password'];
// Now, we have all the ingredients
// Mix password !IMPORTANT!
// Now, run the query to see if we get any matches.
if ($connection) {
$query = $connection->query("select * from user where username = '" . $username . "' and password = '" . $password . "'") or die("Something went wrong");
}
else {
echo($mysqli->connect_error);
}
echo("cats2");
}

Related

password_verify returns false. cant find error [duplicate]

This question already has answers here:
Using PHP 5.5's password_hash and password_verify function
(4 answers)
Closed 3 years ago.
I have been trying to figure out this problem for about 2 months and can't seem to figure it out. I have a database that returns the hashed password. I can confirm this works due to printing out all the information. It can return the non-hashed and hashed password perfectly fine but when it checks the password it will always return false.
I am not sure what to do. It could be something really easy but I seem to not be able to find it.
<?php
session_start();
$dbip = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "projectNitro";
$conn = new mysqli($dbip, $dbuser, $dbpass, $dbname);
if($conn->connect_error) {
echo("Connection failed: " . $conn->connect_error);
}
$password = mysqli_real_escape_string($conn, $_GET["pass"]);
$email = mysqli_real_escape_string($conn, $_GET["email"]);
$sql = "SELECT * FROM users WHERE email='{$email}' LIMIT 1";
$query = mysqli_query($conn, $sql);
$pass = $_GET["pass"];
if($query == TRUE) {
$row = mysqli_fetch_array($query);
$db_password = $row['password'];
$db_usertype = $row['accountType'];
$username = $row['username'];
echo $password;
echo "<br>";
echo $db_password;
echo "<br>";
$verify = password_verify($pass, $db_password);
if($verify) {
$_SESSION['username'] = $username;
$_SESSION['at'] = $db_usertype;
header("Location: http://website.com");
} else {
echo("DB Email: "
.$row["email"]
."<br>Username: "
.$row["username"]
."<br>DB Password: "
.$row["password"]
."<br>AccountType: "
.$row["accountType"]
."<br>Inserted Email: "
.$_GET["email"]
."<br>Inserted Password: "
.$_GET["pass"]."<br>");
if(password_verify($_GET["pass"], $row["password"])) {
echo("epic<br>");
} else {
echo("not epic<br>");
}
}
} else {
header("Location: http://website.com");
}
$conn->close();
?>
You need to do baby steps. keep stepping up as long as it works.
Here is a simpler version of your code that should work with the password sample from the official doc: http://php.net/manual/en/function.password-verify.php
Also use die(); to debug your code in every {} block.
In your current code you redirect to a website in both cases it's really hard to track what is wrong if you are redirected!
You have useless and unclear variables, for instance $dbpass, $db_password is very ambiguous, even if you and I understand it makes it not maintainable. As well as your coding style, you need to indent!
The next step you need to check if this code works, is replace the hard coded password with a hard coded password you have with hard coded hash as well.
<?php
session_start();
$dbip = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "projectNitro";
$conn = new mysqli($dbip, $dbuser, $dbpass, $dbname);
if ($conn->connect_error){
echo("Connection failed: " . $conn->connect_error) . '<br><br>';
}
$password = 'rasmuslerdorf';//mysqli_real_escape_string($conn, $_GET["pass"]);
// $email = mysqli_real_escape_string($conn, $_GET["email"]);
// $sql = "SELECT * FROM users WHERE email='{$email}' LIMIT 1";
// $query = mysqli_query($conn, $sql);
// $pass = $_GET["pass"];
// if ($query == TRUE) {
// $row = mysqli_fetch_array($query);
$db_password = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
// $username = $row['username'];
echo $password;
echo "<br>";
echo $db_password;
echo "<br>";
if (password_verify($password, $db_password)) {
die('ok');
} else {
die('not ok');
}
// } else {
// header("Location: http://website.com");
// }
$conn->close();
?>
Here I modified slightly and added a few comments along the code to help you understand the approach.
<?php
session_start();
// This array is used only like a simple namespace.
$dbCredentials = [
'host' => "localhost",
'user' => "root",
'password' => "",
'dbname' => "projectNitro"
];
$dbConn = new mysqli($dbCredentials['host'], $dbCredentials['user'], $dbCredentials['password'], $dbCredentials['dbname']);
if ($dbConn->connect_error) {
// Should not continue script if can't connect to DB.
die("Connection failed: " . $dbConn->dbConnect_error);
}
// You should check the existence of $_GET["pass"] before using it, with empty() or isset().
$passwordToCheck = mysqli_real_escape_string($dbConn, $_GET["pass"]);// Renamed var more meaningful.
$userEmail = mysqli_real_escape_string($dbConn, $_GET["email"]);
$sql = "SELECT * FROM users WHERE email='{$userEmail}' LIMIT 1";// Don't select * if you don't need everything.
$query = mysqli_query($dbConn, $sql);
$pass = $_GET["pass"];// you already have $passwordToCheck.
if ($query) {// Don't need == TRUE
// $row = mysqli_fetch_array($query);
$db_password = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
$username = $row['username'];
echo "$passwordToCheck<br>$db_password<br>";// This is way less verbose than repeating echo and uses less echo functions.
if (password_verify($passwordToCheck, $db_password)) {// Don't need to keep this condition in a variable.
die('ok');// this is just an example to test.
} else {
die('not ok');// this is just an example to test.
}
} else {
header("Location: http://website.com");// While debugging don't redirect, put die('message');
}
$dbConn->close();
?>

Check if a value exists in MySQL with php

I've been looking around stackoverflow and wasn't able to ever find a way that'd actually work. I have a simple php application
//Database credentials
$servername = "localhost";
$username = "root";
$password = "password";
$database = "database";
// Create connection to database
$db = new mysqli($servername, $username, $password, $database);
// Check connection for errors
if ($db->connect_error) {
die("<h1>Connection to database failed: " . $db->connect_error) . "</h1>";
};
$username = $json['statuses'][0]['user']['screen_name'];
$userid = $json['statuses'][0]['user']['id_str'];
$sql = "SELECT * FROM log WHERE userid='" . $userid . "' LIMIT 1";
if ($db->query($sql)->num_rows > 0) {
echo "<h4>This user already exists</h4>";
} else {
//Put the userid into the database
$sql = "INSERT INTO log (userid) VALUES ('" . $userid . "')";
if ($db->query($sql) === TRUE) {
echo "<h4>Added " . $username . " to the database</h4>";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
}
Currently it seems to be hit or miss. It'll work sometimes, other times a record will exist, and it'll still insert the userid again creating duplicates.
Like said #tadman Your code is BAD. Data from variable $json is directly inserted into query - this is not good...
Simple test:
I set :
$userid = "111111111a";
query:
$sql = "SELECT * FROM log WHERE userid='111111111a' LIMIT 1";
return TRUE because, this user doesn't exists in db,
or
$userID ='111111111\' OR \'1=1';
query:
$sql = "SELECT * FROM log WHERE userid='111111111' OR '1=1' LIMIT 1";
return TRUE because 1=1 is always true.
If column userid is INT type, $userid value is converted to 111111111 and inserted into log table

PHP MySQL Table, Using to log into account in the table

I have got a MySQL Table named 'MainData' and i have 3 columns 'username', 'email' and 'pass'. I have a snipped of my code, it all works except when i try to convert the users $_POST input into an md5 hash. When i leave the md5 encryption's off and all of the passwords are visible in the database it works but when i use md5 it doesnt work and just echo's 'Sorry, the username or password was incorrect.'
Here is the snipped of my code:
<?php
$servername = "localhost";
$username = "avxtechn_benph64";
$password = "admin123";
$dbname = "avxtechn_users";
$dbtable = "MainData";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$usr = $_POST["user"];
$psr = $_POST["password"];
$sql = "SELECT username, pass FROM " . $dbtable;
$result = $conn->query($sql);
$nameCount = 0;
$UserName = 0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ( $usr == $row["username"] && md5($psr) == $row["pass"]) {
$nameCount = $nameCount + 1;
$UserName = $usr;
}
}
} else {
echo "nil";
}
if ($nameCount > 0) {
echo ' Welcome back, ' . $UserName;
}else{
echo 'Sorry, that username or password was incorrect.';
}
$conn->close();
?>
This is the full code.
Here is the PHPMyAdmin database:
I guess that your problem is you stored passwords in your database before as a plain text.
So to get your authentification work now you should:
if ( $usr == $row["username"] && $psr == $row["pass"]) {
or
if ( $usr == $row["username"] && (md5($psr)) == md5($row["pass"])) {
but the best way is to convert your data (make backup first for sure) by running this query:
UPDATE MainData SET pass = MD5(pass)
then your code can start to work. but check the pass type before converting to assure that it can hold larger strings.
I would strongly recommend to change your code.
Use the following SQL code:
$result = $conn->query('SELECT count(*) as nr WHERE username = ' . $username . ' AND pass = MD5('. $password .'));
You should have an integer of 1 in "nr" if the login is valid.
Make Mysql do a single count of the usernames having that user/password combination.
Also MySQL is able to do the MD5 method for you.
( Instead of looping all the results in your resultset. )
EDIT:
Please sanitize your input before adding it into queries.

Reducing MSQL Query to a specific session

Using the code below, I was able to display each username and trial 1/0 flag in the table. What I want to do is display the data only for the existing user so I can say something like "Hello USERNAME, you have TRIAL access..." etc...
We're using standard HTACESS as the un/pass to enter the info area.
What needs to change here to only show the existing user's session?
<?PHP
$user_name = "blahblahblah";
$password = "blahblahblah";
$database = "blahblahblah";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM member_auth";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_array($result) ) {
print $db_field['username'] . " : ";
print $db_field['trial'] . " <br> ";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
please don't use mysql_ functions.. look into PDO or MySQLi here: http://www.phptherightway.com/#databases
Update your query to only return specific user results.
Using Form POST:
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
Using URL Parameters:
$username = mysql_real_escape_string($_GET["username"]);
$password = mysql_real_escape_string($_GET["password"]);
So your SQL query will now look like:
$SQL = "SELECT * FROM member_auth WHERE username = '" . $username . "' AND password = '" . $password . "'";

PHP login script always returns "login failed"

I have to give users the ability to log in for an assignment. At first, it seemed to me this script was simple enough to work, but everytime I try to log in with an existing account it gives me the "login failed" message. I don't know where my mistake lies. It's a PostgreSQL database, I'll enclose an image of it below.
<?php
require 'databaseaccess.php';
try {
$conn = new PDO('pgsql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME,DB_PASSWORD);
} catch (PDOException $e) {
print "Error: " . $e->getMessage() . "\n";
phpinfo();
die();
}
$username = $_POST['username'];
$password = $_POST['password'];
$tablename = "users";
// sql-injection counter
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$qry = $conn->prepare("SELECT * FROM $tablename WHERE userid = :username and userpass = :password");
$qry->bindParam(':username', $username, PDO::PARAM_STR, 16);
$qry->bindParam(':password', $password, PDO::PARAM_STR, 16);
$qry->execute();
$result = pg_query($qry);
$count = pg_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if ($count == 1) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
header("location:logingelukt.php");
} elseif ($count = -1) {
echo "there has been an error";
} else{
print $count;
echo "login failed";
}
?>
I have no problems connecting to the database, so that's not an issue, it's just that it always sees $count as something else than zero. Another oddity is that the print $count command doesn't output anything.I use the account I made with postgresql outside of the page, which is just admin:admin. Also, I'm sure the right variables are getting passed from the form.
EDIT: After using var_dump($result), as advised by kingalligator, it seems that $result is indeed NULL, thus empty. I'm gonna try using fetch() instead of pg_query().
I think the issue is that you're mixing PDO and pg_ functions.
Replace:
$result = pg_query($qry);
$count = pg_num_rows($result);
With:
$result = $qry->fetchAll();
$count = count($result);
PDO Function reference can be found here: http://www.php.net/manual/en/class.pdostatement.php
Have you confirmed that you're actually getting data returned from your query? Try this:
var_dump($result);
To ensure that data is being returned from your query. You can still have a successful connection to a database, yet have a query that returns nothing.
You probably should check your column userid at WHERE clause. I don't know the table columns, but is strange that 'userid' has the name of the user in:
"SELECT * FROM $tablename WHERE userid = :username and userpass = :password"
Maybe it is causing the problem.

Categories