How should I handle the case in which a username is already in use?

Posted by idealmachine on Stack Overflow See other posts from Stack Overflow or by idealmachine
Published on 2011-01-01T07:05:39Z Indexed on 2011/01/01 7:54 UTC
Read the original article Hit count: 340

Filed under:
|
|

I'm a JavaScript programmer and new to PHP and MySQL (want to get into server-side coding). Because I'm trying to learn PHP by building a simple online game (more specifically, correspondence chess), I'm starting by implementing a simple user accounts system. Of course, user registration comes first.

What are the best practices for:

  • How I should handle the (likely) possibility that when a user tries to register, the username he has chosen is already in use, particularly when it comes to function return values?
    ($result === true is rather ugly, and I'm not sure whether checking the MySQL error code is the best way to do it either)

  • How to cleanly handle varying page titles?
    ($gPageTitle = '...'; require_once 'bgsheader.php'; is also rather ugly)

  • Anything else I'm doing wrong? In some ways, PHP is rather different from JavaScript...

Here is a (rather large) excerpt of the code I have written so far. Note that this is a work in progress and is missing security checks that I will add as my next step.

function addUser( $username, $password ) {
    global $gDB, $gPasswordSalt;

    $stmt = $gDB->prepare( 'INSERT INTO user(user_name, user_password, user_registration) VALUES(?, ?, NOW())' );
    $stmt || trigger_error( 'Failed to prepare statement: ' . htmlspecialchars( $gDB->error ) );

    $hashedPassword = hash_hmac( 'sha256', $password, $gPasswordSalt, true );
    $stmt->bind_param( 'ss', $username, $hashedPassword );
    if( $stmt->execute() ) {
        return true;
    } elseif( $stmt->errno == 1062) {
        return 'exists';
    } else {
        trigger_error( 'Failed to execute statement: ' . htmlspecialchars( $stmt->error ) );
    }
}

$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$result = addUser( $username, $password );

if( $result === true ) {
    $gPageTitle = 'Registration successful';
    require_once 'bgsheader.php';
    echo '<p>You have successfully registered as ' . htmlspecialchars( $username ) . ' on this site.</p>';
} elseif( $result == 'exists' ) {
    $gPageTitle = 'Username already taken';
    require_once 'bgsheader.php';
    echo '<p>Someone is already using the username you have chosen. Please try using another one instead.';
} else {
    trigger_error('This should never happen');
}


require_once 'bgsfooter.php';

© Stack Overflow or respective owner

Related posts about php

Related posts about error-handling