I have to develop a administrative system at my work (we usually don't do that, but one client have a very specific need, so we skipped from WordPress to pure PHP, MySQL and HTML5), I'm using PHP and MySQL, but i can't get the stored functions on MySQL working in PHP, I had tested it in phpMyAdmin and it works fine.
All I'm trying to do right now is a login webpage.
My code:
require 'connect.php';
function query($query) {
$connection = connect_db();
$result = mysqli_query($connection,$query);
return $result;
}
function validateUser($email, $password) {
$connection = connect_db();
$query = "SELECT email, password FROM usuario WHERE email =". $email ."AND password =" . $password ."";
$result = mysqli_query($connection,$query);
return $result;
}
function login($email, $password) {
$validate = validateUser($email,$password);
if($validate == 1) {
session_start();
//NOT IMPORTANT
header('Location:http://www.google.com/');
}
} else {
echo 'error';
}
}
Related
I want to be able to connect to my database and have my function search the database for the logged in user and set a cookie, using the users username.
I want to do this using PHP.
I want to do this so that I can call the username whenever I want to display it.
I am very new at php so please bear with me.
Even if there is a link to a post about this, that would be helpful
Edit (This is what I tried so far):
function storeUsername{
$sql = "SELECT username, id FROM users WHERE email = '".escape($email)."' AND active = 1";
$result = query($sql);
if(row_count($result) == 1) {
$row = fetch_array($result);
$username = $row['username'];
{
setcookie('username', $username, time() + 500000);
}
$_SESSION['username'] = $username;
return true;
} else {
return false;
}
return true;
} else {
return false;
}
}
Please can someone help me in guiding me in the correct direction to get this code to work. I have migrated from PHP5.4 to PHP5.5 and I wonder if that might be the reason for the difficulty?
function auth($username, $password) {
// hash password using md5 encryption
$hash_pass = md5($password);
// prepare SQL query
$username = mysqli_real_escape_string($username);
$query = "SELECT * FROM `area51_users` WHERE `user_name`='".$username."'";
if ($result = mysqli_query($Connection, $query) or die (mysqli_error()." (query not executed)")) {
if (mysqli_num_rows ($Connection, $result) > 0) {
// record exits
if ($row = mysqli_fetch_assoc($result) or die (mysqli_error())) {
if ($hash_pass == $row['user_password']) {
// password is valid
// setup sesson
session_start();
$_SESSION['username'] = $username;
$_SESSION['CMS_AUTH'] = "YES";
return true;
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
}
}
Currently I am getting the error "query not executed" from the first if statement.
I am new to PHP and trying to work this all out.
The problem is the scope of $connection (it's not available in your function)
-> Check php variable scope http://php.net/manual/en/language.variables.scope.php
Second your code has many unnecessary things.
You need no if/else or return false, when you use die.
Instead of die you should use Exceptions!
Cleaned up code:
function auth($username, $password)
{
//you need this variable!!!
global $Connection;
// hash password using md5 encryption
$hash_pass = md5($password);
// prepare SQL query
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
$query = "
SELECT
*
FROM `area51_users`
WHERE
`user_name`= '" . $username . "'
AND `user_password` = '" . $password . "'
";
if ($result = mysqli_query($Connection, $query)) {
if (mysqli_num_rows($Connection, $result) > 0) {
// record exits
if ($row = mysqli_fetch_assoc($result))) {
// setup sesson
session_start();
$_SESSION['username'] = $username;
$_SESSION['CMS_AUTH'] = "YES";
return true;
}
}
}
echo mysqli_error($Connection);
return false;
}
You could also enhance your query with prepared statements (safer)
How can I prevent SQL injection in PHP?
So I'm enabling users to create accounts with a username and password. I have managed to encrypt the password when a user creates a new account using:
$hash = password_hash($password, PASSWORD_BCRYPT);
However I'm having trouble with password_verify when logging in, could someone please help me with what I have? I know it's something like this:
password_verify($password, $hash)
But I don't know how to structure it or where to add it in the code. Thanks in advance. This is what I have:
<?php
if (isset($_GET["username"]) && isset($_GET["password"]) ){
$username = $_GET["username"];
$password = $_GET["password"];
$result = login( $username, $password);
echo $result;
}
function makeSqlConnection()
{
$DB_HostName = "";
$DB_Name = "";
$DB_User = "";
$DB_Pass = "";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
return $con;
}
function disconnectSqlConnection($con)
{
mysql_close($con);
}
function login($username, $password)
{
$con = makeSqlConnection();
$sql = "select * from login where username = '$username' and password = '$password';";
$res = mysql_query($sql,$con) or die(mysql_error());
$res1 = mysql_num_rows($res);
disconnectSqlConnection($con);
if ($res1 != 0) {
return 1;
}else{
return 0;
}// end else
}// end of Function
?>
The general practice is as follows:
Fetch password hash from the database where the username = the inputted username.
If rows are found, then there's a user
Now you compare the inputted password against the hash stored in the database.
I'll outline the above flow in some pseudo code for you here:
$query = SELECT password FROM users WHERE username = '$username'
$data = FETCH_THE_DATA($query);
if(password_verify($USER_INPUTTED_PASSWORD, $data['password'])) {
// password is correct
} else {
// password is in-correct
}
Notes
Stop using mysql_* functions. The library is deprecated as it's unreliable and will be removed in future releases of PHP.
You're better off using PDO or MySQLi Prepared Statements
You should always read the manual - password_verify(), it states clearly that you compare the "user inputted password" against the hashed version which is stored in your database.
Since I'm feeling good and sleepy today, I'll write a bunch of codes.
This is an example how to use PDO with prepared statement. You will have to tweak it according to your needs and you have to check if the post/get not empty as well.
I prefer to use POST request for login so this example will use POST request..
This is my user class. Which use placeholders and binding instead of passing the parameters into the query directly. This will give some protections against SQL injection attack.
class User{
private $dbh;
function __construct(){
$this->dbh = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME.';charset=utf8mb4', DB_USER, DB_PASSWORD) or die('db connect error');
}
function create($username, $password){
$status = false;
try{
$stmt = "INSERT INTO login (username, password)
VALUES (?, ?)";
$qry = $this->dbh->prepare($stmt);
$qry->bindParam(1, $username);
$qry->bindParam(2, $password);
$status = $qry->execute();
}catch(PDOException $e){
$e->getMessage();
}
$qry->closeCursor();
return $status;
}
public function getPassword($username){
$status = false;
try{
$stmt = "SELECT * FROM login WHERE username = ? LIMIT 1";
$qry = $this->dbh->prepare($stmt);
$qry->bindParam(1, $username);
$qry->execute();
$status = $qry->fetch(PDO::FETCH_ASSOC);
}catch(PDOException $e){
$e->getMessage();
}
$qry->closeCursor();
return $status;
}
}
This is how to create the user. Note that I don't check if the username already exist. You can either implement it yourself or use unique index on username column provided that the collation is case insensitive.
I have also increased the cost from the default that is 10 and I defined PASSWORD_DEFAULT to be used because I want the PHP engine to always use the strongest available algorithm (currently bcrypt).
function hashPassword($password){
$password = password_hash($password, PASSWORD_DEFAULT,array('cost' => 16));
return $password;
}
$user = new User;
$_POST['password'] = hashPassword($_POST['password']);
if(!$user->create(trim($_POST['username']),$_POST['password'])){
echo 'Failed creating user';
}else{
echo 'User created';
}
This is how to verify the password.
$user = new User;
$getPassword = $user->getPassword(trim($_POST['username']));
if(!$getPassword){
echo 'Error fetching user';
}else{
if(!password_verify($_POST['password'], $getPassword['password'])){
echo 'Login failed';
}else{
echo 'Login successful';
}
}
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
Here is my back end for the login page it first checks the username against the database if the user exists if checks the password against the user in the data base if they match we log in if they don't we don't log in. And that part works fine however if the username does not exist (and I wrote something that is supposed to catch that) I get a blank white page which is not the intended result. Can someone point out where it is that my code is breaking??
<?php
/*
Handles Login Requests
*/
define('DB_HOST', 'localhost');
define('DB_NAME', 'sec_usr');
define('DB_USER', 'sec_usr');
define('DB_PASS', 'n89tzAh2w3Uf4GUu');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASS) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME, $con) or die("Failed to connect to MySQL: " . mysql_error());
/*
$ID=$_POST['user'];
$Password = $_POST['pass'];
*/
function LogIn()
{
session_start();
if(!empty($_POST['user']) && !empty($_POST['pass']))
{
$query = mysql_query("SELECT * FROM username where userName = '$_POST[user]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['userName']))
{
if($row['userPass'] === $_POST['pass'])
{
echo"Success"; /* Works */
}
else
{
echo"Wrong Pass"; /* Works */
}
}
else
{
echo"Wrong User"; /* Does Not Work */
}
}
}
if(isset($_POST['submit']))
{
LogIn();
}
?>
I had added a piece to my question after I had asked the initial question as to how to use the mysqli but my original question which I have reverted the question back to had nothing to do with using mysqli I had figured that if people were telling me to use mysqli I may as well ask those same people how to use it not how to use them together.
As you pointed out yourself on the comments, the problem is in this part:
$row = mysql_fetch_array($query) or die(mysql_error());
The PHP function mysql_fetch_array() returns FALSE if there are no rows found. When the user doesn't exist, the query will return FALSE, and PHP will execute the part after or. The problem is that there is no error for mysql_error() to display, since the query executed successfully, that's why you get an empty page.
To fix it, you could do:
$row = mysql_fetch_array($query);
if($row)
{
if($row['userPass'] === $_POST['pass'])
{
echo "Success";
}
else
{
echo "Wrong Pass";
}
}
else
{
echo "Wrong User";
}
To be on the safe side, in case you don't receive either the user or the pass variable, you can also add an Exception in the previous if:
if(!empty($_POST['user']) && !empty($_POST['pass']))
{
// query the database...
}
else
{
// Code will most likely not reach here.
throw new Exception("Form submitted but user/pass not received.");
}
Also, be aware that mysql_query("SELECT * FROM username where userName = '$_POST[user]'") is open to a SQL injection attack, you must escape the username before using it inside a SQL query. You can read more about it on the mysql_real_escape_string page. Can be done like this (taken from that page):
$query = sprintf("SELECT * FROM username where userName = '%s'",
mysql_real_escape_string($_POST[user])
);
mysql_fetch_array($query);
And last, the Original MySQL API is deprecated as of PHP 5.5.0, it's recommended that you use MySQLi or PDO_MySQL extension.
Instead of using the !empty() check for the query, I'd suggest you use mysql_num_rows() to fetch the number of rows and then check if it is greater than 0.
empty() returns true if the variable is either FALSE or it is not set.
You could try this:
$query = mysql_query("SELECT * FROM username where userName = '$_POST[user]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
$num = mysql_num_rows($row);
if($num)
{
\\username exists.
}
else
{
\\username does not exist.
}
EDIT:
Also, I'd advise you move to mysqli or PDO as they are more secure. Using mysqli won't be very different from mysql except for a few changes but you'd benefit a whole lot more from mysqli than mysql.
mysql v/s mysqli
For starters,
mysql_connect(host, username, password)
mysql_select_db(db)
changes to
mysqli_connect(host, username, password, db)
and
mysql_query(query)
changes to
mysqli_query(connect, query)
So, as you see, there aren't major differences, just minor ones. You could easily shift to mysqli.
Updated code with mysqli
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'sec_usr');
define('DB_USER', 'sec_usr');
define('DB_PASS', 'n89tzAh2w3Uf4GUu');
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die("Failed to connect to MySQL: " . mysqli_error($con));
/*
$ID=$_POST['user'];
$Password = $_POST['pass'];
*/
function LogIn()
{
session_start();
if(!empty($_POST['user']) && !empty($_POST['pass']))
{
$query = mysqli_query($con, "SELECT * FROM username where userName = '$_POST[user]'") or die(mysqli_error($con));
$row = mysqli_fetch_array($con, $query) or die(mysqli_error($con));
$num = mysqli_num_rows($con, $query);
if($num)
{
if($row['userPass'] === $_POST['pass'])
{
echo"Success"; /* Works */
}
else
{
echo"Wrong Pass"; /* Works */
}
}
else
{
echo"Wrong User"; /* Does Not Work */
}
}
}
if(isset($_POST['submit']))
{
LogIn();
}
?>
I'm really new to php and been following a tutorial on youtube by php academy. Basically it's a script(s) that allows for login,registering and a remember me option, the tutorial is 2 years old so I tried to change some of the mysql functions to mysqli but I'm running into some problems..when I enter a username and hit login I get a "mysql_num_rows() expects parameter 1 to be resource, string given in user.php line 9" error and my if statement says "cannot find username try registering" but it should show "exists" because the username I entered is in fact in the database..I'm puzzled, also please forgive me if the script isn't the most secure, I know things should be escaped and such, your help would be appreciated
User.php :
<?php
function user_exists($username)
{
$username=$username;
$query = ("SELECT count(`user_id`) FROM `users` WHERE `username`='$username'");
if(mysql_num_rows($query)===1)
{return true;
} else{
return false;
}
}
?>
login.php
<?php
include ('core/init.php');
if(user_exists('drellen')===true){
echo "exists";
}
if(empty($_POST)===false){
$username=$_POST['username'];
$password=$_POST['password'];
if(empty($username) === true|| empty($password)=== true)
{
echo $error[]="Enter a username and password";
}
else if (user_exists($username)===false)
{
echo $error[]="Cannot find username try registering";
}
}
please note that the init.php has users.php included in it*****
Might have a mixture of the old mysql and the new mysqli functions mixed in, help making it full mysqli would be appreciated
You have not used mysql_query() to run query. How you get number of rows without it.
Note -> You should use mysqli_* functions instead of mysql_*
$query = mysqli_query("SELECT count(`user_id`) FROM `users` WHERE `username`='$username'");
//$row = mysqli_fetch_array($query);
$count = mysqli_num_rows($query);
you can try this
function user_exists($username)
{
$result = mysql_query("SELECT `user_id` FROM `users` WHERE `username`='$username' LIMIT 1 ") or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
return true;
}
else
{
return false;
}
}
Note : mysql_* is deprecated. use mysqli_* or PDO
UPDATE 2:
function user_exists($username)
{
global $your_db_conn;
$sql = "SELECT `user_id` FROM `users` WHERE `username`='$username' LIMIT 1 ";
$result = mysql_query($sql, $your_db_conn) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
return true;
}
else
{
return false;
}
}
Here is a working example
After doing some digging around i found that the most important part in this new function is calling the global $db, and for sanitizing adding the $db, $data as well as in the query. if you look up other basic exampels of using mysqli_query($db, $sql); you will catch onto this quite easily
<?php
$db = mysqli_connect('localhost', 'root', 'password', 'database');
function sanitize($data) {
global $db;
return mysqli_real_escape_string($db, $data);
}
function user_exists($username)
{
global $db;
$username = sanitize($username);
$sql = "SELECT `id` FROM `Users` WHERE `username`='$username' LIMIT 1";
$result = mysqli_query($db, $sql) or die('query');
if($row = mysqli_fetch_assoc($result))
{
return true;
}
else
{
return false;
}
}
?>
<h1>test</h1>
<?php
if (user_exists('admin') === true){
echo "Good news, this exists";
} else {
echo "no good";
}
?>