mysqli connect and select from database error - php

I recently started using mysqli_ to connect to my database because of the concern of sql injection and lack of security. I'm trying to reconfigure my login page with mysqli from mysql but the page just won't load and I'm not sure why. Thanks in advance for any help.
Here is my code:
<?php
$mysqli = new mysqli("localhost", "username", "password", "db");
if($mysqli->connect_errno > 0){
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
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" .
" FROM users" .
" WHERE email = '".$email."' AND password = '".$password."'")) {
printf("Select returned %d rows.\n", $result->num_rows);
if ($result->num_rows == 1) {
$row = $result->fetch_array(MYSQLI_NUM);
$user_id = $ow['user_id'];
//No more setcookie
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = $email;
}
/* free result set */
$result->close();
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form id="signin_form"
action="<?php echo $_SERVER['PHP_SELF']; ?>"
method="POST">
<div class="signin_box">
<label for="email">Email or Username:</label><br>
<input type="text" name="email" id="email" size="30" />
<br />
<label for="password">Password:</label>
<input type="password" name="password" id="password" size="30" />
<br />
<span class="signin_submit">
<input type="submit" value="Sign In" class="signin_submit" />
</span>
</div>
</form>
</body>
</html>

Here
$email = mysqli->real_escape_string($e);
You forgot $
$email = $mysqli->real_escape_string($e);
and
$password = mysqli->real_escape_string($p);
to
$password = $mysqli->real_escape_string($p);

Related

In PHP how to add a greeting that greets someone after a login with their first name from the sql database?

I have been trying to create a greeting after a user logs in that says "Welcome, first name (dynamic)." so when the user logs in they are greeted with their name. For some reasont it has not been working out. I am new at php so this may be a simple error. Any assist or advice would be useful. Thanks.
main code
session_start();
$mysql_hostname = 'localhost';
$mysql_user = 'username';
$mysql_password = 'password';
$mysql_database = 'db_users2015';
$connect = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die ("Couldn't connect");
echo "<BR>Connection Successful";
//to put data into database
//select database
$db_selected= mysql_select_db($mysql_database, $connect)
or die ("Couldn't connect to the database");
//frontend and backend data processing
$email= $_POST['email'];
$password= $_POST['password'];
//To see if email is registered
$sql = "SELECT COUNT(*) FROM users WHERE email= '{$_POST['email']}'";
$sql_result = mysql_query($sql);
if (mysql_result($sql_result, 0)<1)
{
die("<BR>Email address not found");
}
else{
echo "Login Successful!";
}
//To check if email and password match
$sql = "SELECT count(*) FROM users WHERE email = '$email' AND
password ='$password' LIMIT 1";
$result = mysql_query($sql) or die(mysql_error());
$firstname = $_SESSION['firstname'];
$_SESSION['firstname']= $_POST['firstname'];
if (mysql_result($result, 0) > 0){
echo "<BR>Login Successful, welcome";
echo $_SESSION['firstname'];
}
if (mysql_result($result, 0) < 1){
echo 'wrong password/username combo';
}
?>
<HTML>
<HEAD>
<TITLE> Programming</TITLE>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<LINK REL="stylesheet" TYPE="text/css" href="homework2.css">
</HEAD>
<BODY>
<!-- CSS for http://the7.dream-demo.com/ -->
<div id="container">
<div id="header">
<div class="menuitem"> Home </div>
<div class="menuitem">Products</div>
<div class="menuitem">Case Studies</div>
<div class="menuitem">Pricing</div>
<div class="menuitem">About Us</div>
</div>
<div id="bodycontent">
<div id="banner">
<div id="bannerleft"> <h1> We make you better athletes. Find out how! </h1> </div>
<div id="signin">
<form class="well form-inline" action="login.php" method="post">
<input type="text" class="input-small" placeholder="Email" name="email" >
<input type="password" class="input-small" placeholder="Password" name="password">
<br><br>
<!--
If you do not want to use twitter bootstrap css then you should uncomment next 6 lines and uncomment the
above 2 lines that provide input boxes
<label for="email">Email:</label>
<input type="text" name="email" id="email">
<br>
<label for="password">Password:</label>
<input type="password" name="password" id="password">
<br>
-->
<input type="submit" name="submit" id="logmein" value="Log In">
</form>
</div>
</div>
<div id="featurestrip">
<div id="signup">
<form action="signup.php" method="post">
<label for="firstname">Firstname:</label>
<input type="text" name="signup-firstname" id="signup-firstname">
<br>
<label for="lastname">Lastname:</label>
<input type="text" name="signup-lastname" id="signup-lastname">
<br>
<label for="email">Email: </label>
<input type="text" name="signup-email" id="signup-email">
<br>
<label for="password">Password:</label>
<input type="password" name="signup-password" id="signup-password">
<br>
<label for="password">Reconfirm Password:</label>
<input type="password" name="signup-repassword" id="signup-repassword">
<br><br>
<input type="submit" name="signmeup" id="signmeup" value="Sign Me Up!">
</form>
</div>
<div id="featureright"> <p>Sign up and find out more on how we can help. Pricing starts at $19.95 a month. </p>
<p><h3>Premium service starts at $49.95.</h3></p>
</div>
</div>
<div id="corefeatures">
<img height="200px" src="http://www.hockeymanitoba.ca/wp-content/uploads/2013/02/ltad-model.jpg">
</div>
<div id="testimonials"> Testimonial
<img height="200px" src="http://www.neuroexplosion.com/storage/development%20model%20jpeg.jpg?__SQUARESPACE_CACHEVERSION=1305662626397">
<img height="200px" src="http://www.phecanada.ca/sites/default/files/physical_literacy/LTAD_FMS.jpg">
</div>
<!--
<div id="portfolio"> Portfolio</div>
<div id="skills"> Skills</div>
-->
</div>
<div id="footer">Copyright Notice. All Rights Reserved. 2014</div>
</div>
</BODY>
</HTML>
2nd php code edit
<?php
session_start();
$mysql_hostname = 'localhost';
$mysql_user = 'username';
$mysql_password = 'password';
$mysql_database = 'db_users2015';
$connect = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die ("Couldn't connect");
echo "<BR>Connection Successful";
//to put data into database
//select database
$db_selected= mysql_select_db($mysql_database, $connect)
or die ("Couldn't connect to the database");
//frontend and backend data processing
$email= $_POST['email'];
$password= $_POST['password'];
//To see if email is registered
$sql = "SELECT COUNT(*) FROM users WHERE email= '{$_POST['email']}'";
$sql_result = mysql_query($sql);
if (mysql_result($sql_result, 0)<1)
{
die("<BR>Email address not found");
}
else{
echo "Login Successful!";
}
//To check if email and password match
$sql = "SELECT(*) FROM users WHERE email = '$email' AND
password ='$password' LIMIT 1";
$userdata = mysql_fetch_assoc($result);
$result = mysql_query($sql) or die(mysql_error());
$firstname = $_POST['firstname'];
$_SESSION['firstname]' = $userdata['firstname'];
if (mysql_result($result, 0) > 0){
echo "<BR>Login Successful, welcome";
echo $firstname;
}
if (mysql_result($result, 0) < 1){
echo 'wrong password/username combo';
}
?>
under //To check if email and password match
put this:
$result = mysql_query("SELECT * FROM users WHERE email = '$email' AND
password ='$password' LIMIT 1");
if(mysql_num_rows($result) > 0){
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$firstname = $row["firstname"];
echo "<BR>Login Successful, welcome";
echo $firstname;
}else{
echo 'wrong password/username combo';
}
Problem is Been here
$firstname = $_SESSION['firstname'];
$_SESSION['firstname']= $_POST['firstname'];
You are Trying to get First Name from login page html form. but i don't remember if any login page ever have First name field. so you should get first name from database and put it in $_SESSION['firstname']
Hope to be clear enough. :)
To get data out of database
Change this
SELECT count(*) FROM users WHERE email = '$email' AND password ='$password' LIMIT 1
To This
SELECT * FROM users WHERE email = '$email' AND password ='$password' LIMIT 1
$userdata = mysql_fetch_assoc($result);
$_SESSION['firstname'] = $userdata['firstname'];
This will do the trick
the place where you set your firstname should be changed with this
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$_SESSION['firstname']= $row['firstname'];
set firstname by fetching results from database because $_POST['firstname'] does not exists in your page.
Thanks.

Using SHA1 in PHP for Login form

I'm trying to make a simple register and login form.
I want to use SHA1 to save the encrypted password in database.
But when I try to login with the password, it seems it does not work.
There are three files - index.php, register.php ,login.php
Please help me to solve this problem.
//index.php
<form action="register.php" method="post" enctype="multipart/form-data">
<label for="email">Email:</label>
<input type="text" name="email">
<br />
<label for="password">Password:</label>
<input type="password" name="password">
<button>Register</button>
</form>
<form action="login.php" method="post">
<label for="email">Email:</label>
<input type="text" name="email">
<br />
<label for="password">Password:</label>
<input type="password" name="password">
<button>Login</button>
</form>
//register.php
<?php
$email = $_POST['email'];
$password = $_POST['password'];
$regist_day=date('d-m-Y (H:i)');
if (!empty($email) && !empty($password)) {
require_once('lib/db_connect.php');
$dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME)
or die('Error connecting database');
$sql = "INSERT INTO member(email,password,regist_day)";
$sql .= "VALUES ('$email',SHA1('$password'),'$regist_day')";
mysqli_query($dbc,$sql);
echo("
<script>
location.href='try.php'
</script>
") ;
}
else{
echo "You need to enter Email and Password";
}
?>
//login.php
<?php
$user_email = $_POST['email'];
$user_password = SHA1($_POST['password']);
if (!empty($user_email) && !empty($user_password)) {
require_once('lib/db_connect.php');
$dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME)
or die('Error connecting database');
$sql = "SELECT * FROM member WHERE email = '$user_email'";
$result = mysqli_query($dbc,$sql);
$num_match = mysqli_num_rows($result);
if (!$num_match) {
echo "No result";
}
else{
$sql = "SELECT * FROM member WHERE password = '$user_password' ";
$result = mysqli_query($dbc,$sql);
$password_match = mysqli_num_rows($result);
if (!$password_match) {
echo "SHA1 does not work";
exit;
}
else{
echo"success";
}
}
}
else{
echo "You need to enter both Email and Password";
}
?>

how to check whether old password entered is present or not in db

I m having a login page where user enters id and password.To reset the password i have to check whether the entered password is present or not whether it matches with the id i have entered.How to validate it.I m unable to validate it. If user enters any password it displays the record is updated. How to validate it. Here is the code
login.php
<label type="text" name="id" maxlength="50" size="20">ID</label><br />
<input type="text" name="id" placeholder="ID" class="input" size="20"/><br /></div>
<div class="formItem">
<label type="text" name="uid" maxlength="50" size="20">Password</label><br />
<input type="password" name="uid" placeholder="ID" class="input" size="20"/><br /></div>
<span class="field">(* Required field)</span><br /><br />
<input type="submit" name="login1" value="LOGIN" class="button"><br /><br /><br /><br />
</form>
</div>
</body>
</html>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db = "abc";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
if(isset($_POST['login1']))
{
$id= $_POST['id'];
$uid= $_POST['uid'];
$query= "select * from resume where id='$id'
AND uid='$uid'";
$run= mysql_query($query);
if(mysql_num_rows($run)>0){
echo "<script>window.open('resetp.php','_self')</script>";
}
else {
echo "<script>alert('Login details are incorrect!')</script>";
}
}
?>
resetp.php
<label type="text" name="uid" maxlength="50" size="20">Old Password</label><br />
<input type="text" name="uid" placeholder="id" class="input" size="20"/><br /></div>
<div class="formItem">
<label type="text" name="uid" maxlength="50" size="20">New Password</label><br />
<input type="password" name="pass" placeholder="pass" class="input" size="20"/><br /></div>
<div class="formItem">
<label type="text" name="cpas" maxlength="50" size="20">Confirm Password</label><br />
<input type="password" name="cpas" placeholder="" class="input" size="20"/><br /></div>
<div class="formItem">
<input type="submit" name="login1" value="RESET" class="formButton"><br /><br /><br /><br /></div>
</form>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db = "resume1";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
if(isset($_POST['login1']))
{
$pass= $_POST['pass'];
$uid= $_POST['uid'];
$cpas=$_POST['cpas'];
$query = "Update `resume` SET uid='".$_POST['pass']."' where uid='".$_POST['uid']."'";
$run = mysql_query($query);
if($query)
{
echo "<script>alert('Record updated')</script>";
}
else
{
echo "<script>alert('no')</script>";
}
}
?>
How can i validated it
Try this:
This line
<label type="text" name="uid" maxlength="50" size="20">New Password</label><br />
should be
<label type="text" name="pass" maxlength="50" size="20">New Password</label><br />
I guess couldn't understand your requirement.
Why don't you validate like you are doing in login.php
$query= "select * from resume where id='$id'
AND uid='$uid'";
$run= mysql_query($query);.................
the PHP script should be at the beginning, not at the end of the code. Begin with the <?php .... ?> and then follow the <HTML> ... </HTML> otherwise the result is returned even before the script is processed.
There are a lot of security issues with your code. You can try this.
<?php
require 'db.php';
$username = isset($_POST['username']) ? htmlspecialchars(trim($_POST['username']), ENT_QUOTES, 'UTF-8') : '';
$password = isset($_POST['password']) ? htmlspecialchars($_POST['password'], ENT_QUOTES, 'UTF-8') : '';
$error = array();
$error_found = 0;
if(isset($_POST['submit']) && ($_POST['submit'] == 'Reset'))
{
//check for errors.
//check if username field is empty.
if(empty($username))
{
$error[] = 'Please provide your user-name.';
}
//check if password field is empty.
if(empty($password))
{
$error[] = 'Please provide a password.';
}
//if errors exist, put errors found as true.
if(!empty($error))
{
$error_found = 1;
}
//else no errors are found.
else
{
//proceed to reset.
//connecting to database.
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die('Unable to connect, check your connection parameters. ');
mysql_select_db(MYSQL_DB, $db) or die('Could not select database, check availability. ' . mysql_error($db));
//querying the database. Checking if user-name password combination exists.
$query = 'SELECT username FROM resume WHERE username = "' . mysql_real_escape_string($username, $db) .
'" AND password = PASSWORD("' . mysql_real_escape_string($password, $db) . '")';
$result = mysql_query($query, $db) or die(mysql_error($db));
//checking if result is true.
if(mysql_num_rows($result) > 0)
{
//the result is true and so you can now reset your password.
}
else
{
$error[] = 'The username password combination you provided does not exist.';
$error_found = 1;
}
}
}
//HTML
?>
<!DOCTYPE HTML>
<html>
<head><title> ... </title></head>
<body>
<!--Your html code here -->
<?php
//if errors are found, then errors are shown here.
if($error_found == 1)
{
echo '<fieldset><center>';
echo '<ul>';
foreach($error as $e)
{
echo '<li>' . $e . '</li>';
}
echo '</ul>';
echo '</center></fieldset>';
}
?>
<form action="nameOfThisScript.php" method="POST">
Username:<input id="username" type="text" name="username" required />
Password:<input id="password" type="password" name="password" required />
<button id="Reset" type="submit" name="submit" value="Reset">Reset</button>
</form>
</body>
</html>
create a script named db.php in the same folder as this script and put the code
<?php
define('MYSQL_HOST', 'localhost');
define('MYSQL_USER', 'root');
define('MYSQL_PASSWORD', '');
define('MYSQL_DB', 'resume1');
?>
Hope this helps.

Having trouble authenticating users

I'm having a lot of trouble with the $_SESSION variable. I'm trying to create a way for users to log in and out. I can log a user in but i don't seem to be able to maintain the session when i switch page. When the user correctly logs in they are taken to profile.php. But if i return to index.php the following error is printed:
Notice: Undefined index: login in /Applications/MAMP/htdocs/www/Shared sites/userlogreg/index.php on line 3
I'm quite new to this but from looking on SO and elsewhere i can't seem to figure it out. Any help would be appreciated.
index.php
<?php
session_start();
if ($_SESSION['login'] == 1) {
echo "<h1>Logged in!</h1>";
} else {
echo "<h1>Not logged in</h1><br/>";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Index page</title>
</head>
<body>
<h2>Login</h2>
<form action="login.php" method="POST">
<div>
<label for="emailSignIn">Email:</label>
<input type="email" name="email" placeholder="Email" required="required" />
</div>
<div>
<label for="passwordSignIn">Password:</label>
<input type="password" name="password" placeholder="Password" required="required" />
</div>
<input type="submit" name="submit" value="Sign in" />
</form>
<h2>Register</h2>
<form action="register.php" method="POST">
<div>
<label for="firstnameRegister">First name:</label>
<input type="text" name="firstname" placeholder="First name" required="required" />
</div>
<div>
<label for="lastnameRegister">Last name:</label>
<input type="text" name="lastname" placeholder="Last name" required="required" />
</div>
<div>
<label for="emailRegister">Email:</label>
<input type="email" name="email" placeholder="Email" required="required" />
</div>
<div>
<label for="passwordRegister">Password:</label>
<input type="password" name="password" placeholder="Password" required="required">
</div>
<input type="submit" name="submit" value="Create account" />
</form>
</body>
</html>
login.php
<?php
$email = sanitize_input($_POST['email']); //echo "Sanitized email: ".$email; echo "<br/>";
$password = $_POST['password']; //echo "Inputted password: ".$password; echo "<br/>";
if ((!isset($email)) || (!isset($password))) {
// VISITOR NEEDS TO ENTER AN EMAIL AND PASSWORD
//echo "Data not provided";
} else {
// CONNECT TO MYSQL
$mysql = mysqli_connect("localhost", "root", "root");
if(!$mysql) {
//echo "Cannot connect to PHPMyAdmin.";
exit;
} else {
}
}
// SELECT THE APPROPRIATE DATABASE
$selected = mysqli_select_db($mysql, "languageapp");
if(!$selected) {
//echo "Cannot select database.";
exit;
} else {
}
// GET THE USER'S UNIQUE SALT FROM THE DATABASE
$unique_salt = mysqli_query($mysql, "select uniqueSalt from user where email = '".$email."'");
$row = mysqli_fetch_array($unique_salt);
//echo "Salt: ".$row['uniqueSalt']; echo "<br/>";
// HASH THE PASSWORD
$iterations = 10;
$hashed_password = crypt($password,$row['uniqueSalt']);
for ($i = 0; $i < $iterations; ++$i)
{
$hashed_password = crypt($hashed_password . $password,$row['uniqueSalt']);
}
//echo "Password entered by user: ".$hashed_password; echo "<br/>";
$user_db_password = mysqli_query($mysql, "select password from user where email = '".$email."'");
$row = mysqli_fetch_array($user_db_password);
//echo "User's password: ".$row['password']; echo "<br/>";
// query the database to see if there is a record which matches
$query = "select count(*) from user where email = '".$email."' and password = '".$hashed_password."'";
$result = mysqli_query($mysql, $query);
if(!$result) {
//echo "Cannot run query.";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
if ($count > 0) {
session_start();
$_SESSION['login'] = 1;
$_SESSION['email'] = $email;
$_SESSION['errors'] = "";
header("location:profile.php");
//echo "<h1>Login successful!</h1>";
//echo "<p>Welcome.</p>";
//echo "<p>This page is only visible when the correct details are provided.</p>";
} else {
session_start();
$_SESSION['login'] = '';
header("location:index.php");
//echo "<h1>Login unsuccessful!</h1>";
//echo "<p>The email and password combination entered was not recognized</p>";
}
// CLEAN THE INPUT
function sanitize_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Change this line:
if ($_SESSION['login'] == 1) {
..to this:
if (isset($_SESSION['login']) && $_SESSION['login'] == 1) {
That way, you check if 'login' is set before you access it.

Comparing Value on Submit Vs Database

The "dbcred.php" class
<?php
# pdo_testdb_connect.php - function for connecting to the "test" database
function testdb_connect ()
{
$dbh = new PDO("mysql:host=localhost;dbname=dbname", "root", "");
return ($dbh);
}
?>
PHP
<?php
#connect mysql
require_once "dbcred.php";
$dbh = testdb_connect ();
session_start();
$username = $_POST['regduser'];
$userpass = md5($_POST['regdpass']);
$result = mysql_query("SELECT * FROM Student WHERE regduser= '$username' AND regdpass = '$regdpass'");
if (mysql_num_rows($result)!= 1) { $error = "Login failed";
#include "loginform.php";
} else {
$_SESSION['username'] = "$username";
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
#include "membersection.php";
}
?>
HTML
<form action="inc/check_regUsr.php" method="post" id="userLogon">
<div class="field required">
Username: <input type="text" name="regduser" tabindex="1" /><br />
</div>
<div class="field required">
Password: <input type="text" name="regdpass" tabindex="2" /><br />
</div>
<input type="submit" name="submitUser" />
</form>
When I try to submit valid credentials it says: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in on line 12
Why does it not like this and how can I fix it?
Thank you
$result = mysql_query("SELECT * FROM Student WHERE regduser= '$username' AND regdpass = '$regdpass'");
I don't know how your database class is working. So I will write a general mysql connect code.
mysql_connect($host,$username,$password);
mysql_select_db($db);
No you can execute the query.

Categories