field name entered are still inserted in database. (PHP) - php

I have this validation code:
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl=mysql_query("SELECT * FROM tablename");
while($row=mysql_fetch_array($tbl))
{
$name=$_POST['name'];
$lname=$_POST['lname'];
$add=$_POST['add'];
$age=$_POST['age'];
$contact=$_POST['contact'];
$email=$_POST['email'];
$user=$_POST['user'];
$pass=$_POST['pass'];
if(($name!="")&&($lname!="")&&($add!="")&&($age!="")&&($contact!="")&& ($email!="")&&($user!="")&&($pass!=""))
{
if ($_POST['user']==$row['username'])
{
header("location: /register.php?codeErr2=1");
}
else
{
$value=mysql_query("INSERT INTO tablename(name, lastname, address, age, contact,email, username, password) VALUES ('".$_POST['name']."','".$_POST['lname']."','".$_POST['add']."','".$_POST['age']."','".$_POST['contact']."','".$_POST['email']."','".$_POST['user']."','".$_POST['pass']."')");
}
}
else
{
header("location: /register.php?codeErr=1");
}
}
This validation is for my registration form, If all the fields are filled up it will check if the username that the user enters is already on the database or not, else, it will get an error message. If the username is already on the database, an error message will be outputted else it will proceed to the next page and all values will be inserted on the database. The problem is that whenever I enter the username which was already on the database, it still accepts the username. I can't find anything wrong with my validation code. Can someone help me out what could be the possible problem here? Thank you in advance. :)

