php login form not working correctly - php

I'm trying to create a simple login functionality but it's not working, and I'm relatively new to mysqli so please bear with me. I just want to check if the email address and password are correct and if they are then log the user in. Thanks in advance.
Here is my login code that checks the credentials:
UPDATED CODE - I added the report all and I'm now getting internal server error
<?php
require_once 'connect.php';
mysqli_report(MYSQLI_REPORT_ALL);
session_start();
if (!isset($_SESSION['email'])) {
$e = trim($_REQUEST['email']);
$email = $mysqli->real_escape_string($e);
$p = trim($_REQUEST['password']);
$password = $mysqli->real_escape_string($p);
/*
if ($result = $mysqli->query("SELECT email, password, user_id" .
" FROM users" .
" WHERE email = '$email' AND password = '$password'")) {
printf("Select returned %d rows.\n", $result->num_rows);
echo 'Total results: ' . $result->num_rows;
}
*/
if ($stmt = $mysqli->prepare("SELECT email, password, user_id FROM users WHERE email=? AND password=?")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $email, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($email, $password);
/* fetch value */
$stmt->fetch();
if ($stmt->num_rows==1) {
$row = $stmt->fetch_assoc(MYSQLI_NUM);
$user_id = $row['user_id'];
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = $email;
header("Location: home.php");
/* close statement */
$stmt->close();
} else {
printf("Error message: %s\n", $mysqli->error);
}
/*
if ($result->num_rows==1) {
$row = $result->fetch_assoc(MYSQLI_NUM);
$user_id = $row['user_id'];
if ($query_group = $mysqli->query("SELECT *" .
" FROM user_groups" .
" WHERE user_id = '".$user_id."'")) {
//No more setcookie
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = $email;
} else {
echo 'Did not work';
}
}
*/
/* free result set */
// $result->close();
}
}
?>
And here is connect.php to connect to the database:
<?php
$mysqli = new mysqli("data", "username", "password", "db");
if($mysqli->connect_errno > 0){
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
?>

did you try to remove one of the brackets in the end of ypur code. I guess you have to remove one of them.

Related

My Webpage doesn't recognize the data fulfilled in a registration form

I'm currently doing a webpage, and by now I'm focused on the log in and registration forms. I have also a sql database connected. When I register a new user with the registration form, the database is updated succesfully. The problem is that when I try to log in with that user, the page doesn't recognize it. Besides, if I try to log in with an user that I introduced manually with Netbeans, it recognize it.
$con = mysqli_connect("localhost", "root", "mypassword");
if(!$con) {
exit('Connect Error (' . mysqli_connect_errno() .') ' . mysqli_connect_error());
}
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($con, "my_database");
$user = mysqli_real_escape_string($con, htmlentities($_POST['new_mail']));
$password = mysqli_real_escape_string($con, htmlentities($_POST['new_passwd']));
$sql = "INSERT INTO usuarios (usuario, clave) VALUES ('". $user ."' , ' ".md5($password)."')";
mysqli_query($con, $sql);
if(mysqli_affected_rows($con) > 0) {
?>
<script type='text/javascript'>
alert('You have been registered succesfully. Now you can access our website');
</script>
<?php
header("Location: login_page.html");
echo "<br><br><a href='index.php'>Go back</a>";
} else {
if(mysqli_errno($con) == 1062) {
echo "The e-mail address introduced is already on the system.";
echo "<br><a href='register.html'>Try again</a>";
} else {
echo "Error: " .$sql . "<br>" . mysqli_error($con);
}
}
That's the code I use after fulfilling the registration form. The next one is the one I use after the log in form.
$con = mysqli_connect("localhost", "root", "mypassword");
if(!$con) {
exit('Connect Error (' . mysqli_connect_errno() .') ' . mysqli_connect_error());
}
if(mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_errno());
exit();
}
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($con, "my_database");
$user = mysqli_real_escape_string($con, htmlentities($_POST['username']));
$password = mysqli_real_escape_string($con, htmlentities($_POST['password']));
$sql = "SELECT * FROM usuarios WHERE usuario='" . $user ."' AND clave='" . md5($password) . "'";
mysqli_query($con, $sql);
if(mysqli_affected_rows($con) > 0) {
//echo "Welcome " . $_SESSION['username'] . "!";
//echo "<br><br><a href='user_page.php'>Main Page</a>";
//echo "<br><a href= 'close_session.php'>Close Session</a>";
header("Location: main_page.html");
} else {
exit ("The user or password introduced are not correct");
}
$row = mysqli_fetch_row($sql);
$_SESSION['user'] = $row;
$_SESSION['username'] = $row[0];
mysqli_free_result($sql);
?>
Thank you for your help.
Few mistakes that you are doing on your registration page.
You are not using prepared statements.
You are using md5() instead of password_hash() and password_verify() to secure your passwords.
You are using cleansing mechanism on the password which you should't as this may change the original password.
With the above you should use prepared statements and take the advantage of password hash and verify,
therefore your register page. should look :
<?php
$con = mysqli_connect("localhost", "root", "mypassword");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($con, "my_database");
$user = $_POST['new_mail'];
$password = $_POST['new_passwd'];
$hash = password_hash($password, PASSWORD_DEFAULT);
//check if user is not registered already, I'm not sure if you have user_id, what I know you should have id which is auto increment, then select that id
$sql = "SELECT user_id FROM usuarios WHERE usuario = ? ";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 's', $user);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
//user exists
echo "The e-mail address introduced is already on the system.";
echo "<br><a href='register.html'>Try again</a>";
} else {
//user does not exist register the user
$query = "INSERT INTO usuarios (usuario, clave) VALUES (?,?)";
$insert = mysqli_prepare($con, $query);
mysqli_stmt_bind_param($insert, "ss", $user, $hash);
if (mysqli_stmt_execute($insert)):
?>
<script type='text/javascript'>
alert('You have been registered succesfully. Now you can access our website');
</script>
<?php
header("Location: login_page.html");
echo "<br><br><a href='index.php'>Go back</a>";
else:
printf("Error: %s.\n", mysqli_stmt_error($insert));
endif;
}
?>
Then login
<?php
session_start();
$con = mysqli_connect("localhost", "root", "mypassword");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_errno());
exit();
}
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($con, "my_database");
$user = $_POST['username'];
$password = $_POST['password'];
#ONLY SELECT THE SPECIFIC COLUMNS YOU NEED, DON'T USE#
$sql = "SELECT clave,anotherColumn,anotherColumn FROM usuarios WHERE usuario= ? ";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 's', $login);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$row = $row = mysqli_fetch_assoc($result);
if (password_verify($password, $row['clave'])) {
//passwords set sections, redirec
} else {
//user password does not match the stored hash return message
}
} else {
//username does not exist, do something
}
?>

