Making the transition from mysql_ to MySQLi or PDO - php

I have been searching here and Google for how to change all my MYSQL scripts to MYSQLI or PDO starting just from the beginning. The thing is that for some reason I cannot understand because I am inexperienced and I cannot make a simple session work. Here is what I will start doing because I want to learn the new MYSQLi:
I picked the registration form ( I will not use it in public, my site is just for friends and no more people I choose who will be member and I sign em up )
<?php
/* instantiate our class, and select our database automatically */
$sql = mysqli('localhost','user','password','database');
/*
let's assume we've just received a form submission.
so we'll receive the information, and we'll escape it
this step is not necessary, but why not.
*/
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
/* build the query, we'll use an insert this time */
$query = $sql->prepare("INSERT INTO `tablename` VALUES ('?','?','?');");
/*
bind your parameters to your query
in our case, string integer string
*/
$query->bind_param("sis",$name,$age,$email);
/* execute the query, nice and simple */
$query->execute();
?>
This is ok for me easy to understand, now I cannot find a good example of user login, all examples I find are from expert developers and they mostly create so complex scripts that I dont even need it. Already installed many examples ready made and it feels like they are not really good.
What I have been waiting and looking for and searching 1 WEEK 12 hours a day is:
I want the user to simply login and then the script will have something simple like this:
PAGE START
HELLO <PHP ECHO USERNAME> <PHP ECHO AGE> <PHP ECHO ANYTHING FROM DB>
THANKS
<?php
ELSE
IF USER IS NOT LOGGED IN
REDIRECT TO THE PAGE NOTMEMBER.PHP
?>
PAGE END
Why? Because that's the easy and simple way I use to code in MYSQL and all the sites structure is based like this.
Examples or demo sites would also be helpful.
Thanks a lot

I will recommend you to learn PDO(PHP Data Objects) instead of MySQLi cause PDO supports 12 different database drivers while MySQLi only support MySQL Database.
To know the difference between PDO and MySQLi visit-PDO vs. MySQLi: Which Should You Use?
To learn about PDO visit this very nice tutorials-
1.Why you Should be using PHP's PDO for Database Access
2.PHP Database Access: Are You Doing It Correctly?

Your table needs to have a password column as well.
HTML log in form:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="email" />
<input type="text" name="password" />
<input type="submit" name="submit" value="Log in" />
</form>
Catch it in the PHP file:
if(isset($_POST['submit'])) {
$email = $_POST['email'];
$pass = $_POST['password'];
if($email != '' && $pass != '') { //both not empty, proceed
$checkUser = $sql->prepare("SELECT * FROM `users` WHERE `email` = ? AND `pass` = ?");
$checkUser->bind_param('ss', $email, $pass);
$checkUser->execute();
if($checkUser->num_rows() > 0) { //if user exists with given email and pass
$_SESSION['logged-in'] = 1;
}
}
}
Make sure you put session_start(); at the top of each PHP file. Then you simply use
if($_SESSION['logged-in'] == 1) {
echo 'this is for logged in users';
} else {
header("Location: notMember.php");
exit();
}

Related

PHP Instert will not insert into Database

