This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have been following this tutorial for building a simple registration / login script.
http://forum.codecall.net/topic/69771-creating-a-simple-yet-secured-loginregistration-with-php5/
I am new with PHP, but I have a lot of experience using C++, so I thought the transitions wouldn't be too hard, I just need to figure out the syntax. I also did a very very quick introduction to mySQL at university, so I thought it would be a lot easier to use mySQL to check for an existing username when the user has registered, though my knowledge isn't too good. I thought something like this would work;
SELECT username
FROM codecalltut
WHERE username = username;
Would this actually work? It is selecting the username from the database codecalltut and then it checks to see if the username being inputted is already a username? Even if this is correct I don't know how to include it in my PHP.
I've tried using
$qry = "SELECT username
FROM codecalltut
WHERE username = username;"
But I just get a syntax error when it moves to the next statement.
<?php
$qry = "SELECT username
FROM codecalltut
WHERE username = username;"
//if register button was clicked.
} else {
$usr = new Users; //create new instance of the class Users
$usr->storeFormValues( $_POST ); //store form values
//if the entered password is match with the confirm password then register him
if( $_POST['password'] == $_POST['conpassword'] ) {
echo $usr->register($_POST);
} else {
//if not then say that he must enter the same password to the confirm box.
echo "Password and Confirm password not match";
}
}
?>
This is the query used to construct the database:
CREATE DATABASE `codecalltut` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `codecalltut`;
CREATE TABLE IF NOT EXISTS `users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varbinary(250) NOT NULL,
PRIMARY KEY (`userID`,`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
This is the HTML code for when the user clicks "Register"
<li class="buttons">
<input type="submit" name="register" value="Register" />
<input type="button" name="cancel" value="Cancel" onclick="location.href='index.php'" />
</li>
Your HTML form for Registration
<form action='' method='POST'>
<input type='text' name='username' />
<input type='password' name='password' />
<input type='password' name='re-password' />
<input type='submit' name='submit' />
</form>
Your PHP code
if($_POST){
if(empty($_POST['username']) && empty($_POST['password']) && empty($_POST['re-password'])) {
echo 'Please enter all fields';
}else {
$username = $_POST['username'];
$password = $_POST['password'];
$re_password = $_POST['re-password'];
if($password !== $re_password){
echo 'Both passwords do not match';
}else {
$db_name =
$db_user =
$db_pass =
$conn = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx',
array( PDO::ATTR_PERSISTENT => true )
);
$stmt = $conn->prepare("SELECT username,password FROM users WHERE username = ? AND password = ?");
$stmt->execute(array($username, $password));
if($stmt->rowCount() === 0 ) {
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$stmt->execute(array($username, $password));
if($stmt->rowCount() ===1){
echo 'Registration complete';
}else {
echo 'Sorry, unknown error: please try again later';
}
}else {
echo 'Sorry, the username '.$username.' already exists';
}
}
}
}
Did you omit the part where you execute the query? All I see is that you're assigning the query to a variable but not executing it.
I see that you're using PDO, so you should NOT concatenate the username you're checking for into the query, as it leaves you open to SQL injection. I'm assuming your database object is called "$con" and your table is codecalltut. Do this:
$qry = "SELECT * FROM codecalltut WHERE username=?";
$stmt = $con->prepare($qry);
$stmt->execute(array($_POST['username']));
$exists = ($stmt->rowCount() === 1) ? true : false;
Remove the last ; :
$qry = "SELECT username
FROM codecalltut
WHERE username = username;";
REMOVE THIS --^ ^----ADD THIS
Followed by what #Nelson said. You should also enclose strings in your query with ' single quotes like this:
$qry = "SELECT username FROM codecalltut WHERE username = 'username' ";
Also, if you are writting inside, any table, row names, which might conflict with the database language itself, make sure to enclose them with backticks (`)
bytheway
A simple login script would work out this way. (hope, you are using PDO or mysqli instead of mysql functions to interact with your database
// set isset(), to validate if form is submited and then
$username = $_POST['username'];
$pass= $_POST['pass'];
Now, the code.
$conn = new PDO('mysql:host=localhost; dbname=***;', 'db-user', 'user-pass');
$stmt = $conn->prepare("SELECT username,password from members WHERE username = ? AND password = ?");
$stmt->execute(array($username, $password));
if($stmt->rowCount() === 1){
echo 'welcome'.$username;
}else {
echo $username.' is not found'
}
Related
I have the following SQL database:
CREATE TABLE IF NOT EXISTS `accounts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
'experience' enum('Beginner', 'Intermediate', 'Advanced) NULL, Default Beginner,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `accounts` (`id`, `username`, `password`, `email`, 'experience') VALUES (1, 'test', '$2y$10$SfhYIDtn.iOuCW7zfoFLuuZHX6lja4lF4XA4JqNmpiH/.P3zB8JCa', 'test#test.com');
And besides this, I also have a registration form that will populate the database with the given values using a registration form.
And the following HTML form which will be the update form:
<div class="card bg-light">
<div class="register">
<h1>Update My Preferences</h1>
<form action="update_preferences.php" method="post" autocomplete="off">
<div class="form-group input-group">
<select name="new_experience" class="form-control">
<option selected="">Change Investment Experience</option>
<option>Beginner</option>
<option>Intermediate</option>
<option>Advanced</option>
</select>
</div>
<!-- form-group end.// -->
<label for="username">
<i class="fas fa-user"></i>
</label>
<input type="text" name="new_username" value="<?=$_SESSION['name']?>" id="username">
<label for="password">
<i class="fas fa-lock"></i>
</label>
<input type="password" name="new_password" placeholder="" value="" id="password">
<label for="email">
<i class="fas fa-envelope"></i>
</label>
<input type="email" name="new_email" value="<?=$email?>" id="email">
<input type="submit" value="Update">
</form>
</div>
</div>
I manage to add the following code for update_preferences.php but then I got stuck with the error "Could not prepare statement!
Fatal error: Call to a member function close() on boolean in /home2/freemark/public_html/update_preferences.php on line 71":
<?php
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phplogindb';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
// If there is an error with the connection, stop the script and display the error.
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data was submitted, isset() function will check if the data exists.
if (!isset($_POST['new_experience'], $_POST['new_username'], $_POST['new_password'], $_POST['new_email'])) {
// Could not get the data that should have been sent.
die ('Please complete the registration form!');
}
// Make sure the submitted registration values are not empty.
if (empty($_POST['new_experience']) || empty($_POST['new_username']) || empty($_POST['new_password']) || empty($_POST['new_email'])) {
// One or more values are empty.
die ('Please complete the registration form');
}
$new_exp_level=$_POST['new_experience'];
$new_username=$_POST['new_username'];
$new_password=$_POST['new_password'];
$new_email=$_POST['new_email'];
// We need to check if the account with that username exists.
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
if (!filter_var($_POST['new_email'], FILTER_VALIDATE_EMAIL)) {
die ('Email is not valid!');
}
if (preg_match('/[A-Za-z0-9]+/', $_POST['new_username']) == 0) {
die ('Username is not valid!');
}
if (strlen($_POST['new_password']) > 20 || strlen($_POST['new_password']) < 5) {
die ('Password must be between 5 and 20 characters long!');
}
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['new_username']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
// Username already exists
echo 'Username exists, please choose another!';
} else {
// Username doesnt exists, insert new account
if ($stmt = $con->prepare('UPDATE accounts SET $new_exp_level = ?, $new_username = ?, $new_password = ?, $new_email = ? WHERE id = ?')) {
// We do not want to expose passwords in our database, so hash the password and use password_verify when a user logs in.
$password = password_hash($_POST['new_password'], PASSWORD_DEFAULT);
$stmt->bind_param('ssss', $_POST['new_username'], $password, $_POST['new_email'], $_POST['new_experience']);
$stmt->execute();
header('Location: login.html');
exit();
echo 'You have successfully registered, you can now login!';
}
else {
// Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.
echo 'Could not prepare statement!';
}
}
$stmt->close();
} else {
// Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.
echo 'Could not prepare statement!';
}
$con->close();
?>
Not sure what you stuck at but query for multiple fields updating looks like this:
$sql = "UPDATE accounts SET field1 = ?, field2 = ?, field3 = ? WHERE id = ?";
// binding values can be done something like
$stmt->bind_param('ssss', $variable1, $variable2, $variable3, $_SESSION['id']);
Also, read this page about password hashing and never store plain passwords.
if(empty($new_password){
is missing a closing bracket
if(empty($new_password) *)*{
since your update your error is here:
else {
// Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.
echo 'Could not prepare statement!';
}
}
$stmt->close(); <-- this is line 71 (after pasting your code into my IDE so i assume it's the full content)
so $stmt does not have a method called 'close'. this should, I think, say $con->close();
really, if an error is point you to an exact line with an exact message, it shouldn't be too difficult to debug
-- update--
Also i just noticed you're not binding enough parameters
UPDATE accounts SET $new_exp_level = ?, $new_username = ?, $new_password = ?, $new_email = ? WHERE id = ? //<-- 5 placeholders
$stmt->bind_param('ssss', $_POST['new_username'], $password, $_POST['new_email'], $_POST['new_experience']); // <-- 4 params
I found this forum thread to make a log-in and registration system, but it doesn't check if password is correct, only username.
This is my log-in page code:
<?php
include('config.php');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$emailusername = mysqli_real_escape_string($obj->conn,$_POST['emailusername']);
$password = mysqli_real_escape_string($obj->conn,$_POST['password']);
$password = md5($password);
$sql="SELECT uid FROM users WHERE username='$emailusername' or email = '$emailusername' and password='$password'";
$result=mysqli_query($obj->conn,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$active=$row['active'];
$count=mysqli_num_rows($result);
// If result matched $username and $username, table row must be 1 row
if($count==1)
{
$_SESSION['login_user'] = $emailusername;
header("location: index.php");
}
else
{
$error="<div style ='color:#c53131'>Your Login Name or Password is invalid</div>";
}
}
?>
</div>
<form class="fl" action="login.php" method="post">
<label>Username:</label><br/>
<input type="text" name="emailusername"/><br />
<br/>
<label>Password:</label><br/>
<input type="password" name="password"/>
<input type="submit" value=" Submit "/><br />
</form>
This is the table I use:
"uid INT(11) PRIMARY KEY AUTO_INCREMENT,".
"username VARCHAR(30) UNIQUE,".
"password VARCHAR(50),".
"name VARCHAR(100),".
"email VARCHAR(70) UNIQUE); ";
I am new to PHP and have no clue how to make it check if password is correct or incorrect. Any suggestions?
Try your query as below :
SELECT uid FROM users
WHERE (username='$emailusername' or email = '$emailusername')
and password='$password'";
CHECK YOUR Query
$sql="SELECT uid FROM users WHERE (username='$emailusername' OR email = '$emailusername') AND(password='$password')";
Please try the bellow query :
SELECT uid
FROM users
WHERE (username='$emailusername' OR email = '$emailusername')
AND password='$password'
Hope this will help you.
The query should be like this.
$sql="SELECT uid FROM users WHERE (username='".$emailusername."' or email = '".$emailusername."') and password='".$password."'";
If you have to use different logical operators, you should add brackets individual evaluation. Moreover, you have to pass username and password as strings.
This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 2 years ago.
This is how my users register for database, but my question is: How can I prevent the database from having copies of the same username, or in other words, how can I prompt to the user that "Your username already exists" if their username exists in the database.
<?php
$error = ""; // error
$GoodJob = "";
//When submit button is pressed, send data.
if(isset($_POST['submit'])){
if (empty($_POST['username']) || empty($_POST['email']) || empty($_POST['password'])) {
$error = "<br>Please insert only letters or numbers.";
}else{
// Define username, firstname, lastname, email and password.
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
// Define database information
$hostnameV = "***";
$usernameV = "***";
$passwordV = "***";
$databaseV = "***";
//connection to the database
$connection = mysql_connect($hostnameV, $usernameV, $passwordV)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseV,$connection)
or die("Could not select company");
// To protect MySQL injection for Security purposes
$username = stripslashes($username);
$firstname = stripslashes($firstname);
$lastname = stripslashes($lastname);
$email = stripslashes($email);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
// SQL query to send information of registerd users
# FORMULA: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
$query = mysql_query("INSERT INTO `company`.`users` (`id`, `username`, `firstname`, `lastname`, `email`, `password`)
VALUES (NULL, '$username', '$firstname', '$lastname', '$email', '$password')", $connection);
//close the connection
mysql_close($connection);
} // end if statement
***
}
?>
<div id="main">
<div id="login">
<h2>REGISTER</h2>
<form action="" method="post">
<input id="name" name="username" placeholder="Pick a username" type="text">
<input id="name" name="email" placeholder="Your email" type="text">
<input id="name" name="firstname" placeholder="firstname" type="text">
<input id="name" name="lastname" placeholder="lastname" type="text">
<input id="password" name="password" placeholder="Create a password" type="password">
<input name="submit" type="submit" value=" REGISTER ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
I would first start by not using the mysql_* functions as they are deprecated and switch to PDO as it works correctly.
To answer your question, you should simply query the database for the username, if it exists, tell the user.
Before the Insert, using PDO and prepared statements.
$stmt = $dbh->prepare('SELECT count(*) FROM user WHERE username = ?');
$stmt->execute(array($username));
$res = $stmt->fetch(PDO::FETCH_NUM);
$exists = array_pop($res);
if ($exists > 0) {
// tell the user it already exists.
} else {
// carry on with your insert.
}
As others have suggested, making the username unique should also be done. I wouldn't write my code to fail though when trying to insert a duplicate username, I would still test if it exists.
So to provide a bit more clarity, in reference to the below comments about using exceptions, here's why I wouldn't write my code to throw an exception if someone enters a username that is already taken. Exceptions, in my opinion, should be exceptions. That means that something exceptional happened. Someone entering a username that is already taken, I consider that to be a normal operation of the application and it should be handled in a normal non-exceptional fashion. If however, someone entered a valid username and between the time that I checked that it was not taken and when I'm running my insert, someone else grabbed that username (in that 2 millisecond timeframe), that would be an exception and I would handle it. To the user, that "exception" would look exactly the same, but in my code it would be handled as an exception.
So that's why I wouldn't just write my code to do an insert that throws an exception when someone enters a username that is already taken. I would check whether it's taken or not and then insert it, throwing an exception if that username was snagged between the time I checked and when it was inserted. I think that's good application design and proper use of exceptions. Others can disagree, but that's how I would do it. Exceptions should be exceptional, not part of the normal course of doing business.
You can set a validation for checking the username is exist or not.
<?php
function checkUserExist($username){
$checkExist = "SELECT username from userTable WHERE username ='" . $username . "'" or die(mysql_error());
mysql_query($checkExist);
if($checkExist > 0){//That means username is existed from the table
return true;
}else{//username isn't exist
return false;
}
}
if(checkUserExist($username)){//function return true
echo "username is already exist, please change.";
}else{
//Insert the user info into db
}
This is an example for checking the username by using function with mysql_query, you can also use PDO to implement it, Cheers!
I'm making a forum in PHP and MySQL (not a real one, just for practicing). and i made a login page. The problem is that for some reason after I'm writing the username and password and sending it, it keeps getting to the point which it gives me the echo of "wrong password or username". Yet every detail is correct (the names of the columns and the tables in my database are exactly the same in this code and the username and password are correct) so I'm guessing it's not the problem. Any help would be appreciated.
<?php
if(!empty($_POST['username'] ) && !empty($_POST['password'])){
require_once 'dbConnect.php';
$user = mysql_query("SELECT `nickname` , `id` FROM `users` WHERE `nickname` =". $_POST['username'] . "AND `password` = " .sha1($_POST['password']));
if($user){
$data = array();
$data = mysql_fetch_assoc($user);
session_start();
$_SESSION['username'] = $data['nickname'];
echo $_SESSION['username'];
}
else {
echo "wrong password or username";
}
}
else {
echo "enter a username and a password";
}
?>
<form action="index.php?page=login" method="post">
<label>username:
<input type="text" name="username" required/>
</label>
<label>password:
<input type="password" name="password" required/>
</label>
<input type="submit" value="login!" />
</form>
the problem is that yout user and password columns are of type text / varchar. In order to produce a correct query, you have to wrap your values in quotes.
For example:
SELECT * FROM users WHERE username='name' AND password='mypassword'
So you have to alter your existing query like this:
$user = mysql_query("SELECT `nickname` , `id` FROM `users` WHERE `nickname` ='". $_POST['username'] . "' AND `password` = '" .sha1($_POST['password']) . "'");
Mind the single quotes around your values.
In addition: The use of mysql_query is deprecated in PHP. Please use the PHP PDO Class. It supports parameter binding. In your case SQL Injection would be possible.
Comments to answer/answer.
There are a few things wrong with your code and here is what I recommend you do.
Start by defining your variables: (placed below require_once 'dbConnect.php';)
$username = $_POST['username'];
$pass = sha1($_POST['password']);
or, for some added security till you switch to prepared statements:
mysql_real_escape_string($_POST['username'])
mysql_real_escape_string(sha1($_POST['password']))
Then, change:
$user = mysql_query("SELECT `nickname` , `id` FROM `users` WHERE `nickname` =". $_POST['username'] . "AND `password` = " .sha1($_POST['password']));
to
$user = mysql_query("SELECT `nickname` , `id` FROM `users` WHERE `nickname` = '".$username."' AND `password` = '".$pass."'");
As it stands, your present code is open to SQL injection. Use mysqli_ with prepared statements, or PDO with prepared statements.
Add error reporting to the top of your file(s) right after your opening <?php tag
error_reporting(E_ALL); ini_set('display_errors', 1); during development.
Also or die(mysql_error()) to mysql_query() to signal any errors found.
You need to wrap the name and password you provided in quotes.
Concatenating the sql query can solve your error.
there is a mistake in your sql statement,you should not use the quotes in field name and wrap username and password provided
$user = mysql_query("SELECT nickname, id FROM users WHERE nickname ='". $_POST['username'] . "' AND password = '" .sha1($_POST['password'])."'");
I am converting to PDO and I'm having a problem converting at the section where it checks to see if the username and email is taken or not.
below is the code:
<?php
session_start();
$host = "localhost";
$username = "root";
$password = "123";
$dbname = "test";
$conn = new PDO("mysql:host=$host;dbname=$dbname",$username,$password);
?>
<?php
if(isset($_POST['register'])){
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$usernamecheck = $conn->query("SELECT `id` FROM `user` WHERE username='$username'");
$emailcheck = $conn->query("SELECT `id` FROM `user` WHERE email='$email'");
if(mysql_num_rows($usernamecheck) > 0){
echo "That username is already taken";
}elseif(mysql_num_rows($emailcheck) > 0){
echo "That e-mail address is already in use";
}
?>
The errors I get are at the two following lines:
if(mysql_num_rows($usernamecheck) > 0){
}elseif(mysql_num_rows($emailcheck) > 0){
Thanks in Advance.
You're using mysql_num_rows() for a PDO query. You can't mix these APIs.
You're also interpolating $_POST variables directly into your SQL, which is a no-no for security. The benefit of using PDO is that you can easily use SQL query parameters instead, which is much easier and more secure.
Here's how I'd code this task:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT COUNT(*) AS count FROM `user` WHERE username=?");
$stmt->execute(array($username));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$username_count = $row["count"];
}
if ($username_count > 0) {
echo "That username is already taken";
}
$stmt = $conn->prepare("SELECT COUNT(*) AS count FROM `user` WHERE email=?");
$stmt->execute(array($email));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$email_count = $row["count"];
}
if ($email_count > 0) {
echo "That email address is already in use";
}
Also keep in mind that even if you check first, you should assume that someday two people may be trying to create the same username simultaneously, and if the code for their respective requests executes in just the wrong sequence, they could both be told the username does not exist, go ahead and INSERT it. So you should define a UNIQUE KEY on the columns that must be unique. Only the first one to INSERT will succeed, the other will get an error. So you must check for errors.
First of all, the entire task is rather pointless. Making a username unique makes no sense. Given email is used to identify a user, the username - or, rather - display name could be anything and allow duplicates, just like it is done right here, on Stack Overflow.
But if you want the username to be unique, obviously it can be done in one query, without any num rows functionality which being essentially useless
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT username, email AS count FROM `user` WHERE username=? OR email=?";
$stmt = $conn->prepare($sql);
$stmt->execute([$username, $email]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($row['username'] === $username) {
$errors[] = "Username is taken";
}
if ($row['email'] === $email) {
$errors[] = "Email is taken";
}
}