I have made a registration PHP file that runs through an authentication and connects to my database that I made in phpMyAdmin. The problem is, I can put in the same username without consequence and it adds to the database, so I could put; dogs as the username and then again put the same.
How can I make it so the user is told; that username already exists choose another one.
Here's my php so far;
Also please tell me where to insert it.
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query($query);
if ($result) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
} else {
?>
You should query the database before inserting any record (user) to users table.
Try the code below:
<?php
$username = mysql_real_escape_string( $username ); //Sql injection prevention
$existance = mysql_query("SELECT username FROM users WHERE username = '" . $username . "'");
if( !$existance ){
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query( $query );
if ( $result ) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
else{
//unsuccessful insertion
}
} else {
//the user existed already, choose another username
}
?>
Create an if-statement where you check if $username exists in the db. If it does, throw an error. If not, continue with the code.
Note
Your code is vulnerable to SQL-injection. Read this post: How can I prevent SQL injection in PHP?
Rewriting my entire answer to a working example. I'm going to assume your post variables are the same as mine: email, password, username
<?php
$errorMessage = "";
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$email1 = $_POST['email'];
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
$username = htmlspecialchars($username);
$connect = mysql_connect("localhost","DBuser", "DBpassword");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("DBName");
$results = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($row = mysql_fetch_array($results)) {
$kudots = $row['username']; }
if ($kudots != ""){
$errorMessage = "Username Already Taken";
$doNothing = 1;
}
$result = mysql_query("SELECT * FROM users WHERE email = '$email'");
while($row2 = mysql_fetch_array($results)) {
$kudots2 = $row2['email']; }
if ($kudots2 != ""){
$errorMessage = "Email Already in use";
$doNothing = 1;
}
//test to see if $errorMessage is blank
//if it is, then we can go ahead with the rest of the code
//if it's not, we can display the error
if ($errorMessage == "") {
$user_name = "DBUsername";
$pass_word = "DBPassword";
$database = "DBName";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$password = quote_smart($password, $db_handle);
$username = quote_smart($username, $db_handle);
if ($username1 == ""){
$errorMessage = "You need a username";
}
if ($password1 == ""){
$errorMessage = $errorMessage . "<br>You need a password.";
}
if (!(isset($_POST['email']))){
$errorMessage = $errorMessage . "<br>You need an email.";
}
$SQL = "SELECT * FROM users WHERE email = $email";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "email already exists";
$doNothing = 1;
}
if ($errorMessage == "") {
$SQL = "INSERT INTO users (email, username, password) VALUES ($email, $username, $password)";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['email'] = "$email1";
$_SESSION['password'] = "$password1";
header ("Location: myaccount.php");
else {
$errorMessage = "Database Not Found";
}
}
OK, now echo $errorMessage right below or above the form, to inform the user that the Email, or Username is taken. I'm pretty sure I have a duplicate function in here for the Email, but this code does work; disregard if somebody says it's vulnerable to SQL injection; this is a working EXAMPLE! If you want to do MySQL real escape string, just Google it. I had to rewrite a couple things because I don't want my full code on a public board, if for some odd reason this doesn't work; send me an eMail(canadezo121#gmail.com) and I'll send you the full page code. (Which WORKS!) This code will probably raise some concerns with other more professional coders, this example gives you a good logical viewpoint of what goes on and how it works. You can adjust it to MySQLi, PDO, etc as you get more familiar with PHP and MySQL.
1 you must verify if the username all ready exists in database (Select)
2 if not exists after you can insert the new user
Related
So below I have my php code, everything works fine and dandy except when the user logs in and is redirected to the restricted page. When a person signs up, they fill out their first name, email, and password. In the login page it only requires email and password. When they are redirected I want to only display their first name though. I have tried making the session = $result which should return the result of the sql query, but if I do that it doesn't even redirect to the restricted page. What am I doing wrong?
<?php
// DATABASE VARIABLES
$user_name = "";
$pass_word = "";
$database = "";
$server = "";
// CONNECTS TO DATABASE
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
// ACCOUNT INFORMATION
$email;
$password;
$num_rows = 0;
// IF SUBMIT IS CLICKED
if (isset($_POST['submit'])) {
// STORES INPUTS AS VARIABLES
$email = $_POST['email'];
$password = $_POST['password'];
// REMOVES HARMFUL CODE
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
if ($db_found) {
$SQL = "SELECT * FROM accounts WHERE email = '$email' AND password = '$password'";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = ?;
header ("Location: loggedin/account.php");
}
else {
session_start();
$_SESSION['login'] = '';
}
}
else {
}
}
?>
Here is what I would do.....
// DATABASE VARIABLES
$user_name = "";
$pass_word = "";
$database = "";
$server = "";
// CONNECTS TO DATABASE
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
// ACCOUNT INFORMATION
$email;
$password;
$num_rows = 0;
// IF SUBMIT IS CLICKED
if (isset($_POST['submit'])) {
// STORES INPUTS AS VARIABLES
$email = $_POST['email'];
$password = $_POST['password'];
// REMOVES HARMFUL CODE
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
if ($db_found) {
$SQL = "SELECT * FROM accounts WHERE email = '$email' AND password = '$password'";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
// Grab user name from db
$row = mysql_fetch_row($result);
if ($num_rows > 0) {
// Add to session variable
session_start();
$_SESSION['login'] = $row['username'];
header ("Location: loggedin/account.php");
}
else {
//Either exit or redirect to login failure page.
}
}
else {
This seems alright to me although I cant test at current.
Edit
You may want to have a read on using the Mysqli and PDO connection, it is slightly quicker and definitely more secure, just a suggestion if you have the time. Also prepared statements would definitely be more secure.
This is how I do Login... You must have an ID for each user in mysql and define
$_SESSION['user_id'] = $fetched_id;
and in loggedin/account.php page you can simply make this:
$user_id = $_SESSION['user_id'];
$query = mysql_query("SELECT `first_name` FROM `users` WHERE `id` = '{$user_id}'");
I would like to have a page in which a user, when logged in, can edit their username/password/email, but am having difficulty in understanding any way in which to do this easily; I am new to PHP and SQL. I know this version of SQL is deprecated, but I am not building this for security, so I am not concerned with SQL injection attacks at the moment.
This is my login code currently.
<?PHP
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
//==========================================
// ESCAPE DANGEROUS SQL CHARACTERS
//==========================================
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname = $_POST['username'];
$pword = $_POST['password'];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
//==========================================
// CONNECT TO THE LOCAL DATABASE
//==========================================
$user_name = "root";
$pass_word = "";
$database = "login";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$uname = quote_smart($uname, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM login WHERE L1 = $uname AND L2 = $pword";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
//====================================================
// CHECK TO SEE IF THE $result VARIABLE IS TRUE
//====================================================
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: Logged.php");
}
else {
echo "<script> alert('Invalid Login')</script>";
}
}
else {
echo "<script> alert('Invalid Login')</script>";
}
mysql_close($db_handle);
}
}
?>
This will then take you to a page called logged.php, which will contain forms for the user to enter in the new username, password, and email they want to use, but I don't know how to make it able to actually edit a database entry and, secondly, to edit the correct entry.
The database columns currently are ID, L1, L2 and Email. What am I doing incorrectly?
I have this code, it was originally in mysql() but since it's deprecated and obsolete well i decided to change. Something is clearly not working because when I execute it always says incorrect password/username although it is correct. Database works. Triple checked. Pardon me, i'm a noob at php. here:
<?php
//If the user is logged, we log him out
if(isset($_SESSION['username']))
{
//We log him out by deleting the username and userid sessions
unset($_SESSION['username'], $_SESSION['userid']);
?>
<div class="alert alert-info">You have been logged out securely.</div>
<?php
}
else
{
$ousername = '';
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password']))
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$escapePass = stripslashes($_POST['username']);
$escapeUser = $_POST['username'];
$ousername = stripslashes($_POST['username']);
$username = mysqli_real_escape_string($link, $escapePass);
$password = sha1(stripslashes($_POST['password']));
}
else
{
$username = mysqli_real_escape_string($link, $escapeUser);
$password = sha1($_POST['password']);
}
//We get the password of the user
$query = 'SELECT password, id FROM users WHERE username="'.$username.'" ';
$req = mysqli_query($link, $query);
$dn = mysqli_fetch_array($req);
print $reg;
//We compare the submited password and the real one, and we check if the user exists
if($dn['password']==$password and mysqli_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
?>
#Fred -ii- This:
if(get_magic_quotes_gpc())
{
$escapePass = stripslashes($_POST['username']);
$escapeUser = $_POST['username'];
$passescape = sha1($_POST['password']);
$passescape2 = sha1(stripslashes($_POST['password']));
$ousername = stripslashes($_POST['username']);
$username = mysqli_real_escape_string($link, $escapePass);
$password = mysqli_real_escape_string($link, $passescape2);
}
else
{
$username = mysqli_real_escape_string($link, $escapeUser);
$password = mysqli_real_escape_string($link, $passescape);
}
Just for a quick testing purpose, try this below which is a bare bones method.
You can then slowly build up sanitizing and troubleshoot from thereon.
<?php
$username = $_POST['username'];
$password = sha1($_POST['password']);
$link = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
$query = "SELECT password, id FROM users
WHERE username = '$username' AND password='$password'";
$result = mysqli_query($link, $query);
if(mysqli_num_rows($result) < 1)
{
echo 'Sorry, your username and/or password was incorrect.';
}
else
{
echo "Welcome!";
}
?>
Footnote: I noticed in your original code that you are using sessions.
I did not see session_start(); in your code, nor any mention of it.
This needs to be at the top of your code and inside all your files used,
which will be needed in order to access anything currently in $_SESSION
More on sessions can be found on the PHP.net Website.
http://www.php.net/session_start
I am currently building a signup script for my website. I new to the whole PHP-mySQL interaction bit. Anyway, this is the code I've gotten so far. The problem is that I had added some more code to check if the username already exists in the database, after the form submits it kicks to store.viddir.com/join/signup.php rather than store.viddir.com/login, like I had it. Any pros that can help a novice out? Many thanks
<?php
$submitted = $_POST["submitted"];
if($submitted == 'yes') {
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$userName = $_POST["userName"];
$password = $_POST["password"];
$confirmPassword = $_POST["confirmPassword"];
$eMail = $_POST["eMail"];
// Kill script if input fields are blank
if ($firstName == '' or $lastName == '' or $userName == '' or $password == '' or $confirmPassword == '' or $eMail == '')
{
die();
}
// Check if passwords match
if ($password != $confirmPassword)
{
die();
}
// Check if password is appropriat length
$passwordLength = strlen($password);
if ($passwordLength < 7 or $passwordLength >30) {
die();
}
/////////////////////////
// Connect to database //
/////////////////////////
$sqlserver = "localhost";
$sqluser = "XXXX";
$sqlpassword = "XXXXXX";
mysql_connect($sqlserver, $sqluser, $sqlpassword) or die(mysql_error());
mysql_select_db("store");
// Check database if username already exists
$newUserName = $userName;
$checkUserName = mysql_query("SELECT userName FROM userInfo WHERE userName = '$newUserName'");
if ($checkUserName) {
die();
}
//////////////////////////
// Insert into database //
//////////////////////////
// Signup time in Unix Epoch
$time = time();
// Human readable date
$date = date("F jS, Y g:i:s A");
$sql = "INSERT into userInfo (firstName, lastName, userName, password, eMail, time, date) VALUES ('$firstName', '$lastName', '$userName', '$password', '$eMail', '$time', '$date')";
//$sqlserver = "localhost";
//$sqluser = "XXXX";
//$sqlpassword = "XXXXXX";
//mysql_connect($sqlserver, $sqluser, $sqlpassword) or die(mysql_error());
//mysql_select_db("store");
mysql_query($sql) or die(mysql_error());
mysql_close();
header("Location: http://store.viddir.com/login");
exit;
}
?>
See mysql_num_rows. You should also look into using PDO or MySQLi
http://php.net/manual/en/function.mysql-num-rows.php
if (mysql_num_rows($query) > 0) {
echo "user already exists";
}
You should do a count in the mysql query and then check if the result is not equal to 0.
Example:
// Check database if username already exists
$newUserName = $userName;
$checkUserName = mysql_query("SELECT COUNT(userName) FROM userInfo WHERE userName = '$newUserName'");
if ( mysql_result($checkUserName, 0, 0) != 0 ) {
die();
}
After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;