You should check for username and die after the redirect:
$tbl=mysql_query("SELECT * FROM tablename WHERE `username` = '".mysql_real_escape_string($_POST['user'])."'");
$row = mysql_fetch_assoc($tbl);
if ($_POST['user'] == $row['username']){
header("location: /register.php?codeErr2=1");
die;
}
You code is SQL injection vulnerable:
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl=mysql_query("SELECT * FROM tablename WHERE `username` = '".mysql_real_escape_string($_POST['user'])."'");
$row = mysql_fetch_assoc($tbl);
if ($_POST['user'] == $row['username']){
header("location: /register.php?codeErr2=1");
die;
}
$name= $_POST['name'];
$lname= $_POST['lname'];
$add = $_POST['add'];
$age = $_POST['age'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$user = $_POST['user'];
$pass = $_POST['pass'];
if(($name!="") && ($lname!="") && ($add!="") && ($age!="") && ($contact!="") && ($email!="") && ($user!="") && ($pass!="")){
$value=mysql_query("INSERT INTO tablename(name, lastname, address, age, contact, email, username, password)
VALUES
('".mysql_real_escape_string($name)."','".mysql_real_escape_string($lname)."','".mysql_real_escape_string($add)."','".mysql_real_escape_string($age)."',
'".mysql_real_escape_string($contact)."','".mysql_real_escape_string($email)."','".mysql_real_escape_string($user)."',
'".mysql_real_escape_string($pass)."')");
} else {
header("location: /register.php?codeErr=1");
die;
}
As a side note you should move to PDO or MySQLi as mysql_* functions are deprecated.
Here is a nice tutorial and here is an example:
$db = new PDO('mysql:host=localhost;dbname=nnx;charset=UTF-8', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION))
$stmt = $db->prepare("SELECT * FROM `tablename` WHERE `username` = :username");
$stmt->execute(array(':username' => $_POST['user']));
$row_count = $stmt->rowCount();
if($row_count){
header("location: /register.php?codeErr2=1");
die;
}
if(($name!="") && ($lname!="") && ($add!="") && ($age!="") && ($contact!="") && ($email!="") && ($user!="") && ($pass!="")){
$stmt = $db->prepare("INSERT INTO `tablename`(`name`, `lastname`, `address`, `age`, `contact`, `email`, `username`, `password`) VALUES (:name, :lname, :address, :age, :contact, :email, :username, :password)");
$stmt->execute(array(':name' => $_POST['name'], ':lname' => $_POST['lname'], ':address' => $_POST['add'], ':age' => $_POST['age'], ':contact' => $_POST['contact'], ':email' => $_POST['email'], ':username' => $_POST['user'], ':password' => $_POST['pass']));
} else {
header("location: /register.php?codeErr=1");
die;
}
This way your are sql injection free.

<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$name=$_POST['name'];
$lname=$_POST['lname'];
$add=$_POST['add'];
$age=$_POST['age'];
$contact=$_POST['contact'];
$email=$_POST['email'];
$user=$_POST['user'];
$pass=$_POST['pass'];
if(($name!="")&&($lname!="")&&($add!="")&&($age!="")&&($contact!="")&& ($email!="")&&($user!="")&&($pass!=""))
{
$tbl=mysql_query("SELECT * FROM tablename where username = '{$user}'");
$num_rows = mysql_num_rows($tbl);
if($num_rows > 0){
header("location: /register.php?codeErr2=1");
} else {
while($row=mysql_fetch_array($tbl))
{
$value=mysql_query("INSERT INTO tablename(name, lastname, address, age, contact,email, username, password) VALUES ('".$_POST['name']."','".$_POST['lname']."','".$_POST['add']."','".$_POST['age']."','".$_POST['contact']."','".$_POST['email']."','".$_POST['user']."','".$_POST['pass']."')");
}
}
} else {
header("location: /register.php?codeErr=1");
}
?>

Related

How can I check if a user exists with PDO?

My PDO query is not working for some reason, the page itself doesn't seem to have any error, I've been trying to fix this for like 2 months and nothing worked, I got this "final" code which not seems to have any errors and it's still not working.
<?php
require 'database.php';
$message = '';
if (!empty($_POST['username']) && !empty($_POST['email']) && !empty($_POST['phone']) && !empty($_POST['password'])) {
$sql = "INSERT INTO users (username, email, phone, password) VALUES (:username, :email, :phone, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':phone', $_POST['phone']);
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt->bindParam(':password', $password);
$query = $con->prepare("SELECT username FROM users WHERE username = :username");
$query->bindParam(':username', $_POST['username']);
$query->execute();
if($query->rowCount() > 0){
?> Este usuario ya existe <?php
}
else {
if($stmt->execute()) {
header('Location: login.php');
}
else {
echo "OcurriĆ³ un error";
}
}
}
?>
I suppose that it's because you have used a inapropriate variable.
in initialisation of $stmt you used $conn and in $query you used $con
make sure to the rigth varaible

Why doesn't my password validation work?

I'm making a login screen for my blog but when it has to validate the hash it fails. I have googled a lot watched here and asked a few class mates but it still fails. When you submit you get the alert
Wrong password or username!
How can I fix this?
this is my login script
<?php
include_once('resources/db.php');
$sql = "SELECT username, password FROM users WHERE username = :username";
$query = $db->prepare($sql);
$query->execute(array(":username" => $_POST['username']));
$user = $query->fetch(PDO::FETCH_ASSOC);
if ( isset( $_POST['submit'] )) {
$username = $_POST['username'];
$password = $_POST['password'];
$hash_password = $user['password'];
if ( password_verify($password, $hash_password)) {
if ($query->rowCount() == 1){
echo "chrisschotman is ingelogd";
} else {
echo "<script type=\"text/javascript\">alert('Wrong username!')</script>";
}
} else {
echo "<script type=\"text/javascript\">alert('Wrong password or username!')</script>";
}
}
?>
this is my login form
<form action="" method="post">
<input type="text" placeholder="username" name="username"maxlength="24"><br>
<input type="password" placeholder="password" name="password" minlength="8"
maxlength="16"><br>
<input type="submit" value="login" name="submit">
</form>
this is my registration script
<?php
include_once('resources/db.php');
// var_dump($_POST);
$query = $db->prepare('insert into users (`username`, `password`, `privileges`) values(?, ?, ?)');
$query =$db->prepare('select * from users');
$query->execute();
?>
//here is the registration form
<?php
if (isset($_POST)) {
include_once('resources/db.php');
$sql = "INSERT INTO users (`username`, `password`) VALUES (:username, :password)";
$query = $db->prepare($sql);
$query->execute(array(
':username' => $_POST['username'],
':password' => password_hash($_POST['password'], PASSWORD_DEFAULT)
));
if ($query) {
echo "Registered succefully";
} else {
echo "Occured and error";
}
}
?>
database structure
database rows
Change the database row to varchar(255)
$sql = "SELECT username, password FROM users WHERE username = :username";
$query = $db->prepare($sql);
$query->execute(array(":username" => $_POST['username']));
$user = $query->fetch(PDO::FETCH_ASSOC);
And try this registration:
<?php
$db = new PDO('mysql:host=localhost;dbname=' . $db_name . ',' . $db_user . ',' . $db_pass);
if (isset($_POST)) {
include_once('resources/db.php');
$sql = "INSERT INTO users (`username`, `password`) VALUES (:username, :password)";
$query = $db->prepare($sql);
$query->execute(array(
':username' => $_POST['username'],
':password' => password_hash($_POST['password'], PASSWORD_DEFAULT)
));
if ($query) {
echo "Registered succefully";
} else {
echo "Occured and error";
}
}

ERROR WHILE INSERTING USING MYSQLI

i'm new to this PHP please help me here i'm unable to insert values into table.
But if i gave values directly to insert command in place of variables it works.
<?php
include ("db.php");
$msg = "";
if(isset($_POST["submit"]))
{
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$name = mysqli_real_escape_string($db, $name);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql="SELECT email FROM users2 WHERE email='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg = "Sorry...This email already exist...";
}
else
{
$query = mysqli_query($db, "INSERT INTO users2 (name, email, password)VALUES ('$name', '$email', '$password')");
if($query)
{
$msg = "Thank You! you are now registered.";
}
}
}
?>
$sql = "INSERT INTO users2 (name, email, password) VALUES (?,?,?)";
if (!$stmt = $db->prepare($sql)) {
die($db->error);
}
$stmt->bind_param("sss", $name, $email, $password);
if (!$stmt->execute()) {
die($stmt->error);
}
I don't know what is the problem in my above question but
i used the above query instead of the one i used the in question and Boom it is a success.
if any one of you know whats the problem in the question please let me know.
You have to concat the variable in string of insert not just put as variable
$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('".$name."', '".$email."', '".$password."')")
or
$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('{$name}', '{$email}', '{$password}')")
You should use prepare statement for this mysql_real_escape_string-versus-Prepared-Statements
Never use md5() is-md5-considered-insecure
Prefer password_hash() or password_verify() Manuel
``

