#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    6
    Rep Power
    0

    Cool How do i make a user name unique? php


    Hi how do i make a user name unique using php?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    158
    Rep Power
    10
    Originally Posted by nonde
    Hi how do i make a user name unique using php?
    With great difficulty. All PHP can do is check a list of existing names an see if it already exists. But, that does not stop anyone from inserting the same name while you are running the check.

    The only reliable way is to use a database and put a UNIQUE constraint on the column that holds the username.

    Comments on this post

    • Jacques1 agrees
    • Northie agrees
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    6
    Rep Power
    0
    Originally Posted by Vinny42
    With great difficulty. All PHP can do is check a list of existing names an see if it already exists. But, that does not stop anyone from inserting the same name while you are running the check.

    The only reliable way is to use a database and put a UNIQUE constraint on the column that holds the username.



    thankx for that. but am trying to write an sql code.
    basicaly am new to programming and am getting an error in my codes.

    I want to authenticate a user wen they register and then the system should do the hand shake by sending them an email.and they must not use the email address as the username
  6. #4
  7. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    Originally Posted by nonde
    basicaly am new to programming and am getting an error in my codes.
    We can't help you with that until you've actually posted the code and told us exactly what error you get.

    If you want concrete help, we need concrete info.



    Originally Posted by nonde
    and they must not use the email address as the username
    What? Why is that? And how do you wanna prevent people from entering an email address into the name field?
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    6
    Rep Power
    0
    Originally Posted by Jacques1
    We can't help you with that until you've actually posted the code and told us exactly what error you get.

    If you want concrete help, we need concrete info.





    What? Why is that? And how do you wanna prevent people from entering an email address into the name field?

    am trying to validate my users. when they create an account the system should send them an email address and make sure that the username entered is unique.
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    6
    Rep Power
    0
    Originally Posted by nonde
    am trying to validate my users. when they create an account the system should send them an email address and make sure that the username entered is unique.
    "
    <?php

    $query= mysql_query("SELECT * FROM visitors WHERE username=$_POST[username]");

    if (mysql_num_rows($query)>0);
    {
    die ("Sorry! This Username already exists!");
    }

    {
    $query= "INSERT INTO visitors (username,password,email,postcode)
    VALUES
    ('$_POST[username]','$_POST[password]','$_POST[email]','$_POST[postcode]')";
    $query = mysql_query($mysql,$query) or die(mysqli_error());

    }"

    ?>
  12. #7
  13. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,871
    Rep Power
    6351
    Alright Jacques, ready set go. This guy needs it.

    Comments on this post

    • DonR agrees : am awaiting the "Jacques hammer" to fall on this poor noob ;)
    • Northie agrees : ROFLMFAO
    • paulh1983 agrees : LOL..
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  14. #8
  15. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    Originally Posted by nonde
    am trying to validate my users. when they create an account the system should send them an email address and make sure that the username entered is unique.
    There are several issues with your code:

    You insert the user-defined POST parameters directly into the query string. This allows anybody to inject their own SQL commands and manipulate the query. In extreme cases, people can take over your whole server. See The 6 worst sins of security for further information.

    The next problem is that your code is very fragile and won't work if you have many requests at the same time. It's easy to see: User A and user B both request the username "foobar" at the same time, so you check if it's in use already. Since it probably isn't, you allow both users to register with that name. This results either in a duplicate name or a database error, depending on whether or not there's a UNIQUE constraint on name column.

    What to do? Well, it's actually pretty easy: Let your database system do the unique check. That's what it's made for. Set up a UNIQUE constraint if you haven't already. Then simply insert the row and see what the database system has to say. Either the query is successful, or you get a constraint violation. MySQL has error codes for that.

    PHP Code:
    <?php

    // put SQL error codes into constants to make them readable
    define('SQL_CONSTRAINT_VIOLATION''23');

    $db_options = array(
        
    PDO::ATTR_EMULATE_PREPARES => false                     // important! use actual prepared statements (default: emulate prepared statements)
        
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION           // throw exceptions on errors (default: stay silent)
        
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC      // fetch associative arrays (default: mixed arrays)
    );
    $database = new PDO('mysql:host=localhost;dbname=YOURDB;charset=utf8''YOURUSER''YOURPASSWORD'$db_options);    // important! specify the character encoding in the DSN string, don't use SET NAMES



    // create prepared statement to safely pass values to the query
    $insert_user_stmt $database->prepare('
        INSERT INTO
            visitors (username, password, email, postcode)
        VALUES
            (:username, :password, :email, :postcode)
    '
    );

    // try to insert user; if it fails, an exception will be thrown
    try {
        
    $insert_user_stmt->execute(array(
            
    ':username' => $_POST['username']
            , 
    ':password' => $_POST['password']
            , 
    ':email' => $_POST['email']
            , 
    ':postcode' => $_POST['postcode']
        ));
        echo 
    'User inserted!';
    } catch (
    PDOException $error) {
        
    // an error happened; check if it's because of the unique constraint
        
    if (substr($error->getCode(), 02) == SQL_CONSTRAINT_VIOLATION)
            echo 
    'This username already exists.';
        else
            throw 
    $error;    // some other error happened; just pass it on
    }
    You may not be familiar with some of those techniques, because many online "tutorials" still teach PHP like it was used in the 90s. But if you read up on prepared statements and play a bit with the code, you should understand what it does. Otherwise, just ask.

    Comments on this post

    • Strider64 agrees
    • Northie agrees
    Last edited by Jacques1; October 1st, 2013 at 04:53 PM.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    6
    Rep Power
    0
    thankx for the reply but this is too much for me
    am just beginning this staff. am looking for the basic validation not the security

    Comments on this post

    • Northie disagrees
  18. #10
  19. Mad Scientist
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2007
    Location
    North Yorkshire, UK
    Posts
    3,661
    Rep Power
    4123
    Originally Posted by nonde
    am looking for the basic validation not the security
    oh dear, if you think like this then you have no place in developing things like this

    Security is the most important part of development like this. Learn it now and learn it well. Don't forget to keep up with changes in it either.

    Sure, it slows down the process of "getting something working" but if its going to put on the internet for public use then it must be secure. A good mantra to have is to assume that all your users are malicious and every request is an attempted attack.

    Just because something works in the way you intended it to be used does not limit people to use it in other ways. Read Jacques six worst sins of security (linked to in a previous post) and take it on board

    Comments on this post

    • Jacques1 agrees
    I said I didn't like ORM!!! <?php $this->model->update($this->request->resources[0])->set($this->request->getData())->getData('count'); ?>

    PDO vs mysql_* functions: Find a Migration Guide Here

    [ Xeneco - T'interweb Development ] - [ Are you a Help Vampire? ] - [ Read The manual! ] - [ W3 methods - GET, POST, etc ] - [ Web Design Hell ]
  20. #11
  21. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    Originally Posted by nonde
    thankx for the reply but this is too much for me
    am just beginning this staff. am looking for the basic validation not the security
    Well, if you ever want to leave the world of localhost and put your code online, it has to be secure. No attacker will spare you just because you're new to PHP.

    Sure, you might first learn the wrong way, then unlearn everything and finally learn the right way. But wouldn't it make sense to get it right from the beginning?

    The problem is that you've used bad tutorials. People have taught you a lot of garbage and outdated stuff from the 90s. And now you're confused, because it's the first time you see code from the 21st century. I understand. But sooner or later, you have to deal with this problem. So why not do it right now? Throw away the bad tutorials, throw away the mysql_* functions and learn modern (and secure) PHP. There are excellent articles about how to use the "new" database extensions. Just give it a try. You'll see that it's no magic, it's just a bit different from what you've learned previously.

    If the error-handling is too much for you, then leave it out. Go back to your original approach of doing two separate queries. That's no correct approach, but it should work well enough.

    Step by step:

    At first, you obviously have to connect to the database. This is a bit different from the old mysql_connect(). I suggest you simply copy and paste the code and worry about it for now.

    PHP Code:
    $db_options = array(
        
    PDO::ATTR_EMULATE_PREPARES => false
        
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    );
    $database = new PDO('mysql:host=localhost;dbname=YOURDB;charset=utf8''YOURUSER''YOURPASSWORD'$db_options); 
    Of course you have to replace "YOURDB", "YOURUSER" etc. with the real data.

    Now you wanna check if the username is already taken. Since this involves an unsecure value (namely $_POST['username']), you need a way to securely pass it to the query. You cannot just insert the variable into the query string. The solution for this is to use a prepared statement.

    Prepared statements work like this: At first, you create a "query template" with a placeholder for every dynamic value you wanna insert. In your case, you have one value, so you need one placeholder. Then you send this query template to the database system. It will get parsed just like a normal query. But it can't be executed yet, because the actual values aren't known. That's the next step: You assign a value to each placeholder and send it to the database system. Now the whole thing can be executed like a normal query.

    So you have two steps: prepare and execute. It works very much like a PHP function. At first, you define the function with its parameters (prepare). And then you call the function, assigning values to its parameters (execute).

    The concrete code looks like this. Note that you can check the existence of a certain dataset directly in the query by using the EXISTS operator. There's no need to actually fetch the dataset and check it with PHP.

    PHP Code:
    /* ---- Is the username taken already? ---- */

    // create prepared statement with one placeholder for the username
    $user_exists_stmt $database->prepare('
        SELECT
            EXISTS (
                SELECT
                    1
                FROM
                    visitors
                WHERE
                    username = :username
            )
    '
    );

    // execute the prepared statement, passing $_POST['username'] to the placeholder
    $user_exists_stmt->execute(array(
        
    ':username' => $_POST['username']
    ));

    // fetch the result; it's either 0 (username doesn't exist) or 1 (username exists)
    $user_exists $user_exists_stmt->fetchColumn(); 
    Not exactly rocket science, right? Yeah, it's a bit longer than just stuffing the user variables into the query string. But this code actually works correctly at all times, no matter what bad or stupid people send to your webserver.

    All what's missing now is a second prepared statement for the INSERT query.

    Comments on this post

    • DonR agrees : off-topic, but, I appreciate you taking the time to explain the code, even if the OP doesn't want to use it, maybe some of us others can...thank you
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Dec 2004
    Posts
    2,974
    Rep Power
    375
    jacques while i appreciate you are trying to help them, If someone doesnt take your advice, dont spend too much time in trying to explain further. I keep seeing people not getting it and you having to explain further.
  24. #13
  25. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Oct 2009
    Location
    Nebraska, USA
    Posts
    867
    Rep Power
    275
    Originally Posted by paulh1983
    If someone doesnt take your advice, dont spend too much time in trying to explain further.
    I, for one, still in the beginning stages of learning PHP myself, appreciate whenever one of you other "higher ups" take the time to explain the code or explain what is being done wrong, so, I can learn from my mistakes (even if some of the OPs don't)...
    So, please keep up the great work you MODs and "more literate" programmers do to help us "beginners" and "mid-beginners" to gain the "proper" knowledge.
    Thank you.
  26. #14
  27. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    6
    Rep Power
    0
    Originally Posted by DonR
    I, for one, still in the beginning stages of learning PHP myself, appreciate whenever one of you other "higher ups" take the time to explain the code or explain what is being done wrong, so, I can learn from my mistakes (even if some of the OPs don't)...
    So, please keep up the great work you MODs and "more literate" programmers do to help us "beginners" and "mid-beginners" to gain the "proper" knowledge.
    Thank you.

    Jacques1
    thank you so much for taking the time to explain. its really appreciated. you right i need to catch up with the modern php.

    Comments on this post

    • DonR disagrees : what was the point of "quoting" my post when you are directing your reply to Jacques1?
  28. #15
  29. No Profile Picture
    Contributing User
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Dec 2004
    Posts
    2,974
    Rep Power
    375
    Originally Posted by DonR
    I, for one, still in the beginning stages of learning PHP myself, appreciate whenever one of you other "higher ups" take the time to explain the code or explain what is being done wrong, so, I can learn from my mistakes (even if some of the OPs don't)...
    So, please keep up the great work you MODs and "more literate" programmers do to help us "beginners" and "mid-beginners" to gain the "proper" knowledge.
    Thank you.
    Jacques helping and writing 2000 words essay and this guys throws it back saying he doesnt need it, jacques then expands further. This is what I don't like; appreciate the help but dont throw it back on his face. Jacques has helped us all and clearly an expert and I feel that he may get angry (more than already ) if people arent listening to him

IMN logo majestic logo threadwatch logo seochat tools logo