(so to begin I'm a high school student so not the greatest with the lingo so try your best to guide rather than tell if you can) When using insert to put data into my database from the website it appears to work but nothing appears in the database but no error codes.
I am using Mysqli, PHP, and Wampserver to run a local server and the website will not send data to the Database.
<?php
include 'connect.php';
include 'header.php';
?>
Sign Up<br>
<form method="post" action="">
Username: <input type="text" name="user_name"><br>
password: <input type="password" name="user_pass"><br>
password <Check: input type="password" name="user_pass_check"><br>
Email: <input type="text" name="user_email"><br>
<input type="submit" value="Register">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sql = "INSERT INTO users(user_name, user_pass, user_email) VALUES('".mysqli_real_escape_string($con, $_POST['user_name'])."', '".sha1($_POST['user_pass'])."', '".mysqli_real_escape_string($con, $_POST['user_email'])."', NOW(), 0)";
$result = mysqli_query($con, $sql);
if (!$result) {
echo 'Something went wrong';
echo mysqli_error($con);
} else {
echo "you have successfully registered. you can now <a href='signin.php'>sign in</a> and start posting";
}
}
}
include 'footer.php'?>
In my file used for connection
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'seqevents';
$con = new mysqli($host, $user, $pass, $dbname) or die("cannot connect");
session_start();
if (!isset($_SESSION['user_level'])) {
$_SESSION['user_level'] = 0;
}
I receive no error messages and nothing happens on the website it just reloads and gets rid of any input within the text boxes.
First the (likely) problem, then some other important pointers:
When you insert, you insert set 3 columns (user_name,user_pass,user_email) and then load 5 values into it (NOW() and 0) are extra, it has no clue where to place those values.
DO NOT USE MD5. If you're thinking "yeah, but my site isnt very interesting, why cares" read this line again. DO NOT USE MD5. Or sha1:
Never store passwords in clear text or using MD5/SHA1! Only store password hashes. Use PHP's password_hash() and password_verify() . If you're running a PHP version lower than 5.5 (which I really hope you aren't), you can use the password_compat library to get the same functionality. – Dharman
Use prepared statements. mysqli_real_escape_string is a good first step, but not adequite. Prepared statements secure the query for you. Bit more complex, a lot more secure.
I suggest removing $_SERVER['REQUEST_METHOD'] === 'POST'. What if you have two forms on your page? You're stuck. Instead, give your submit button a name like submitRegForm. Then you can do if( isset($_POST['submitRegForm']) )
DO NOT USE MD5 OR SHA1

How to check username and password matches the database values

I'm really sorry if the question looks silly. But I've been trying for days to check my username and password in the database matches what I'm typing in the html page... This is my Login form...
<form method="POST" action="Dashboard/Dashboard.php">
<div class="form-group md-form">
<!--<input type="email" class="form-control" id="email" value="" placeholder="Enter email address">-->
<i class="fa fa-user prefix grey-text"></i>
<input name="username" id="username" type="text" class="form-control" required>
<label for="defaultForm-email">Username</label>
</div>
<div class="form-group md-form">
<!--<input type="password" class="form-control" id="password" value="" placeholder="Enter password">-->
<i class="fa fa-lock prefix grey-text"></i>
<input name="password" id="password" type="password" class="form-control" required>
<label for="defaultForm-pass">Your password</label>
</div>
<div class="text-center">
<button type="reset" class="btn btn-amber btn-sm"><strong>Reset</strong></button>
<input type="submit" name="submit" id="submit" class="btn btn-green btn-sm" value="Sign in">
</div>
</form>
And this is the code(php) I'm using in Dashboard.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$databaseName = "test";
$conn = mysqli_connect($servername, $username, $password, $databaseName);
$un = $_POST['username'];
$pw = $_POST['password'];
print $pass . "_" . $email;
$query = mysqli_query($conn, "SELECT log_username,log_password FROM login WHERE log_username='$un' AND log_password='$pw'");
$result_can = mysqli_query($conn, $query);
while ($row = mysql_fetch_assoc($result_can)) {
$check_username = $row['username'];
$check_password = $row['password'];
}
if ($un == $check_username && $pw == $check_password) {
$message = "ok";
echo "<script type='text/javascript'>alert('$message');</script>";
header("Location: Doctors.php");
} else {
$message = "No";
echo "<script type='text/javascript'>alert('$message');</script>";
header("Location: Doctors.php");
}
?>
I really tried like thousands of times, but couldn't figure out where I went wrong... Can anyone please help me?
I know my code is open to SQL injection, but I don't care about it as this is a example I needed to show to my friends So neglect that part.
Stack Overflow is for "professional and enthusiast programmers." With respect, you've shown us code in your question that isn't even close to being worthy of either name. It's grossly insecure, and if you put it on the public internet, your site will be cracked by cybercriminals.
StackOverflow people don't have much of a sense of humor about bad security code. You get strong reactions to code like yours because, well, Equifax, and Ashley Madison, and Adobe, and all the rest of the places that have been cracked by cybercriminals. Why do we jump on you? Because we don't like cybercriminals and we don't want to make life easy for them. Friends don't let friends do bad password security. Friends don't show friends grossly insecure password-validation code.
What's wrong with your code? You're storing passwords as plain text, and you're vulnerable to SQL injection. I will address the first of these issues.
Fortunately, php has outstanding industry-leading facilities to do password security. Read about them here. http://php.net/manual/en/faq.passwords.php Use them. How do you handle passwords?
When a user registers on your site and first presents a password, you hash it, in your code running on your server, something like this.
$usersPassword = $_POST['password']);
$hash = password_hash( $usersPassword , PASSWORD_DEFAULT );
// you then store the username and the hash in your dbms.
// the column holding the hash should be VARCHAR(255) for future-proofing
// NEVER! store the plain text (unhashed) password in your database
When a user tries to log in, you do a query like this on your server:
SELECT log_password FROM log_user WHERE log_username = TheUsernameGiven
You then put the retrieved password into a variable named $hash.
You then use php's password_verify() function, again on your server, to check whether the password your would-be user just gave you matches the password in your database.
Finally, on your server you check whether the user's password needs to be rehashed, because the method you used previously to hash it has become obsolete.
$usersPassword = $_POST['password']);
$valid = password_verify ( $usersPassword, $hash );
if ( $valid ) {
if ( password_needs_rehash ( $hash, PASSWORD_DEFAULT ) ) {
$newHash = password_hash( $usersPassword, PASSWORD_DEFAULT );
/* UPDATE the user's row in `log_user` to store $newHash */
}
/* log the user in, have fun! */
}
else {
/* tell the would-be user the username/password combo is invalid */
}
This sequence is futureproof, because it can rehash passwords later if the old hashing method gets too easy for cybercreeps to crack. Many user accounts have lifetimes far longer than versions of packages like php.
For credentials like passwords to remain secret, you must use https, not http, to connect between browser and server. Otherwise cybercriminals can intercept the traffic from your user to your server and grab her password. It can be a pain in the xxx neck to rig up an https-enabled server, but it's a critical part of deploying a web application. (Services like Heroku allow you to test your apps with https easily.)
Several problems, some were mentioned by comments above.
Mixing mysql_* vs. mysqli_* API
You call the query with mysqli_query() but you try to fetch results with mysql_fetch_assoc(). You can't mix these different APIs. The mysql_* functions will not use the connection you opened with mysqli_connect(), and vice-versa. Pick one MySQL extension and stick with it.
Hint: Don't use mysql_* at all. It's deprecated, and has been removed from PHP 7.0+
Querying with conditions for both username and password
Just search for the username, and fetch the password. If you search for both, then the search will return zero rows, unless the correct password was used.
You don't want that. You want to avoid putting the plaintext password in the SQL query. Just search on the username, and fetch the stored password and then compare what you fetch to the user input password.
Uninitialized variables
If you fetch zero rows from your query, then $check_username and $check_password are never set. Then you compare those variables in your if statement. Not a fatal error, but bad style.
No password hashing
You appear to be comparing the user input, which I assume is plaintext, directly to what's stored in the database. You're Probably Storing Passwords Incorrectly.
Instead, when you store your password, use password_hash() first.
No query parameters
I know you said you don't care about your SQL injection vulnerability, but this is like being an electrician and saying you don't care that your electrical panel is stuffed with oily rags. Be sure to post your disregard for safety on your LinkedIn profile, so employers know who to avoid.
Recommended implementation
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // enable exceptions
$conn = new mysqli($servername, $mysql_username, $mysql_password, $databaseName);
$log_username = $_POST['username'];
$log_password = $_POST['password'];
$sql = "SELECT log_username, log_password_hash FROM login WHERE log_username=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $log_username);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
if (password_verify($log_password, $row['log_password_hash'])) {
$message = "ok";
// header must be called before any other output
header("Location: Doctors.php");
exit();
}
}
$message = "No";
// header must be called before any other output
header("Location: Doctors.php");
There are several problems here, both in your code and in the thought process. Let's work our way down:
$un = $_POST['username'];
$pw = $_POST['password'];
print $pass . "_" . $email;
That print line should be giving you a warning. The variables $pass and $email do not exist. You should remove that line, unless what you were trying to do is to print $un and $pw instead.
$query = mysqli_query($conn, "SELECT log_username,log_password FROM login WHERE log_username='$un' AND log_password='$pw'");
There's no need to select both the username and password column. If there is a match, they will always be the same as $un and $pw, which you already have. You're only checking whether the username and password are correct or not, so selecting a single column is good enough. Preferably the user id, but only the username will be sufficient.
Keep in mind that -- assuming the query executes successfully -- $query will contain a mysqli_result object.
$result_can = mysqli_query($conn, $query);
This line needs to be removed. You have already executed your query and $query is its result, what you're doing here makes no sense and should be giving you a warning, or perhaps even a fatal error.
while ($row = mysql_fetch_assoc($result_can)) {
$check_username = $row['username'];
$check_password = $row['password'];
}
if ($un == $check_username && $pw == $check_password) {
$message = "ok";
echo "<script type='text/javascript'>alert('$message');</script>";
header("Location: Doctors.php");
} else {
$message = "No";
echo "<script type='text/javascript'>alert('$message');</script>";
header("Location: Doctors.php");
}
You cannot mix mysql_* and mysqli_* functions. Using mysql_fetch_assoc() here should give you a fatal error. You should use mysqli_fetch_assoc() instead (on $query instead of $result_can), however:
Since you're only interested in whether or not there was any result at all, this whole section can be changed to:
if (mysqli_num_rows($query) > 0) {
$message = "ok";
echo "<script type='text/javascript'>alert('$message');</script>";
header("Location: Doctors.php");
} else {
$message = "No";
echo "<script type='text/javascript'>alert('$message');</script>";
header("Location: Doctors.php");
}
This will pose other problems, because you cannot use header() to redirect the user after echo'ing your <script> tag (you will get a "headers already sent" error). If you want the Javascript alert, perform the redirect with Javascript as well. Also, that $message variable is rather useless, you might as well put the message directly into the alert:
if (mysqli_num_rows($query) > 0) {
echo "<script type='text/javascript'>alert('ok'); window.location.href='Doctors.php';</script>";
} else {
echo "<script type='text/javascript'>alert('No'); window.location.href='Doctors.php';</script>";
}
Once you fix all of these issues, you still have some thinking to do.
You should never store passwords in plain text in your database.
You may not care about SQL injection right now, but with your current query I can log in as any valid user (e.g. "admin") by typing their username as admin' AND 1 --, or if I just want access I can use a username of any' OR 1 -- and be logged in as the first user in your table. Look into prepared statements and how they work.
You have no error handling at all. You should add checks to see if the database connection was opened successfully, the query executed properly, the form was posted and the username/password fields were filled in and think about how you want to present a useful error message to the user.
The main lesson here should be: when you're developing and it doesn't work, always check the error logs to see if it contains any hints and turn on PHP's error reporting features so you can see what you did wrong right in your browser.