Quick PHP Variable guidance

I'm a newbie with PHP. I am trying to create a log in /register system for a project, so I am using a login system source code I found which has many functions and features like salted passwords. The system itself works fine, but I am trying to add more fields to my MySQL Table. The system had an array for extra columns, but I think it was resulting in bad mysql syntax so I decided to write out the query myself using the variables, but I am not sure how I can give access to the variables to the function. The variables are in the register.php document, here is the code (all of register.php):
if( isset($_POST['submit']) ){
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$user = $_POST['username'];
$sex = $_POST['sex'];
$country = $_POST['strCountryChoice'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$pass2 = $_POST['pass2'];
$birthdate = $_POST['birthdate'];
$created = date("Y-m-d H:i:s");
//need to add a lot more validation functions.. AKA Check if email exists and username. Password > 5 chars
if( $user=="" || $email=="" || $pass=='' || $pass2=='' || $firstname=='' || $lastname='' || $sex='' || $country='' || $birthdate='' ){
echo "Fields Left Blank","Some Fields were left blank. Please fill up all fields.";
exit;
}
if( !$LS->validEmail($email) ){
echo "E-Mail Is Not Valid", "The E-Mail you gave is not valid";
exit;
}
if( !ctype_alnum($user) ){
echo "Invalid Username", "The Username is not valid. Only ALPHANUMERIC characters are allowed and shouldn't exceed 10 characters.";
exit;
}
if($pass != $pass2){
echo "Passwords Don't Match","The Passwords you entered didn't match";
exit;
}
$createAccount = $LS->register($user, $pass,
array(
"email" => $email,
"name" => $firstname,
"lastname" => $lastname,
"gender" => $sex,
"country" => $country,
"DOB" => $birthdate,
"created" => date("Y-m-d H:i:s") // Just for testing
)
);
if($createAccount === "exists"){
echo "User Exists.";
}elseif($createAccount === true){
echo "Success. Created account.";
}
}
The whole system takes place in another file which has the class. Here is the register function:
public function register( $id, $password, $other = array() ){
if( $this->userExists($id) && (isset($other['email']) && $this->userExists($other['email'])) ){
return "exists";
}else{
$randomSalt = $this->rand_string(20);
$saltedPass = hash('sha256', "{$password}{$this->passwordSalt}{$randomSalt}");
if( count($other) == 0 ){
/* If there is no other fields mentioned, make the default query */
//old query: ("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`) VALUES(:username, :password, :passwordSalt)");
//new query: ("INSERT INTO `{$this->dbtable}` (`username`, 'email' , `password`, `password_salt` , 'name' , 'lastname' , 'gender' , 'country' , 'DOB') VALUES(:username, :email, :pass, :passwordSalt, :firstname, :lastname, :gender, :country, :DOB)");
$sql = $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`) VALUES(:username, :password, :passwordSalt)");
}else{
/* if there are other fields to add value to, make the query and bind values according to it */
//old query: ("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`, $columns) VALUES(:username, :password, :passwordSalt, :$colVals)");
//new query: ("INSERT INTO `{$this->dbtable}` (`username`, 'email' , `password`, `password_salt` , 'name' , 'lastname' , 'gender' , 'country' , 'DOB') VALUES(:username, :email, :pass, :passwordSalt, :firstname, :lastname, :gender, :country, :DOB)");
$keys = array_keys($other);
$columns = implode(",", $keys);
$colVals = implode(",:", $keys);
//l= $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`, $columns) VALUES(:username, :password, :passwordSalt, :$colVals)");
//INSERT INTO MyGuests (firstname, lastname, email)cLUES ('John', 'Doe', 'john#example.com')
$sql = $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (username,email,password,password_salt,name,lastname,created,gender,country,DOB) VALUES ('$username','$email','$pass','$saltedPass','$firstname','$lastname','$created','$gender','$country','$birthdate')");
print($sql);
foreach($other as $key => $value){
$value = htmlspecialchars($value);
$sql->bindValue(":$key", $value);
}
}
/* Bind the default values */
$sql->bindValue(":username", $id);
$sql->bindValue(":password", $saltedPass);
$sql->bindValue(":passwordSalt", $randomSalt);
$sql->execute();
return true;
}
}
So I need to use the variables from register.php in the class file. Can I just include it at the top or do I need to do something specific to the function?
Thanks. I'm focusing on the $sql line after else.
Yes you can include/require register.php file in the class file to use all the variables.
On another note i would like to mention that you should always filter out the POST data before adding it to the query for security concerns.

