0

It's a bit hard to understand, extract and apply all the advice provided by advanced users from posts like this or this and others, for non-advanced users like me.

I need to a simple but secure MySQLi and PHP user registration (username + password); I've tried to follow advices contained in these post, but I'm not sure if my code is secure from injections and if is it outdated:

Registration.php:

$host = "localhost";
$dbuser = "xxxx";
$dbpassword = "xxxx";
$dbname = "xxxx";

$conn = mysql_connect($host, $dbuser, $dbpassword);
if($conn == 0){
    echo "Connection Failed";
}

$db_select = mysqli_select_db($dbname, $conn);

$username = mysqli_real_escape_string($_POST['username']);
$password = $POST['password'];

if($user == '' or $password == ''){
    echo "Compile all!";
}else{
    $query = "Insert Into 'user' ('username' , 'password') VALUES ('$username' , '$password')";
    $query2 = mysqli_query($query);
    echo "Registration complete";
}

It certainly needs a lot of improvements, I hope to understand all your advices because I'm new to this.

Community
  • 1
  • 1
  • You're mixing api's (mysql & mysqli), they are **not** interchangeable. – Darren Jun 24 '14 at 23:41
  • And short answer: Yes you're open to sql injections (`$password = $POST['password'];`). – Darren Jun 24 '14 at 23:42
  • Quotes are for strings,backticks are for table and column names. – Mihai Jun 24 '14 at 23:44
  • I've already created a table manually from the web UI, it is called "user".. please can you post some example? –  Jun 24 '14 at 23:48
  • I've not used it, but the UserCake library might be better for you than rolling your own. There's quite a few security issues to be aware of when writing this stuff. – halfer Jun 24 '14 at 23:54
  • You should look into [**`PDO`**](http://www.php.net//manual/en/book.pdo.php) & [**`MySQLi Prepared Statements.`**](http://www.php.net//manual/en/book.mysqli.php) – Darren Jun 24 '14 at 23:56
  • @halfer I've installed UserCake, but when I logout a blank page appears and in the URL only "localhost" appears... –  Jun 25 '14 at 00:41
  • @user3746998: see your Apache error log in case there is a config issue causing a fatal error. – halfer Jun 25 '14 at 08:35

3 Answers3

1

You need to stay consistent with your functions, mysql_* functions are not interchangeable with mysqli_* functions. Stick with mysqli_* functions and read about prepared statements, they will help with preventing injection.

As far as passwords, the first thing you need to know is to not store passwords in your database. What that means is as plain text. If you have access to PHP5.5 +, read about these functions which directly relate to hashing a password, which you can store in database.

Brett Santore
  • 799
  • 6
  • 14
1

Here is the Registration code that i'm using for My registration. Its working great.

<?php include('header.php'); ?>

<?php
include('config.php');  // Database connection and settings

error_reporting(E_ALL);
ini_set('display_errors', 1);


if(isset($_POST['register'])){

$name = trim(mysqli_escape_string($conn,$_POST['username']));
$first_name = trim(mysqli_escape_string($conn,$_POST['first_name']));
$last_name = trim(mysqli_escape_string($conn,$_POST['last_name']));
$display_name = trim(mysqli_escape_string($conn,$_POST['display_name']));
$email = trim(mysqli_escape_string($conn,$_POST['email']));
$passwords = trim(mysqli_escape_string($conn,$_POST['password']));
$password = password_hash($passwords, PASSWORD_DEFAULT); // for Better Hashing Password

or $password = md5($passwords);

$query_verify_email = "SELECT * FROM users WHERE email ='$email'";
$verified_email = mysqli_query($conn,$query_verify_email) or die("Error: ".mysqli_error($conn));
if (!$verified_email) {
echo ' System Error';
}
if (mysqli_num_rows($verified_email) == 0) {
// Generate a unique code:
$hash = md5(uniqid(rand(), true));
$query_create_user = "INSERT INTO users ( username, email, password, hash,first_name,last_name,display_name,pic,gender,isactive) 
VALUES ( '$name', '$email', '$password', '$hash','$first_name','$last_name','$display_name','','',0)";
$created_user = mysqli_query($conn,$query_create_user) or die("Error: ".mysqli_error($conn));
if (!$created_user) {
echo 'Query Failed ';
}

if (mysqli_affected_rows($conn) == 1) { //If the Insert Query was successfull.

$subject = 'Activate Your Email';

$headers = "From: admin@infotuts.com \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$url= 'verify.php?email=' . urlencode($email) . "&key=$hash";

$message ='<p>To activate your account please click on Activate buttton</p>';
$message.='<table cellspacing="0" cellpadding="0"> <tr>';
$message .= '<td align="center" width="300" height="40" bgcolor="#000091" style="-webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;

color: #ffffff; display: block;">';

$message .= '<a href="'.$url.'" style="color: #ffffff; font-size:16px; font-weight: bold; font-family: Helvetica, Arial, sans-serif; text-decoration: none;

line-height:40px; width:100%; display:inline-block">Click to Activate</a>';
$message .= '</td> </tr> </table>';

mail($email, $subject, $message, $headers);

echo '<div class="alert alert-success">A confirmation email
has been sent to <b>'. $email.' </b> Please click on the Activate Button to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="alert alert-info">You could not be registered due to a system
error. We apologize for any
inconvenience.</div>';
die(mysqli_error($conn));
}
}
else{
echo '<div class="alert alert-danger">Email already registered</div>';}
}
?>
<div class="row">
    <div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
        <form role="form" action='' method="post" enctype="multipart/form-data">
            <h2>Please Sign Up <small>It's free and always will be.</small></h2>
            <hr class="colorgraph">
            <div class="row">
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="form-group">
                        <input type="text" name="first_name" id="first_name" class="form-control input-lg" placeholder="First Name" tabindex="1">
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="form-group">
                        <input type="text" name="last_name" id="last_name" class="form-control input-lg" placeholder="Last Name" tabindex="2">
                    </div>
                </div>
            </div>
            <div class="form-group">
                <input type="text" name="username" id="username" class="form-control input-lg" placeholder="User Name" tabindex="3">
            </div>
            <div class="form-group">
                <input type="text" name="display_name" id="display_name" class="form-control input-lg" placeholder="Display Name" tabindex="3">
            </div>
            <div class="form-group">
                <input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address" tabindex="4">
            </div>
            <div class="row">
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="form-group">
                        <input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="5">
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="form-group">
                        <input type="password" name="password_confirmation" id="password_confirmation" class="form-control input-lg" placeholder="Confirm Password" tabindex="6">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-xs-4 col-sm-3 col-md-3">
                    <span class="button-checkbox">
                        <button type="button" class="btn" data-color="info" tabindex="7">I Agree</button>
                        <input type="checkbox" name="t_and_c" id="t_and_c" class="hidden" value="1">
                    </span>
                </div>
                <div class="col-xs-8 col-sm-9 col-md-9">
                     By clicking <strong class="label label-primary">Register</strong>, you agree to the <a href="#" data-toggle="modal" data-target="#t_and_c_m">Terms and Conditions</a> set out by this site, including our Cookie Use.
                </div>
            </div>

            <hr class="colorgraph">
            <div class="row">
                <div class="col-xs-12 col-md-6"><input type="submit" name='register' value="Register" class="btn btn-primary btn-block btn-lg" tabindex="7"></div>
                <div class="col-xs-12 col-md-6"><a href="login.php" class="btn btn-success btn-block btn-lg">Sign In</a></div>
            </div>
        </form>
    </div>
</div>
</div>
Kavin
  • 332
  • 2
  • 8
0

There are quite a few problems with your code. The main problems is you're using obsolete db connection methods (mysql_* functions). You're also trying to interchange mysqli_* functions with it. My recommendation is you scrap that code and learn PDO. I'm sure it's becoming a standard in newer PHP version (or so I was told).

Other than that, you're checking whether a db connection is valid but even if it isn't the code will carry on and run the query.. If you aren't too bothered about UX if the db connection fails then you can just call die($string); and that will kill the script and echo out a string. Another thing, 'or' isn't a valid operator. It's || for or. You're also referencing a super global variable wrong. It's '$_POST', not '$POST'. You're also not hashing passwords. You should look up how to hash passwords but be aware of broken algorithms like md5 etc. I usually tend to go with crypt with a random bytes salt. There is large debate over the best one. But overall if you program a good system then you shouldn't have too worry too much about data being 'un-hashed' (wrong terminology).

I hope this helped. My advice is learn PHP more before indulging in projects like login systems etc. that could put user's data at risk.

user3530525
  • 691
  • 3
  • 8
  • 20