Cannot POST to my Mysql database using my HTML registration form: UPDATED CODE

so im trying to create a registration form for my website and am using a SQL database using phpmyadmin. I have done a ton of research on how to create the PHP file that will add the User to my database after creating their account. To the best of my knowledge, i have the correct execution and code but when i go to my website, create a user and go to my phpmyadmin to check my database table to see if the user is created..it is not.Below i will include my code for connection php file along with my register.php file. At this point i have no idea as to what is wrong with my code that is not actually POSTing and data to the database after creating an account on my website.
Below is my UPDATED dbconnect.php file which is included in my register.php
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = '******';
/*** mysql password ***/
$password = '******';
try {
function testdb_connect (){
$dbh = new PDO("mysql:host=$hostname;dbname=*******", $username, $password);
return ($dbh);
}
$dbh = testdb_connect();
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Here is the UPDATED PHP section of register.php:
<?php
session_start();
if(isset($_SESSION['User']))
{
header("Location: home.php");
}
include_once 'dbconnect.php';
if(isset($_POST['submit']))
{
$uname = $_POST['uname'];
$email = $_POST['email'];
$upass = $_POST['upass'];
}
$stmt = $dbh->prepare("SELECT COUNT(*) as `emailcount` FROM `User` WHERE email=:email");
$stmt->execute(array("email" => $_POST['email']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row['emailcount'] > 0) {
echo "<script>alert('Email $email already exists in our system. Please try another email')</script>";
}
$stmt = $dbh->prepare("INSERT INTO User(`uname`, `email`, `upass`) VALUES (:uname, :email, :upass)");
$stmt->execute(array("uname" => $_POST['uname'], "email" => $_POST['email'], "upass" => md5($_POST['upass'])));
?>
And here is the UPDATED HTML form which creates the user account and is supposed to POST to my database table:
<form method='post' action='register.php'>
<pre>
<div>
<label>Name : (letters only)*</label>
<input type="text" name="uname" pattern="[A-Za-z]+" title="only letters" required />
</div>
<div>
<label>E-mail : (xyz#zyx.com)*</label>
<input type="email" name="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" title="xyz#something.com" required />
</div>
<div>
<label>password : (at least 6 chars)</label>
<input type="password" name="upass" pattern=".{6,}" title="Six or more characters" required />
</div>
<input type='submit' name='submit' value='Sign Up'>
</pre>
</form>
There's a couple of things here that needs to be altered, let's start with your choice of API.
Mixing APIs and addressing prepared statements
This isn't something you can do in PHP. Your connection uses PDO, while your queries used the old and outdated mysql_* functions. I'd recommend you edit your code to reflect the connection rather than change the connection to the deprecated mysqli_*. You should also use prepared statements.
So instead of the line $run = mysql_query($check_email);, you'd do something like this, which will use the API you chose in your connection-code, and take advantage of prepared statements.
$stmt = $dbh->prepare("SELECT COUNT(*) as `emailcount` FROM `User` WHERE email=:email");
$stmt->execute(array("email" => $_POST['email']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row['emailcount'] > 0) {
echo "<script>alert('Email $email already exists in our system. Please try another email')</script>";
}
And your insertion query would look something like this:
$stmt = $dbh->prepare("INSERT INTO User(`uname`, `email`, `upass`) VALUES (:uname, :email, :pass)");
$stmt->execute(array("uname" => $_POST['uname'], "email" => $_POST['email'], "pass" => md5($_POST['upass'])));
Also note that you used name="upass" in your form, but your PHP used $_POST['pass'], which are different, and they need to be the same.
Calling the function for your connection
In your connection file, you put the PDO object inside a function, which is fine, but you need to call it, either after you require the file, or in the connection file itself.
$dbh = testdb_connect();
EDIT: Per the comments, also discovered another issue with the variable-scope:
You're also facing some issues with variable scope, as you define the variables for your connection outside the function. The function can't see those variables, because they are not defined inside the function, passed as arguments or made global.
I strongly recommend you not use global variables, and instead pass them as arguments or define them inside the function. This example below have been modified to define them inside the function instead.
<?php
// Define a function for the PDO object
function testdb_connect() {
try {
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = '--------';
/*** mysql password ***/
$password = '------';
$dbh = new PDO("mysql:host=$hostname;dbname=databasename", $username, $password);
return $dbh;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
$dbh = testdb_connect(); // call the function, create the connection
?>
The errors you provided in the comments suggests that the object was not created, which should now be fixed with the above code. I also restructured it a bit, putting the try/catch block in a more appropriate place.
Your submit-button
This is mainly why nothing happened. Your submit-button has no name, attribute, but two values instead. Which means that the line if(isset($_POST['submit'])) will never be true, because there is no input-element with that name.
Instead of
<input type='submit' value='submit' value='Sign Up'>
it should look like
<input type='submit' name='submit' value='Sign Up'>
False positives with isset
The line if(isset($_SESSION['User'])!="") would give you a false positive, as an isset() returns a boolean (true/false), which will never be equal to an empty string.
It should be if (isset($_SESSION['User'])) {, which will redirect the user only if he is signed in.
Additional notes
With the changes above, your checks for empty email/password should be slightly changed, as we will no longer need the lines you commented out (as those use the old mysql_real_escape_string() and we'll be using PDO instead, so they are not defined):
if (empty($_POST['uname'])) {
echo "<script>alert('Please Enter Your name')</script>";
exit();
}
if (empty($_POST['email '])) {
echo "<script>alert('Please Enter Your Email')</script>";
exit();
}
Your password-hashing is md5, which is discouraged to use with passwords. You should look into using a function such as password_hash() instead.
Enable error_reporting(E_ALL); when troubleshooting
Additional reading-material
How can I prevent SQL-injection in PHP?
Why shouldn't I use mysql_* functions in PHP?
You need to uncomment this:
$uname = mysql_real_escape_string($_POST['uname']);
$email = mysql_real_escape_string($_POST['email']);
$upass = md5(mysql_real_escape_string($_POST['pass']));
check post value of password field....& update it by $upass = md5(mysql_real_escape_string($_POST['upass']));
possible error apart form commented lines
1: is databasename your database name
2: PHP version > 5.5.0
3: input field has an escaped character and db setting dosnt accept NULL as value
dont use mysql_real_escape_string***
<input type="password" name="upass" pattern=".{6,}" title="Six or more characters" required/>
Since the name of input type password is 'upass', then you should assign 'upass' to your $upass variable. or change the name of input type to 'pass'.
It should be like this after submitting form
$upass = md5(mysql_real_escape_string($_POST['upass']));

Anyone able to help me with this bug in a login form?

So, I have a login form which is having a bit of trouble. It keepsechoing Incorrect password, please try again. whenever I try and access the restricted page. I have had a fiddle on myself, but I have not been able to find out what is wrong. The code is as follows:
<?php
//MySQL Database connect;
include "databaselogin.php";
//Checks if there is a login cookie
if(isset($_COOKIE["ID_my_site"]))
//If there is a cookie, the user is directed to a restricted page
{
$emailaddress = $_COOKIE["ID_my_site"];
$pass = $_COOKIE["Key_my_site"];
$check = mysql_query("SELECT * FROM Users WHERE EmailAddress='$emailaddress'") or die(mysql_error());
while($info = mysql_fetch_array( $check )) {
if ($pass != $info["password1"]) {
}
else {
header("location: restricted.php");
}
}
}
if (isset($_POST["submit"])) { //If the form has been submitted
//Make sure they filled it all in
if(!$_POST["emailaddress"] | !$_POST["password1"]) {
echo("You did not fill in all the required fields.");
}
//Checks it against the database
if (!get_magic_quotes_gpc()) {
$_POST["emailaddress"] = addslashes($_POST["emailaddress"]);
}
$check = mysql_query("SELECT * FROM Users WHERE EmailAddress = '".$_POST["emailaddress"]."'") or die(mysql_error());
//Gives a message if the user doesn't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
echo ("The Email Address that you have entered is not in use, <a href='register.php'>click here</a> to register");
}
while($info = mysql_fetch_array( $check )) {
$_POST["password1"] = stripslashes($_POST["password1"]);
$info["Password"] = stripslashes($info["Password"]);
$_POST["password1"] = sha1($_POST["password1"]);
//Gives an error is the password is wrong
if ($_POST["password1"] != $info["Password"]) {
echo("Incorrect password, please try again.");
}
else {
//If the login is ok, a cookie is added
$_POST["EmailAddress"] = stripslashes($_POST["EmailAddress"]);
$hour = time() + 3600;
setcookie(ID_my_site, $_POST["emailaddress"], $hour);
setcookie(Key_my_site, $_POST["password1"], $hour);
//Then they are redirected to a restricted area
header("location: restricted.php");
}
}
}
else {
//If they are not logged in
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Login</h1></td></tr>
<tr><td>Email Address:</td><td>
<input type="text" name="emailaddress" maxlength="40" placeholder="Email Address">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password1" maxlength="12" Placeholder="Password">
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
<?php
}
?>
All help will be massively appreciated.
There are a couple of issues. First, mysql_query is a deprecated PHP function and should be replaced with mysqli_query. All functions in your code should use the mysqli prefix instead of mysql (so mysql_fetch_assoc should be changed to mysqli_fetch_assoc). This function also takes a parameter providing a connection to the database, which is done with mysqli_connect. So your code should have something like this:
$con = mysqli_connect($username, $password, $host, $db); // Fill in the variables with correct values
$check = mysqli_query($con, "SELECT * FROM Users WHERE EmailAddress='$emailaddress'");
$con only needs to be set once and can be used in other query calls in your code.
First of all the way you store your credentials in cookies is very dangerous. Anyone who has access to your computer or to your network if you're not using ssl can steal your cookies and log in to your account.
Secondly your problem lies in
while($info = mysql_fetch_array( $check )) {
this is an infinite loop. you should only call this once.
Your overall code could use some improvements such as:
update mysql to mysqli or PDO
use prepared statements
optimize code for speed (use || instead of |)
use a stronger hashing algorithm
Leave a comment if you want a more in depth instruction to improve your code
Hope this helped
Improvements
this is a great article about PDO. But PDO is object based and since you're new to PHP and i don't know your skill level you can better use mysqli for now. There're plenty of articles available on how you can do this.
PDO
in your code you use
if(!$_POST["emailaddress"] | !$_POST["password1"]) {
but if you use || instead of | the if condition skips the second argument if the first already failed.
You use sha1 for hashing your passwords. But this algorithm is a bad practice. You should use Bcrypt or at least use an individual salt for each password you encrypt with sha1 and store that next to the password in the database
SHA1 not safe anymore
You never store the user info in a session to retain the login on next requests, the way you're implementing it is called a remember me function and is considered hard to implement safely. it is easier to work with sessions first and if you really need it cookies later.
If you're using sessions you should also check if the session_id hasn't been set by an attacker in the clients browser. You can do this by setting a random cookie such as init
and when this is not set you call
session_regenerate_id();
You store both the email and the hashed password in a cookie. this can be very dangerous. You shouldn't store the password even if it is hashed in an cookie. The best practice is to hash a randomly created string of characters with a high entropy and store only that in the cookie and in the database. When the user logged in once with that cookie you should refresh the cookie with a new hash.
To fix your error you should remove the while loop around the mysql_fetch_array($check)
Tips for in the future
Your code looks a lot more organized if you start to learn to work with PHP objects. This can also make your project a lot easier to work with.
I don't know if you're going to use this code in a production website because I highly recommend against that. You can better use a safe and sound solution that somebody with more experience has created and when you have more experience you can start building your own.

Trouble getting a login with PHP to take input

***the question has been answered. Here is the solution:
Ok, so I need to address a few things before answering the problem. First, the database is meant to have the numerous security flaws. This is a security class, and I am trying to hack into it on purpose. Then after I hack in, i'm supposed to prevent my own attacks.
Second thing I wish to clear up, is that this is a local database only, and never used by anyone but myself, classmates and instructor.
now for the answer: The first thing I was doing wrong was that the code was supposed to be logged into from the localhost webpage. I was trying to log in from the login.php file.
Second thing, was that I was mixing my mysql * and mysqli * methods. You cannot have multiple versions of the same method in the code.
Thanks to all who posted and for the fast responses.
A brief explanation of the problem:
I have been coding a database for a school project. I have the school database set up correctly, as per the instructor's review. The code I have is supposed to take a user input, check it with a "enrolled" list of students and compare the student ID and passsword to a pre-existing list.
After the check, the code is to start a session based on the student being enrolled. If the student is not enrolled it redirects them to the login page again.
The trouble I am having is that the code simply doesn't work. I get a error that says I have an issue on line 35 of my login.php file. Here is my code:
<?php
//Connect to DB
$con=mysql_connect("localhost","root","cravenreach","univ");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "Succeed to connect to MySQL. ";
}
//Session setup
session_start();
if( isset($_POST['sid']) && isset($_POST['password']))
{
$checklogin = mysql_query($con, "SELECT * FROM students WHERE sid=".$_POST['sid']." AND password=".$_POST['password']);
echo $count1 = mysql_num_rows($checklogin);
if($count1==1)
{
// auth okay, setup session
$_SESSION['sid'] = $_POST['sid'];
// redirect to required page
header( "Location: main.php" );
}
else {
// didn't auth go back to login
header( "Location: login.php" );
}
}
else {
// username and password not given so go back to login
//header( "Location: login.php" );
//This code is broken, causes a redirect loop.
echo "failure to start";
//header( "location: .php");
}
?>
here is the index.php code:
<html>
<body>
<form action="login.php" method="post">
<p><label>Student ID: <input type="text" name="sid"></label></p>
<p><label> Password: <input type="password" name="password"></label></p>
<input type="submit">
<input type="reset" value="Clear">
</form>
</body>
</html>
The error I receive is this: "Succeed to connect to MySQL. failure to start."
I understand that the code is not evaluating the login as true, and is skipping down to the last else statement. I just dont understand why.
To recap: My code will not actually accept the correct student input (or incorrect for that matter) and will not allow the user to login. It simply throws an error. My question is: what is wrong with my code? Is my query wrong, or implementation of the session?
You need to replace mysql_* functions into mysqli_* and also, You need add " end of the query before )
$checklogin = mysqli_query($con, "SELECT * FROM students WHERE sid='".mysqli_real_escape_string($_POST['sid'])."' AND password='".mysqli_real_escape_string($_POST['password'])."' ");
Your query should be like
//Prevnt from SQL injection
$sid = mysql_real_escape_string($_POST['sid']);
$password = mysql_real_escape_string($_POST['password']);
checklogin = mysql_query("SELECT * FROM students WHERE sid='$sid' AND password='$password'",$con);
Note MySQL is deprecated use MySQLi or PDO

Categories