Here is the code
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$phone = $_POST['phone'];
$referral = $_POST['refer'];
$referred = false;
mysql_connect("localhost","username","password") or die (mysql_error());
mysql_select_db("database") or die ("Cannot connect to database");
$query = mysql_query("Select * from member");
while($row = mysql_fetch_array($query))
{
$table_users = $row['username'];
$table_email = $row['email'];
$table_phone = $row['phone'];
if($referral == $table_users)
{
$referred = true;
}
if($username == $table_users || $email == $table_email || $phone == $table_phone)
{
$bool = false;
}
}
if(($bool))
{
$username = mysql_real_escape_string($username);
mysql_query("INSERT INTO member (username, password, email, phone, refer) VALUES ('$username', '$password', '$email', '$phone', '$referral')");
if($referred)
{
$from="Sent from test";
$subject="New user referred.";
$message="A new user " . $username . " has been referred by " . $referral . "Please stay updated. ";
mail("mymail", $subject, $message, $from);
}
$_SESSION['login'] = true;
echo "Thank you for registering with us.You can login now to start earning.";
}
If the referral code field is left empty or it does not match any value in database it still sends
the mail. So, what is going on here? I have added some more code. I left a part of it earlier.
This statement if($referral == $table_users) doesn't look right. You have not set the $referral variable anywhere in your code.
Related
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
I'm using notepad++ and Godaddy's phpMyAdmin to host the server. The file does not display anything when posted and whenever I put it in a PHP code checker it tells me this:
Error: There is 1 more opening parenthesis '(' found This count is unaware if parenthesis are inside of a string)
and
Error: There is 1 more opening curly braces '{' found
This count is unaware if curly braces are inside of a string
Any help would be much appreciated.`
//Declaring them as variables
$username = $_POST["username"];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
//error handling
if((!$username) || (!$fname) || ($lname) || ($email) || ($pass1) || ($pass2))
{
$message = "please insert all fields in theform below!";
}
else
{
if($pass1 != $pass2)
{
$message = "Passwords do not match!"
}
}
else
//gathering the data
{
$username = preg_replace("#[^0-9a-z]#i","",$username);
$fname = preg_replace("#[^0-9a-z]#i","",$fname);
$lname = preg_replace("#[^0-9a-z]#i","",$lname);
$pass1 = sha1(#pass1);
$email = mysql_real_escape_string($email);
//check for dublicates
$user_query = mysql_query("SELECT username FROM members WHERE username ='$username' LIMIT 1") or die("Could not check username");
$count_username = mysql_num_rows($user_query);
$user_query = mysql_query("SELECT email FROM members WHERE username ='$email' LIMIT 1") or die("Could not check email");
$count_email = mysql_num_rows($email_query);
if($count_username > 0)
{
$message = "Your username is alread in use";
}
else if($count_email > 0)
{
$message = " Your email is alread in use";
}
else
//insert the memebers to database
{
$ip_address = $_SERVER['REMOTE_ADDR'];
$query = mysql_query("INSERT INTO members(username, firstname, lastname,email,password,ip_adress,sign_up_date)VALUES('$username','$fname','$lname','$email', '$pass1','$ip_address',now()")or die("could not insert");
$member_id = mysql_insert_id();
mkdir(,"users/$member_id",0755);
$message = "You have now been registered";
}
}
The issue is that your else statement was misplaced. I moved it after the if statement where you check that the passwords match.
//Declaring them as variables
$username = $_POST["username"];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
//error handling
if((!$username) || (!$fname) || ($lname) || ($email) || ($pass1) || ($pass2))
{
$message = "please insert all fields in theform below!";
}
else
{
if($pass1 != $pass2)
{
$message = "Passwords do not match!"
}
else
{
//All required fields are filled
//Paswords match
//gathering the data
$username = preg_replace("#[^0-9a-z]#i","",$username);
$fname = preg_replace("#[^0-9a-z]#i","",$fname);
$lname = preg_replace("#[^0-9a-z]#i","",$lname);
$pass1 = sha1(#pass1);
$email = mysql_real_escape_string($email);
//check for dublicates
$user_query = mysql_query("SELECT username FROM members WHERE username ='$username' LIMIT 1") or die("Could not check username");
$count_username = mysql_num_rows($user_query);
$user_query = mysql_query("SELECT email FROM members WHERE username ='$email' LIMIT 1") or die("Could not check email");
$count_email = mysql_num_rows($email_query);
if($count_username > 0)
{
$message = "Your username is alread in use";
}
else if($count_email > 0)
{
$message = " Your email is alread in use";
}
else
//insert the memebers to database
{
$ip_address = $_SERVER['REMOTE_ADDR'];
$query = mysql_query("INSERT INTO members(username, firstname, lastname,email,password,ip_adress,sign_up_date)VALUES('$username','$fname','$lname','$email', '$pass1','$ip_address',now()")or die("could not insert");
$member_id = mysql_insert_id();
mkdir(,"users/$member_id",0755);
$message = "You have now been registered";
}
}
}
I'm having a problem with redirecting a page in php.
<?php
include '../include/dbfunctions.php';
$email = $password = "";
$err = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['login']) && !empty($_POST['password'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$link = get_db_connection();
if (mysqli_connect_errno()) {
die(" Something went wrong ! ");
}
$user_email = mysqli_real_escape_string($link, $email);
$user_password = mysqli_real_escape_string($link, $password);
$query = "SELECT username FROM user WHERE user_email = '$user_email' AND user_password = SHA1('$user_password') AND user_active = '1';";
$data = mysqli_query($link, $query);
if (mysqli_num_rows($data) == 1) {
$row = mysqli_fetch_array($data);
$username = $row['username'];
mysqli_close($link);
if (!empty($username)) {
header('location:http://www.xxxxxxxxxxxxxx.be/login/dashboard.php');
exit();
}
} else {
$err = "Invalid combination of e-mail and password";
echo $err;
}
} else {
}
}
?>
I can't figure it out. If i fill in an invalid password or email, i get the error message. But when they are correct, nothing happens.
if (!empty($username)) {
header('location:http://www.yoursite.be/login/dashboard.php?error=error in login please try agine');
exit();
}
if (!empty($username)) {
header('location:http://www.xxxxxxxxxxxxxx.be/login/dashboard.php');
exit();}
$username might be empty.
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();
}
im a newbie in php and sql programming and can someone help me in my syntax , lately ive been creating this code to edit my user and write it on the database but it always gets an error in oldpassword and password , and it always says password didnt match even if i do it correctly the process , any help on me ? tnx
<?php
$update = strip_tags($_POST['update']);
$username = strtolower(strip_tags($_POST['username']));
$oldpassword = strip_tags($_POST['oldpassword']);
$newpassword = strip_tags($_POST['newpassword']);
$firstname = strip_tags($_POST['first']);
$lastname = strip_tags($_POST['last']);
$gender = strip_tags($_POST['gender']);
$address = strip_tags($_POST['address']);
$zipcode = strip_tags($_POST['zip']);
$contact = strip_tags($_POST['con']);
$email = strip_tags($_POST['mail']);
error_reporting(0);
if($update)
{
if($username&& $oldpassword && $newpassword && $firstname && $lastname && $address && $zipcode && $contact && $email)
{
$connect = mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("brightlights") or die(mysql_error());
$updatecheck = mysql_query("SELECT * FROM username FROM tb_user WHERE username='$username'");
$count = mysql_num_rows($updatecheck);
if($count<=1)
{
if($_SESSION['password']==($oldpassword))
{
mysql_query("UPDATE tb_user SET
username = '$username',
password = '$newpassword',
Firstname = '$firstname',
Lastname = '$lastname',
gender = '$gender',
address = '$address',
zipcode = '$zipcode',
contact = '$contact',
email = '$email'
WHERE username='".$_SESSION['username']."'");
$_SESSION['username'] = $username;
$_SESSION['password'] = $newpassword;
$_SESSION['Firstname'] = $firstname;
$_SESSION['Lastname'] = $lastname;
$_SESSION['gender'] = $gender;
$_SESSION['address'] = $address;
$_SESSION['zipcode'] = $zipcode;
$_SESSION['contact'] = $contact;
$_SESSION['email'] = $email;
session_write_close();
echo "Succesfully Updated!";
}else
echo "Password not match!";
}else
echo "Username already Taken!";
}else
echo "Please fill up all form!";
}
?>
if($_SESSION['password']==($oldpassword))
But I can't see session_start() after <?php
I think $_SESSION['password'] is an encrypted password that doesn't match. Please echo $_SESSION['password'] and $oldpassword and exit, and check their values.