Jacob Tonna
Jacob Tonna

Reputation: 17

Check if username is taken

i need to check if the username is taken and if it is it wont allow the user to register it will redirect them to the register page where should i add the script to check if the username is taken alredy? or where can i get a script for this heres my script what i have sofar.

 <?php

// Check if he wants to register:
if (!empty($_POST[username]))
{
// Check if passwords match.
if ($_POST[password] != $_POST[password2])
    exit("Error - Passwords don't match. Please go back and try again.");

// Assign some variables.
$date = time (" d - m - Y ");
$ip = $_SERVER[REMOTE_ADDR];

require_once("connect.php");

// Register him.
$query = mysql_query("INSERT INTO members 
(username, fname, email, password, date, ip)
VALUES      ('$_POST[username]','$_POST[fname]','$_POST[email]','$_POST[password]','$date','$ip')")
or die ("Error - Couldn't register user.");

echo "Welcome $_POST[username]! You've been successfully reigstered!<br />
    You Will Be Redirected To Our Home Page Where U Can Login ";
exit();
}

?>

Upvotes: 0

Views: 1652

Answers (3)

Code-Source
Code-Source

Reputation: 2243

I did some change on your code to make it works and clean it.

<?php
// Check if he wants to register
// - Make sure that param exists
// - Check length 
if (isset($_POST['username']) && strlen($_POST['username']) > 0) {

    // Check if passwords match.
    // - Make sure that params exist
    // - Check length 
    // - Check matching
    if (!isset($_POST['password']) || 
        !isset($_POST['password2']) ||
        strlen($_POST['password']) === 0 || 
        $_POST['password'] !== $_POST['password2']) {
           die("Error - Passwords don't match. Please go back and try again.");
    }

    require_once("connect.php");

    // Set array of params
    $fields = array(
        'username' => $_POST['username'],
        'fname' => isset($_POST['fname']) ? $_POST['fname'] : '',
        'email' => isset($_POST['email']) ? $_POST['email'] : '',
        'password' => $_POST['password'],
        'date' => date("d-m-Y"),
        'ip' => $_SERVER[REMOTE_ADDR]
    );

    // Escape fields agains sql injection
    $fields = array_map('mysql_real_escape_string', $fields);

    // Check if member exists
    $exists = mysql_num_rows(mysql_query("SELECT * FROM members WHERE username='" . $fields['username'] . "'"));
    if ($exists === 0) {

        // Insert member in DB
        if (mysql_query("INSERT INTO `members` (`" . implode('`,`', array_keys($fields)) . "`) VALUES ('" . implode("','", array_values($fields)) . "')") !== false) {
            echo "Welcome" . $_POST['username'] . "! You've been successfully reigstered!<br />
            You Will Be Redirected To Our Home Page Where U Can Login ";
            exit();
        } else {
            die("Error - Couldn't register user.");
        }
    } else {
        die("Error - Member exists!");
    }
}
?>

Upvotes: 0

Mark Steudel
Mark Steudel

Reputation: 1682

I updated your code where I would probably check to see if username is taken. Like other folks have said read up on sql injection attacks and protect yourself.

<?php

// Check if he wants to register:
if (!empty($_POST[username])) {
// Check if passwords match.
    if ($_POST[password] != $_POST[password2])
        exit("Error - Passwords don't match. Please go back and try again.");

// Assign some variables.
    $date = time(" d - m - Y ");
    $ip = $_SERVER[REMOTE_ADDR];

    require_once("connect.php");

    // CHEK IF USERNAME IS VALID
    if (someFunctionThatChecksIfUsernameIsTaken($_POST['username'])) {
        // Register him.
        $query = mysql_query("INSERT INTO members 
        (username, fname, email, password, date, ip)
        VALUES      ('$_POST[username]','$_POST[fname]','$_POST[email]','$_POST[password]','$date','$ip')")
                or die("Error - Couldn't register user.");

        echo "Welcome $_POST[username]! You've been successfully reigstered!<br />
        You Will Be Redirected To Our Home Page Where U Can Login ";
        exit();
    } else {
        // redirect him back to the page and tell the user that the username is taken
    }
}
?>

Upvotes: 0

Majid Laissi
Majid Laissi

Reputation: 19788

You need to check the presence of your username first:

SELECT count(1) FROM members WHERE username = '$_POST[username]'

And then if the result is > 0 you throw a User already exists error.

Upvotes: 3

Related Questions