-4

i am trying to make the user show when i click browse in phpmyadmin in localhost. i created a table called test. i am trying, when you sign up, it shows the user in the database and signs him or her up, but it does not using this code: hoping.php:

<?php
$reg     = @$_users['reg'];
$fn      = "";
$ln      = "";
$un      = "";
$em      = "";
$em2     = "";
$pswd    = "";
$pswd2   = "";
$d       = "";
$u_check = "";
$fn      = strip_tags(@$_test['fname']);
$ln      = strip_tags(@$_test['lname']);
$un      = strip_tags(@$_test['username']);
$em      = strip_tags(@$_users['email']);
$em2     = strip_tags(@$_users['email2']);
$pswd    = strip_tags(@$_users['password']);
$pswd2   = strip_tags(@$_users['password2']);
$d       = date("Y-m-d");

if ($reg) {
    if ($em == $em2) {
        $u_check = mysql_query("SELECT username FROM users WEHRE username='$un'");
        $check   = mysql_num_rows($u_check);
        if ($check == 0) {
            if ($fn && $ln && $un && $em && $em2 && $pswd && $pswd2) {
                if ($pswd == $pswd2) {
                    if (strlen($un) > 25 || strlen($fn) > 25 || strlen($ln) > 25) {
                        echo "The maximum limit for username/first name/last name is 25 characters!";
                    } else {
                        if (strlen($pswd) > 30 || strlen($pswd) < 5) {
                            echo "Your password must be between 5 and 30 characters long!";
                        } else {
                            $pswd  = md5($pswd);
                            $pswd2 = md5($pswd2);
                            $query = mysql_query("INSERT INTO users VALUES ('', '$un', '$fn', '$ln','$em', '$pswd', '$d','0')");
                            die("<h2>Welcome to communicate</h2>Login to your account to get started ...");
                        }
                    }
                } else {
                    echo "Your passwords don't match!";
                }
            } else {
                echo "Please fill in all of the fields";
            }
        } else {
            echo "Username already taken ...";
        }
    } else {
        echo "Your E-mails don't match!";
    }
}
if (isset($_users["user_login"]) && isset($_users["password_login"])) {
    $user_login     = preg_replace('#[^A-Za-z0-9]#i', '', $_users["user_login"]);
    $password_login = preg_replace('#[^A-Za-z0-9]#i', '', $_users["password _login"]);
}
?>

<div style="width: 800px; margin: 0px auto 0px auto;">
<table>
   <tr>
      <td width="60%" valign="top">
         <h2>Already a member? Sign in below!</h2>
         <form action="hoping.php" method="users">
            <input type="text" name="username" size="25" placeholder="Username"/><br /><br />
            <input type="text" name="Password2" size="25" placeholder="Password (again)"/><br /><br />
            <input type="submit" name="reg" value="Sign Up!">
         </form>
      <td>
      <td width="40%">
         <h2>Sign Up Below!</h2>
         <form action="hoping.php" method="users">
         <input type="text" name="fname" size="25" placeholder="First Name" />
         <p />
            <input type="text" name="lname" size="25" placeholder="Last Name"/><br /><br />
            <input type="text" name="username" size="25" placeholder="username"/><br /><br />
            <input type="text" name="email" size="25" placeholder="Email Address"/><br /><br />
            <input type="text" name="email2" size="25" placeholder="Email Address (again)"/><br /><br />
            <input type="text" name="password" size="25" placeholder="Password"/><br /><br />
            <input type="text" name="Password2" size="25" placeholder="Password (again)"/><br /><br />
            <input type="submit" name="reg" value="Sign Up!">
      </td>
   </tr>
</table>

<?php include ("./connect.inc.php");

connect.inc.php

<?php 
mysql_connect("localhost", "root", "") or die("Couldnt conocet to server");
mysql_select_db("test") or die("Could'nt select DB");
?>
Stanimir Stoyanov
  • 1,623
  • 18
  • 29
