im new at programing and php, and i want to create an error on my registration system that when the user creates an account with the same username already existing in the database it says something like this: "Username already in use" and then if it isnt an existing username it says "Registation Complete"
I tried this code:
<?
require ("conect.php");
$user = $_POST['user'];
$pass = $_POST['password'];
$email = $_POST['email'];
$email_check = $_POST['email_check'];
$register = mysql_fetch_array;
if($user = $register[user]) {
echo"Username already in use";
}
else
{
$insert = mysql_query("INSERT INTO registration (user, password, email)
VALUES('$_POST[user]','$_POST[password]','$_POST[email]')");
echo "The account $user was successfully created.";
}
?>
But it didnt work, can someone help please
As pointed out by the other users, you should be using prepared statements through PDO (or mysqli, but I definitely prefer PDO)
You're storing the POSTS in variables, but then in the database query you are just using the $_POST variable again?
I'm not sure what your doing with the $register = mysql_fetch_array part, but to get the desired functionality you should use a select query to count the number of users using the username.
You're not using any secure hash format to store the password. I switched it to use password_hash().
Try something like this (I haven't tested the code yet though, so there might be errors):
<?php
//Put all POSTS in variables
$user = $_POST['user'];
$pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
$email = $_POST['email'];
$email_check = $_POST['email_check'];
//Database config- probably should store in a separate file
$database_host = "";
$database_name = "";
$database_user = "";
$database_password = "";
$conn = new PDO("mysql:host=$database_host;dbname=$database_name",$database_user,$database_password);
//Find out if the username is taken.
$sql = "SELECT count(*) FROM `registration` WHERE user = :user";
$q = $conn->prepare($sql);
$q->execute(array(':user' => $user));
$number_of_rows = $q->fetchColumn();
//Clear $sql and $q so you can use them again
$sql = NULL;
$q = NULL;
if ($number_of_rows > 1) {
//Username already taken
echo "Username already taken";
}
else {
$sql = "INSERT INTO registration (user,password,email) VALUES (:user,:password,:email)";
$q = $conn->prepare($sql);
$q->execute(array(':user'=>$user, ':password'=>$password, ':email'=>$email));
echo "The account " . $user . " was successfully created";
}
?>
You really, really need to read about prepared statements. The method you are using is very old, incredibly insecure, and generally a bad-practice by today's standards.
Your code isn't even worth fixing for these reasons, it should be re-written using prepared statements.
Related
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' password='$2y$10$QV6'' at line 1
I'm fairly new to server-side scripting, please take a look at the syntax below and align it where neccesary or assist me with an alternative solution regarding this error.
<?php
$tbl_name = "user_accounts"; // Table name
// Connect to server and select database.
$mysqli = new mysqli("localhost", "root", "", "ems");
// email and password sent from form
$email = $_POST['email'];
$password = $_POST['password'];
if (!$_POST['email'] | !$_POST['password']) {
print "<script>alert('Your email & password do not match!');
javascript:history.go(-1);</script>";
exit;
}
// To protect MySQL injection
$email = stripslashes($email);
$password = stripslashes($password);
$email = mysqli_real_escape_string($mysqli, $email);
$password = mysqli_real_escape_string($mysqli, $password);
$hash = password_hash($password, PASSWORD_BCRYPT);
$sql = "SELECT account_type, email and password FROM $tbl_name WHERE email='$email', password='$hash'";
$mysqli_result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
// Mysql_num_row is counting table row
$count = mysqli_num_rows($mysqli_result);
// If result matched $email and $password, table row must be 1 row
if ($count == 1) {
// Register $email, $password and redirect to file "index.php"
$_session['email'] = $email;
$_session['password'] = $password;
//Checking User Account Type
if ($_SESSION['account_type'] == 'user') {
header("location:user.php");
} else if ($_SESSION['account_type'] == 'admin') {
header("location:admin.php");
} else {
print "<script>alert('This Account Doesn't Exist!');
javascript:history.go(-1);</script>";
exit;
}
} else {
echo "Wrong email or Password";
}
?>
A few problems here:
You do not separate conditions using a comma, instead you use AND
You cannot check a password hash like that as it will be different every time as the salt is generated dynamically. Instead you should get the password from the row and use the password compare function password_verify().
You should use a prepared statement instead of escaping your input to avoid sql injection.
password_hash generates every time a new hash, even with the same value.
Your Query should only query for the email and then execute password_verify($password, $passwordFromQuery).
More about password_hash() here and about password_verify() here
I woud recommend using prepared statements. Read more about it here
Try this
$sql="SELECT account_type, email and password FROM $tbl_name WHERE email='".$email."', password='".$hash."'";
$mysqli_result=mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
As I was changing my MySQLi to PDO, I encountered an error when fetching hashed strings from my users table.
This was the code I used before:
CheckPassword VERIFIES VALID USING MYSQLI
$mysqli = new mysqli("localhost","_USER_","_PASS_","_DB_");
$username = '_USERNAME_';
$pass = '_PASSWORD_';
$sql = "SELECT * FROM `users` WHERE username='$username' LIMIT 1";
$result = $mysqli->query($sql);
if($assoc = $result->fetch_assoc()){
$db_pass = $assoc['userpass'];
require 'PasswordHash.php';
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
if($hasher->CheckPassword($pass, $db_pass)) {
echo "valid"; // VERIFIES VALID
} else {
echo "invalid";
}
}
The reason why I switched to PDO was to prevent SQL Injections.
But now: CheckPassword VERIFIES INVALID USING PDO
$pdo = new PDO('mysql:dbname=_DB_;host=localhost', '_USER_', '_PASS_',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$username = '_USERNAME_';
$pass = '_PASSWORD_';
$stmt = $pdo->prepare('SELECT * FROM `users` WHERE username = :u LIMIT 1');
$stmt->bindParam(':u', $username);
$stmt->execute();
if($fetch = $stmt->fetch(PDO::FETCH_ASSOC)){
$db_pass = $fetch['userpass'];
require 'PasswordHash.php';
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
if($hasher->CheckPassword($pass, $db_pass)) {
echo "valid";
} else {
echo "invalid"; // VERIFIES INVALID
}
}
}
How is it that; MySQLi fetches the hashed string different compared to PDO? No matter what encryption I use for hashing the passwords, it CANNOT validate them as true when fetching using PDO, BUT only when fetching using MySQLi?
The reason because when you comparing the password that the user enter and the password that in the database , its different , the pass that the user enter to log in to his account is not hashed while the one in the database is , so we need a way to hash the entered pass and validate it with the already hashed pass in the database . How to do that ? here
This is an example from a code that i use in my Control panel :
<?php
// connect to your database
if(isset($_POST['btn-login']))
{
$User_name = $_POST['userlogin'];
$password_user = $_POST['pass'];
$FetchUserData = $conn->prepare("SELECT * FROM users WHERE userlogin = ?");
$FetchUserData->execute(array($User_name));
$FetchedData = $FetchUserData->fetch(PDO::FETCH_ASSOC);
if ($FetchedData)
{
$password = $FetchedData['userpassword']; // Save the fetched password inside variable
$isPasswordCorrect = password_verify($password_user, $password);
if( $password_user == $isPasswordCorrect )
{
$_SESSION['login_user']=$User_name;
header("location: home.php");
}
else
{
echo "Password is wrong":
}
}
else
{
echo "User is not exist ";
}
}
?>
This Code line is the code used to hash the enterd pass with the exist pass in the database :
$isPasswordCorrect = password_verify($password_user, $password);
Small explanation :
password_verify(parameterA,parameterB)
parameterA : The password that you want it to be validate .
parameterB : the password that you want it to be validated with .(
database that is stored in the database )
Hope this answer be helpful for you .
Hey.. I'm a bit stuck on PHP code to insert data into multiple SQL tables. I an unable to get the data into both tables within a single action. This is for a registration page to create a user login and start of company profile. Any suggestions would be much appreciated. Thanks
<?php
session_start();
if(isset($_SESSION['user'])!="")
{
header("Location: home.php");
}
include_once 'resources/php/dbconnect.php';
if(isset($_POST['btn-signup']))
{
$uname = mysql_real_escape_string($_POST['uname']);
$email = mysql_real_escape_string($_POST['email']);
$upass = md5(mysql_real_escape_string($_POST['pass']));
$orgname = mysql_real_escape_string($_POST['orgname']);
$uname = trim($uname);
$email = trim($email);
$upass = trim($upass);
$orgname = trim($orgname);
// email exist or not
$query = "SELECT user_email FROM users WHERE user_email='$email'";
$result = mysql_query($query);
$count = mysql_num_rows($result); // if email not found then register
if($count == 0){
if(mysql_query("START TRANSACTION;
INSERT INTO users('user_name','user_email','user_pass')
VALUES('$uname','$email','$upass');
INSERT INTO companies('name','owner_id')
VALUES('$orgname','$email');
END;"))
{
?>
<script>alert('Registration Successful');</script>
<?php
}
else
{
?>
<script>alert('error while registering you...');</script>
<?php
}
}
else{
?>
<script>alert('Sorry Email ID already taken ...');</script>
<?php
}
}
?>
As you can see here the mysql extension is deprecated and you MUST stop using it. Great alternatives are PDO and mysqli
You should also use Prepared Statements to safeguard your code against SQL Injection attacks.
To complete a Transaction using PDO you can do this:
$conn->query("START TRANSACTION");
$stmt = $conn->prepare("INSERT INTO users(user_name,user_email,user_pass) VALUES(?,?,?)");
try
{
$stmt->bindValue(1,$user_name);
$stmt->bindValue(1, $user_email);
$stmt->bindValue(3, $user_pass);
$stmt->execute();
$secondStmt = $conn->prepare("INSERT INTO companies(name,owner_id) VALUES(?,?)");
$secondStmt->bindValue(1, $name);
$secondStmt->bindValue(2, $owner_id);
$secondStmt->execute();
$conn->query("COMMIT"); //This commits all changes if no error occured
}
catch(Exception $e)
{
$conn->query("ROLLBACK"); //This reverts any changes made in case of an error
}
You can do two inserts like this:
$queryUsers = INSERT INTO users('user_name','user_email','user_pass')
VALUES('$uname','$email','$upass');
mysql_query($queryUsers);
$queryCompanies = INSERT INTO companies('name','owner_id')
VALUES('$orgname','$email');
mysql_query($queryCompanies);
In addition, carefully with mysql_query, is deprecated, try to use mysqli().
Regards
I've been following a login system tutorial. You can find it here. There are 2 parts of coding C# and PHP. The C# part is working fine but my PHP part returning error. Here is my PHP code:
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$passwordp = "";
$database = "game_database";
$dbport = 3306;
// Create connection
mysql_connect($servername, $username, $passwordp, $dbport)or die("Cant Connect to server");
mysql_select_db($database) or die("Cant connect to database");
// Check connection
$Email = $_REQUEST["Email"];
$Password= $_REQUEST["Password"];
if (!$Email || !$Password){
echo"Email or password must be used";
}
else{
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
$result_id = #mysql_query($SQL) or die("Database Error");
$Total = mysql_num_rows($result_id);
if ($Total){
$datas = #mysql_fetch_array($result_id);
if (strcmp($Password, $datas["Password"])){
$sql2 = "SELECT Characters FROM users WHERE Email = '" . $Email ."'";
$result_id2 = #mysql_query($sql2) or die("Database Error!!!");
while ($row = mysql_fetch_array($result_id2)){
echo $row ["Characters"];
echo ":";
echo "Success";
}
}
else{
echo "WrongPassword";
}
}else {
echo "NameDoesNotExist";
}
}
?>
It seems the error comes from $result_id but I'm not sure?
You are true, the error is from $result_id, because your SQL statement has problem and there are extra stuff to fix.
You have put users table in two single quotes, it is wrong.
Your code is:
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
It should be with out quotes:
$SQL = "SELECT * FROM users WHERE Email = '" . $Email ."'";
You have wrote:
if ($Total){
It should check how many users record found, typically it should find only 1 record and return 1, therefore change it to:
if ($Total == 1){
Note1:
But when this is said, it does not mean the code is perfect, you should further develop your code to fulfill nowadays requirement. I would suggest you think of password hashing, use mysqli or PDO in sted of mysql and input sensitization. I would suggest you look at this link it describes some of the things I mentioned.
Note2:
I was able to write you a total solution with mysqli/PDO etc, but I wanted only to point the errors I have catch so far in your code so you can learn from your mistakes and develop your self.
And in general read about security principles, check this page.
Link1: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Link2: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
This is another simple way where you can create user log in, it is
more secure than the one you have at the moment. And you should
protect your code from sql injections.
<?php
if (isset($_POST['email'], $_POST['password']) === true )
{
require 'connection.php';
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$sql = "SELECT * FROM users WHERE email= '$email'";
$result = mysqli_query($connection,$sql);
if (mysqli_num_rows($result))
{
if( $email == $row['email'] && $password == $row['password'])
{ //use session to check if user is logged in
if (!isset($_SESSION['loggedin']))
{
//you can set session of user's log in details
//you can redirect to user profile
}
else
//already log in, redirect to user profile
}
else
echo "Incorrect Email or Password.";
}
else
echo "Incorrect Username or Password.";
mysqli_close($connection);
}
else
{
echo "Oops, something went wrong!";
?>
I have to make a login system on my website, but my users don't have the same things on their sites so I will $_GET my users' customers_id (from database) in the URL when they are logged in.
But I cannot see how.
my login code is this.
<?php
$email = $_POST['user'];
$password= $_POST['pass'];
$login = $_POST['login'];
$user_custermers_id = $_GET['id'];
if($login == 'Login' || isset($login))
{
global $wpdb;
$get = mysql_query("SELECT * FROM das_custermer_users WHERE email = '$email' AND password ='" . md5($password)."'") or die(mysql_error());
$result = mysql_num_rows($get);
if($result == 0)
{
$msg = "Wrong E-mail or Password";
}
else
{
session_start();
$_SESSION['email'] = $email;
header("location: http://dashboard.tg.com");
}
}
?>
You're writing really bad and dangerous code. What if I catch $_POST['email'] and change it to '--;DELETE your_data_base; ?
You don't check what data you have and SQL injection is possible in your example.
if($login == 'Login' || isset($login))
this condition is without sense because if there is $login== 'login' then isset is TRUE so second OR condition is unneccesary
session_start();
you should move it to 1st line.
global is an old PHP syntax avoid it.
$user_custermers_id = $_GET['id']; this is really bad. You should cast to to int or use intval()
If I were you I would use PDO connection. PDO has PDOStatement::rowCount you can use this property to check if there are any rows.
PDO throws exceptions so mysql_errror() is not needed. mysql_num_rows() is deprecated as of PHP 5.5.0, and will be removed in the future so avoid it.
I found this sample in internet. This code should be also in try catch block to handle exceptions
$login = mysql_escape_string(trim($_POST['login']));
$pass = mysql_escape_string(trim($_POST['pass']));
$dbh = new PDO('mysql:host=localhost;dbname=mydatabase', 'user', 'pass');
$sth = $dbh->prepare("SELECT * FROM table WHERE login = ? AND pass = ?");
$sth->bindParam(1, $login);
$sth->bindParam(2, md5($pass));
$sth->execute();
if ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
}