Selecting multiple data from a database through PHP

I have a search form that is able to retrieve the username of a user, however I can't figure out how to get it to return more than that, I want it to display the first names and last names too.
Below is the code at the minute that works, but when I try and add in more variables, for example if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?")) then it doesn't return anything at all and asks to insert a search query.
I have also tried if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE %?%")) and LIKE "%?%")), but no results.
search.php
<?php
include 'connection.php';
if(isset($_POST['searchsubmit']))
{
include 'searchform.php';
$name=$_POST['name'];
if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?"))
{
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($personresult);
$stmt->fetch();
?>
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2>
<BR>
<?php
print_r($personresult);
?>
</center>
<?php
}
else
{
echo "<p>Please enter a search query</p>";
}
}
else
{
echo "NOT SET!";
}
You are only calling Username .. You need to be calling *
SELECT * FROM users WHERE Username LIKE ?
This is my personal script I use:
<?php
$dbservername = "localhost";
$dbusername = "db_user";
$dbpassword = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!empty($_POST["username"])) {
$username = $_POST["username"];
}
if (!empty($_POST["password"])) {
$password = $_POST["password"];
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row["Username"] . " " . $row["Firstname"] . " " . $row["Lastname"] . "<br>";
if ($row["Username"] == $username && $row["Password"] == $password) {
echo "success";
// do more stuff here like set session etc
} else {
$echo "incorrect username and/or password";
}
}
}
?>
Are you initializing the statement object with mysqli_stmt_init?
See mysqli_stmt_init and mysqli-stmt.prepare
If the database server cannot successfully prepare the statement,
PDO::prepare() returns FALSE or emits PDOException (depending on error
handling)
add this line in connection.php right after creating connection object:
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
At least, you can trace possible errors
<?php
include 'connection.php';
if( isset( $_POST['searchsubmit'] ) ) {
include 'searchform.php';
$name=$_POST['name'];
if ( $stmt = $connection->prepare ("SELECT `Username`,`firstname`,`lastname` FROM `users` WHERE `Username` LIKE ?") ) {
/* not 100% sure about whether this is required here like this or not but usually a like expression uses '%' as a wildcard */
$var='%'.$name'.%';
$stmt->bind_param('s', $var );
$res=$stmt->execute();
/* 3 columns selected in query, 3 columns bound in results */
$stmt->bind_result( $personresult, $firstname, $lastname );
if( $res ){
$stmt->fetch();
echo "
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2><!-- 3 columns/variables -->
{$personresult},{$firstname},{$lastname}
<BR>
</center>";
}
} else {
echo "<p>Please enter a search query</p>";
}
} else {
echo "NOT SET!";
}
$stmt->close();
$connection->close();
?>