Php multiple isset check doesn't work

I have 4 inputs and they need to be filled. I made an isset test but it doesn't work. It is always showing true, but all inputs aren't filled and this php is for registering. Can you help me? Sorry for my bad English.
<?php
require('config.php');
Error_reporting(-1);
if (isset ($_POST['submit'])){
$username= $_POST['username'];
$iname= $_POST['iname'];
$email= $_POST['email'];
$pass= $_POST['pass'];
$pass1= $_POST['pass1'];
if (isset ($_POST['username']['iname']['email']['pass']['pass1'])){
/*$username= $_POST['username'];
$iname= $_POST['iname'];
$email= $_POST['email'];
$pass= $_POST['pass'];
$pass1= $_POST['pass1'];*/
if ($pass1 == $pass){
$username= mysqli_real_escape_string($link, $username);
$iname= mysqli_real_escape_string($link, $iname);
$email= mysqli_real_escape_string($link, $email);
$pass= mysqli_real_escape_string($link, $pass);
$pass1= mysqli_real_escape_string($link, $pass1);
$pass= md5($pass);
$check="SELECT username FROM users WHERE username = '$username'";
$rs = mysqli_query($link,$check);
$checker = mysqli_fetch_assoc($rs);
if ($checker['username'] == $username)
{
echo "Username is already taken";
exit();
}
$insert = "INSERT INTO `users` (`id`, `username`, `iname`, `email`, `pass`) VALUES (NULL, '$username', '$iname', '$email', '$pass')";
$query = mysqli_query ($link, $insert) or die("Query error");
//"INSERT INTO users ('id', 'username', 'iname', 'email', 'pass') VALUES ('NULL, '{$username}', '{$iname}', '{$email}', '{$pass}')"
}else{
echo "Passwords doesnt match";
}
}else{
echo "Fill all areas";
}
}else{
}
?>
I tested all answers in the comments, but none of them works! I don't understand why it doesn't work!
You can use this:
if (isset ($_POST['username'], $_POST['iname'], $_POST['email'], $_POST['pass'], $_POST['pass1'])){
//your code
}
this condition will return true only if all arguments to isset() are set and do not contain null.
Note: Instead of checking only for isset you should check this for empty also.
Like following:
if (isset ($_POST['username'], $_POST['iname'], $_POST['email'], $_POST['pass'], $_POST['pass1']) && !empty($_POST['username']. $_POST['iname']. $_POST['email']. $_POST['pass']. $_POST['pass1'])){
//your code
}
Try using
if (isset ($username, $iname, $email, $pass,$pass1))
instead...
require('config.php');
Error_reporting(-1);
if (isset ($_POST['submit'])){
$username= $_POST['username'];
$iname= $_POST['iname'];
$email= $_POST['email'];
$pass= $_POST['pass'];
$pass1= $_POST['pass1'];
if (!empty($username) and !empty($iname) and !empty($email) and !empty($pass) and !empty($pass1)){
if ($pass1 == $pass){
$username= mysqli_real_escape_string($link, $username);
$iname= mysqli_real_escape_string($link, $iname);
$email= mysqli_real_escape_string($link, $email);
$pass= mysqli_real_escape_string($link, $pass);
$pass1= mysqli_real_escape_string($link, $pass1);
$pass= md5($pass);
$check="SELECT username FROM users WHERE username = '$username'";
$rs = mysqli_query($link,$check);
$checker = mysqli_fetch_assoc($rs);
if ($checker['username'] == $username)
{
echo "Username is already taken";
exit();
}
$insert = "INSERT INTO `users` (`id`, `username`, `iname`, `email`, `pass`) VALUES (NULL, '$username', '$iname', '$email', '$pass')";
$query = mysqli_query ($link, $insert) or die("Query error");
//"INSERT INTO users ('id', 'username', 'iname', 'email', 'pass') VALUES ('NULL, '{$username}', '{$iname}', '{$email}', '{$pass}')"
}else{
echo "Passwords doesnt match";
}
}else{
echo "Fill all areas";
}
}else{
}
Best way to be sure is use it separately:
if(isset($_POST["username"]) and isset($_POST["email"]) and.... )

Categories