ilikeyoyo
  • 168
  • 4
  • 20
  • Don't use mysql*! It's deprecated and very insecure. Like thise you're wide open to SQL injection. – icecub Nov 02 '14 at 00:51
  • What is the question? What `it does not using this code` means? – Stanimir Stoyanov Nov 02 '14 at 01:03
  • it means that when using this code, it does not sign up the user. – ilikeyoyo Nov 02 '14 at 01:12
  • what should i use besides mysql? – ilikeyoyo Nov 02 '14 at 01:13
  • 3
    I'm already rewriting your entire code for you. It's so full of mistakes and errors that I can't even begin to point them all out. I'll be using PDO() instead of mysql() with prepared statements for your security. Gonna take some time though. – icecub Nov 02 '14 at 01:21
  • @Whathaveyoutried Well I'm bored xD Aside from that I like these kinds of small projects to keep my skills in shape and useally try to improve myself along the way. Like for example I wasn't used to Salt encryption techniques. Now learning it because of this :) – icecub Nov 02 '14 at 01:51
  • I re-write people's code sometimes... for those reasons exactly. [Here's some PHP](http://stackoverflow.com/a/26456264/623952) that shows how to store passwords... and [this is php about](http://stackoverflow.com/a/26321573/623952) logging in, new users, new passwords. mysqli. – gloomy.penguin Nov 02 '14 at 02:11
  • `name="Password2"` and `['password2']` = No love. Check for errors. – Funk Forty Niner Nov 02 '14 at 02:32
  • **WARNING:** DO NOT write your own authentication layer unless you have a lot of experience with this. A better plan is to use a [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) that comes with an [authentication system](http://laravel.com/docs/security) that's ready to use. As always, follow the advice in a [best practices for PHP guide](http://www.phptherightway.com/). What you have here is not an authentication system, but the opposite: A web site **hacking** system. – tadman Nov 02 '14 at 02:32

1 Answers1

0

Ok so here's the improved script. Please make sure you read all the comments and correct stuff where needed as this is NOT ready-to-use code!

Change your connect.inc.php to (please make sure you fill in all the nessesary information):

<?php

$dbhost = ""; //MySQL host (usually: localhost)
$dbuser = ""; //MySQL user
$dbpass = ""; //MySQL password
$dbname = ""; //MySQL database name

$pdo = new PDO("mysql:host=".$dbhost.";dbname=". $dbname, $dbuser, $dbpass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

?>

Change hoping.php to:

<?php

require "connect.inc.php";

/*
Using md5 to encrypt a password is not secure.
I've written a much more secure function for password encryption.
However this requires your database to have enough room for it.

For example: `password` VARCHAR(128) NOT NULL

If you need to alter your database to make the room, please
execute this command in phpMyAdmin (change password to whatever
the column name is in your users table):

ALTER TABLE `users` MODIFY COLUMN `password` VARCHAR(128);

If your database has the room for this, please set the following
variable to true. Otherwise leave it false to keep using md5.
*/
$secureCrypt = false;

if(isset($_POST['login'])){
    $sql = "SELECT * FROM users WHERE username = :user";
    $pre = $pdo->prepare($sql);

    $pre->bindValue(":user", $_POST['Username']);

    if($pre->execute()){
        $data = $pre->fetch();
        if($secureCrypt){
            //Please correct 'column_name_here'.
            //I was unable to do this for you because I lacked the column name
            //where the passwords are stored.
            if(crypt($_POST['Password'], $data['column_name_here']) == $data['column_name_here']){
                echo "You have succesfully logged in!<br />";
            } else {
                echo "Invalid password!<br />";
            }
        } else {
            if(md5($_POST['Password']) == $data['column_name_here']){
                echo "You have succesfully logged in!<br />";
            } else {
                echo "Invalid password!<br />";
            }
        }
    } else {
        echo "\nMySQL returned error:\n";
        print_r($pdo->errorInfo());
    }
}

if(isset($_POST['register'])){
    $error = false;
    $error_text = "";

    //Check names for illegal characters
    // Allows A-Z, a-z, underscore( _ ), dots( . ), spaces and dashes( - )
    function nameRegex($var){
        if(!preg_match("/^[a-zA-Z_\. \-]+$/i", $var)){
            return true;
        } else {
            return false;
        }
    }

    //Check names for illegal characters
    // Allows A-Z, a-z, underscore( _ ), dots( . ) and dashes( - )
    function userRegex($var){
        if(!preg_match("/^[0-9a-zA-Z_\-]+$/i", $var)){
            return true;
        } else {
            return false;
        }
    }

    //Check for valid mail address
    function mailFilter($var){
        if(filter_var($var, FILTER_VALIDATE_EMAIL) === false){
            return true;
        } else {
            return false;
        }
    }

    //Check if 2 values match
    function matchValues($var1, $var2){
        if($var1 != $var2){
            return true;
        } else {
            return false;
        }
    }

    //Check if username already exists
    function checkUser($user){
        $sql = "SELECT username FROM users WHERE username = :user";
        $pre = $pdo->prepare($sql);

        $pre->bindValue(":user",$user);

        if($pre->execute()){
            $count = $pre->rowCount();
            if($count > 0){
                return true;
            } else {
                return false;
            }
        } else {
            echo "\nMySQL returned error:\n";
            print_r($pdo->errorInfo());
        }
    }

    //Check for correct size
    function checkSize($var, $size){
        if(strlen($var) > $size){
            return true;
        } else {
            return false;
        }
    }

    //Securely encrypt user passwords
    function cryptPass($pass, $rounds = 9){
        $salt = "";
        $saltChars = array_merge(range('A','Z'), range('a','z'), range(0,9));

        for($i=0;$i<22;$i++){
            $salt .= $saltChars[array_rand($saltChars)];
        }

        return crypt($pass, sprintf('$2y$%02d$', $rounds) . $salt);
    }


    if(nameRegex($_POST['fname'])){
        $error = true;
        $error_text .= "Your First Name contains illegal characters!<br />";
    }

    if(nameRegex($_POST['lname'])){
        $error = true;
        $error_text .= "Your Last Name contains illegal characters!<br />";
    }

    if(userRegex($_POST['username'])){
        $error = true;
        $error_text .= "Your Username contains illegal characters!<br />";
    }

    if(mailFilter($_POST['email'])){
        $error = true;
        $error_text .= "Your Email Address does not appear to be valid!<br />";
    }

    if(mailFilter($_POST['email2'])){
        $error = true;
        $error_text .= "Your 2nd Email Address does not appear to be valid!<br />";
    }

    if(matchValues($_POST['email'], $_POST['email2'])){
        $error = true;
        $error_text .= "It appears both Email Addresses did not match!<br />";
    }

    if(matchValues($_POST['password'], $_POST['password2'])){
        $error = true;
        $error_text .= "It appears both Passwords did not match!<br />";
    }

    if(checkUser($_POST['username'])){
        $error = true;
        $error_text .= "The Username is already taken by another user!<br />";
    }

    if(checkSize($_POST['fname'], 25)){
        $error = true;
        $error_text .= "The First Name contains to many characters!<br />";
    }

    if(checkSize($_POST['lname'], 50)){
        $error = true;
        $error_text .= "The Last Name contains to many characters!<br />";
    }

    if(checkSize($_POST['username'], 16)){
        $error = true;
        $error_text .= "The Username contains to many characters!<br />";
    }

    if(checkSize($_POST['username'], 125)){
        $error = true;
        $error_text .= "The Email address contains to many characters!<br />";
    }

    if(!$error){
        if($secureCrypt){
            $hashPass = cryptPass($_POST['password']);
        } else {
            $hashPass = md5($_POST['password']);
        }

        $sql = "INSERT INTO users VALUES ('',':username',':fname',':lname',':email',':password',':date','0')";
        $pre = $pdo->prepare($sql);

        $pre->bindValue(":username",$_POST['username']);
        $pre->bindValue(":fname",$_POST['fname']);
        $pre->bindValue(":lname",$_POST['lname']);
        $pre->bindValue(":email",$_POST['email']);
        $pre->bindValue(":password",$_POST['password']);
        $pre->bindValue(":date",date("Y-m-d"));

        if($pre->execute()){
            echo "You are succesfully registered. Welcome!";
        } else {
            echo "\nMySQL returned error:\n";
            print_r($pdo->errorInfo());
        }
    } else {
        echo "There are some problems with your registration.<br />";
        echo "Please correct the following errors:<br /><br />";
        echo $error_text;
        echo "<br />";
    }
}

?>

<!DOCTYPE HTML>
<html>
    <head>
        <title>Login Page</title>
        <style>
        #div1 {
            width: 800px;
            margin: 0px auto 0px auto;
        }
        #td1 {
            width: 60%;
            vertical-align: top;
        }
        #td2 {
            width: 40%;
        }
        </style>
    </head>
    <body>
        <div id="div1">
            <table>
                <tr>
                    <td id="td1">
                        <h2>Already a member? Sign in below!</h2>
                        <form action="hoping.php" method="post" id="user_login" accept-charset="utf-8">
                            <input type="text" name="username" size="25" placeholder="Username"/><br /><br />
                            <input type="password" name="Password" size="25" placeholder="Password"/><br /><br />
                            <input type="submit" name="login" value="Login!">
                        </form>
                    </td>
                    <td id="td2">
                        <h2>Sign Up Below!</h2>
                        <form action="hoping.php" method="post" id="user_register" accept-charset="utf-8"> 
                            <input type="text" name="fname" size="25" placeholder="First Name" value="<?php echo $_POST['fname'] ?>" /><br /><br />
                            <input type="text" name="lname" size="25" placeholder="Last Name" value="<?php echo $_POST['lname'] ?>" /><br /><br />
                            <input type="text" name="username" size="25" placeholder="username" value="<?php echo $_POST['username'] ?>" /><br /><br />
                            <input type="text" name="email" size="25" placeholder="Email Address" value="<?php echo $_POST['email'] ?>" /><br /><br />
                            <input type="text" name="email2" size="25" placeholder="Email Address (again)" value="<?php echo $_POST['email2'] ?>" /><br /><br />
                            <input type="text" name="password" size="25" placeholder="Password"/><br /><br />
                            <input type="text" name="password2" size="25" placeholder="Password (again)"/><br /><br />
                            <input type="submit" name="register" value="Sign Up!">
                        </form>
                    </td>
                </tr>
            </table>
        </div>
    </body>
</html>
icecub
  • 8,615
  • 6
  • 41
  • 70
  • it gives an error for line 98 in hoping.php: Notice: Undefined variable: pre in D:\Download\htdocs\hoping.php on line 100 Fatal error: Call to a member function bindValue() on a non-object in D:\Download\htdocs\hoping.php on line 100 and on line 98: Notice: Undefined variable: pdo in D:\Download\htdocs\hoping.php on line 98 Fatal error: Call to a member function prepare() on a non-object in D:\Download\htdocs\hoping.php on line 98 – ilikeyoyo Nov 02 '14 at 03:31
  • @Rarster Did you edit your "connect.inc.php" like I told you? Those errors only mean the PDO object was not created. This can only happen if you didn't change that file or if that file is not in the same folder as "hoping.php" – icecub Nov 02 '14 at 03:38