Not checking for User if existing

I want to check if a user exists or not.
It keeps registering users even though I added a check inside. The echo does not give me a accurate feedback on how to fix this issue.
Edit:
Code edited due to comments. It does not exit or check for the existing user.
Here is my code:
if($_POST['username']) {
if ( $password == $c_password ) {
$db_name = '*';
$db_user = '*';
$db_password = '*';
$server_url = '*';
$mysqli = new mysqli($server_url , $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
$check="SELECT * FROM USER WHERE 'Name'='". $username."'";
$rs = mysqli_query($mysqli,$check) or die(mysqli_error($mysqli));
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {
echo "User Already in Exists<br/>";
exit;
}
else
{
$stmt = $mysqli->prepare("INSERT INTO USER (Name, Password) VALUES (?, ?)");
$password = md5($password);
$stmt->bind_param('ss', $username, $password);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
error_log("Success: $success");
if ($success > 0) {
error_log("User '$username' created.");
echo '{"success":1}';
} else {
echo '{"success":0,"error_message":"Username Exist."}';
}}
}
} else {
echo '{"success":0,"error_message":"Passwords does not match."}';
}
} else {
echo '{"success":0,"error_message":"Invalid Username."}';
}

PHP to mySQL check if user exists

I have a script that updates/creates user from an iOS device. Now i want to have the script also check if the user already exists in the database. I am going to restrict this to username for now, so no more than ONE unique username may exist. I have an if-statement in my PHP but i cannot get it to work - help please :).
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = 'dbname';
$db_user = 'dbuser';
$db_password = 'dbpass';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
$userexists = mysql_query("SELECT * FROM users WHERE username='$username'");
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
}
if(mysql_num_rows($userexists) != 0) {
echo '{"success":0,"error_message":"Username Exist."}';
}
else {
$stmt = $mysqli->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
$password = md5($password);
$stmt->bind_param('sss', $username, $password, $email);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
error_log("Success: $success");
if ($success > 0) {
error_log("User '$username' created.");
echo '{"success":1}';
}
else {
echo '{"success":0,"error_message":"Username Exist."}';
}
}
}
else {
echo '{"success":0,"error_message":"Passwords does not match."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Username."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
You could SELECTthe table before trying to insert username. If it already exists (= you have a result) you dont simply insert.
Better yet, use ON DUPLICATE IGNORE or something like that.

Cannot update database

<?php
session_start();
if (isset($_POST['userid']) && isset($_POST['password']))
{
// if the user has just tried to log in
$userid = $_POST['userid'];
$password = $_POST['password'];
$db_conn = new mysqli('localhost', 'user', 'passwd', 'dbname');
if (mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
}
$query = 'select * from users '
."where userid like'$userid' "
." and password like sha1('$password')";
$result = $db_conn->query($query);
if ($result->num_rows >0 )
{
// if they are in the database register the user id
$_SESSION['valid_user'] = $userid;
}
$db_conn->close();
}
?>
<?
$db_conn = new mysqli('localhost', 'user', 'passwd', 'dbname');
if (mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
}
if (isset($_POST['submit'])) {
if (empty($_POST['name']) || empty ($_POST['dob']) || empty ($_POST['contact'])|| empty ($_POST['address'])|| empty ($_POST['email'])) {
echo "All records to be filled in";
exit;}
}
$name = $_POST['name'];
$dob = $_POST['dob'];
$contact = $_POST['contact'];
$address = $_POST['address'];
$email = $_POST['email'];
$userid = $_SESSION['valid_user'];
$sql = "UPDATE users SET name=$name, dob=$dob, contact=$contact, address=$address, email=$email
WHERE userid ='$userid'";
$result = $db_conn->query($sql);
if (!$result)
echo "Your query failed.";
else
echo "User Information Updated ";
?>
<meta http-equiv="refresh" content="5;URL=members.php" />
I got your query failed when I run it. Anyone have any clue why my database dont get updated?
I'm pretty sure my sql works. Is there any mistake in my coding?
Your query is okay, except that you're not using prepared statements.
The issue lies in your variables. echo them and see what's in them.
Since we don't have access to your database it's hard for us to verify if something else might be wrong with your query. You could for example create an SQL Fiddle.
Something else you should read up on: SQL Injection
Prepared statements look like this:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Looks like your exist statement is wrong..
if (isset($_POST['submit']))
{
if (empty($_POST['name']) || empty ($_POST['dob']) || empty ($_POST['contact'])|| empty ($_POST['address'])|| empty ($_POST['email']))
{
echo "All records to be filled in";
**exit**;
}
}

Categories