I am trying to create an email validation form for my database but am having a number of issues. When i try and run the code below i get the error no database selected.
I also get an undefined variable error. I want the put the name of the user into my database under the username field, but apparently $name is an undefined variable. error on line xx undefined variablemysql_query("INSERT INTO registrations (username, password, email, hash) VALUES( '". mysql_real_escape_string($name) ."',.
I am using WAMP server. The name of the database is sitememberdetails, and the name of the
table i need the information put into is registrations. I am pretty new to this - Could anyone tell me how i would define the variable and how i select the db( even though it already appears to be selected?)
<?php
$host = "localhost";
$username = "";
$password = "";
$databasename = "sitememberdetails";
$email="xxxxxx#xxxxxxxx.xxx";
$connection = mysql_connect($host,$username,$password) or die
("Error: ".mysql_error());
mysql_select_db($databasename);("sitememberdetails") or
die(mysql_error());
if(isset($_POST['name']) && !empty($_POST['name']) AND
isset($_POST['email']) && !empty($_POST['email'])){
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']); }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-
z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$msg = 'The email you have entered is invalid, please try again.';
}else{
$msg = 'Your account has been made, <br /> please verify it
by clicking the activation link that has been send to
your email.';
}
$hash = md5( rand(0,1000) );
$password = rand(1000,5000);
mysql_query("INSERT INTO registrations (username, password,
email, hash) VALUES(
'". mysql_real_escape_string($name) ."',
'". mysql_real_escape_string(md5($password)) ."',
'". mysql_real_escape_string($email) ."',
'". mysql_real_escape_string($hash) ."') ") or
die(mysql_error());
$to = $email; // Send email to our user
$subject = 'Signup | Verification'; // Give the email a subject
$message = '
Thanks for signing up!
Your account has been created, you can login with the following
credentials after you have activated your account by pressing
the url below.
Username: '.$name.'
Password: '.$password.'
Please click this link to activate your account:
http://www.yourwebsite.com/verify.php?email='.$email.'&
hash='.$hash.'
';
$headers = 'From:noreply#yourwebsite.com' . "\r\n"; // Set from
headers
mail($to, $subject, $message, $headers); // Send our email
?>
try changing this code
mysql_select_db($databasename);("sitememberdetails") or
die(mysql_error());
to this
mysql_select_db($databasename) or die(mysql_error());
EOL;
if (database_connection) {
unset($undefined_variable_error)
} else {
echo $undefined_variable_error;
}
// Because mysql_real_escape_string needs an open mysql connection
check out this modified code:
<?php
$host = "localhost";
$username = "";
$password = "";
$databasename = "sitememberdetails";
$email="xxxxxx#xxxxxxxx.xxx";
$connection = mysql_connect($host,$username,$password) or die ("Error: ".mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$name = "";
if(isset($_POST['name']) && !empty($_POST['name']) AND
isset($_POST['email']) && !empty($_POST['email'])){
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']); }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$msg = 'The email you have entered is invalid, please try again.'; }
else {
$msg = 'Your account has been made, <br /> please verify it
by clicking the activation link that has been send to your email.';
}
$hash = md5( rand(0,1000) );
$password = rand(1000,5000);
mysql_query("INSERT INTO registrations (username, password,email, hash) VALUES(
'". mysql_real_escape_string($name) ."',
'". mysql_real_escape_string(md5($password)) ."',
'". mysql_real_escape_string($email) ."',
'". mysql_real_escape_string($hash) ."') ") or die(mysql_error());
$to = $email; // Send email to our user
$subject = 'Signup | Verification'; // Give the email a subject
$message = ' Thanks for signing up!
Your account has been created, you can login with the following
credentials after you have activated your account by pressing
the url below.
Username: '.$name.'
Password: '.$password.'
Please click this link to activate your account:
http://www.yourwebsite.com/verify.php?email='.$email.'&
hash='.$hash.'
';
$headers = 'From:noreply#yourwebsite.com' . "\r\n"; // Set from
mail($to, $subject, $message, $headers); // Send our email
?>
and i advise you to use PDO instead of mysql_ functions
Seems like the $name value isn't getting posted to the form. You're mysql_escaping the name variable if it is set and isn't empty, but what happens if the name variable isn't set at all? There are no checks for this so it continues until it gets to the INSERT statement and causes an error.
Look at example #1 here to select the db. You have a semicolon after ($databasename); which doesn't make sense.
Here's some revised code, using PDO instead of mysql_*. Let me know if this one works and we can address any issues from there.
<?php
$host = 'localhost';
$dbname = 'sitememberdetails';
$user = '';
$pass = '';
try
{
$DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['email']) && !empty($_POST['email']))
{
$name = $_POST['name'];
$email = $_POST['email'];
}
else
{
$name = 'No Name';
$email = 'No Email';
}
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email))
{
$msg = 'The email you have entered is invalid, please try again.';
}else{
$msg = 'Your account has been made, <br /> please verify it by clicking the activation link that has been send to your email.';
}
$hash = md5( rand(0,1000) );
$password = rand(1000,5000);
$query = "INSERT INTO registrations (username, password, email, hash) VALUES('?', '?', '?', '?')";
$sth = $DB->prepare($query);
//By using ?'s and prepare/execute, PDO will prevent SQL Injection for you!
$sth->execute(array($name, md5($password), $email, $hash));
$to = $email; // Send email to our user
$subject = 'Signup | Verification'; // Give the email a subject
$message = 'Thanks for signing up! Your account has been created,
you can login with the following credentials after you
have activated your account by pressing the url below.
Username: '.$name.'
Password: '.$password.'
Please click this link to activate your account:
http://www.yourwebsite.com/verify.php?email='.$email.'&
hash='.$hash;
$headers = 'From:noreply#yourwebsite.com' . "\r\n"; // Set from header
mail($to, $subject, $message, $headers); // Send our email
?>
Related
I currently have the following code: If that email is already registered then the user will be promoted with a message. However if the email is not already registered then they can register. When I run this code and register a user who has not already registered, they are still getting the alert that username already exists. I think it may be something with the brackets!
<?php
include ("dbConnect.php");
require 'libPassword.php';
function filter_email_header($email){
return preg_replace('/[\0\n\r\|\!\/\<\>\^\$\%\*\&]+/','',$email);
}
if(isset($_POST['submit'])){
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$telephone = $_POST['telephone'];
$address = $_POST['address'];
$medical_conditions = $_POST['medical_conditions'];
$dob = $_POST['dob'];
$email = $_POST['email'];
$password = $_POST['password'];
$last_login = date("Y-n-d");
$dbQuery=$db->prepare("SELECT email FROM customer where email > 0");
$dbParams = array('email'=>$email);
$dbQuery->execute($dbParams);
if ($dbQuery) {
$message = "username already exists";
echo "<script type='text/javascript'>alert('$message');</script>";
}//if
else{
$hashPassword = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
if($dbQuery->rowCount()==0){
$dbQuery=$db->prepare("INSERT INTO customer (forename, surname, telephone, address, medical_conditions, dob, email, password) VALUES (:forename, :surname, :telephone, :address, :medical_conditions, :dob, :email, :hashPassword)");
$dbParams = array('forename'=>$forename,'surname'=>$surname, 'telephone'=>$telephone, 'address'=>$address,'medical_conditions'=>$medical_conditions, 'dob'=>$dob, 'email'=>$email, 'hashPassword'=>$hashPassword);
$dbQuery->execute($dbParams);
if($dbQuery) {
header("Location: myProfile.php");
}//if
}//if
else{
echo('Please fill out all fields marked with *');
}//else2
}//else1
if(isset($email)){
$sender='jess#gymmembership.com';
$email = filter_email_header($email);
$headers = "From:". $sender;
$to = $email; // Send email to our user
$subject = 'Signup | Verification'; // Give the email a subject
$message = '
Thanks for signing up!
Here is your login details:
------------------------
Your email: '.$email.'
Password: '.$password.'
------------------------
You can now login to your account:
'; // Our message above including the link
$headers = 'From:gymmanagementsystem' . "\r\n"; // Set from headers
//mail($to, $subject, $message, $headers); // Send our email
$sent=mail($to, $subject, $message, $email);
}}
?>
Probably because you are checking if the query executed and not check whether or not you actually got a match. Check if your number of row are > 0.
if ($dbQuery) {
$message = "username already exists";
echo "<script type='text/javascript'>alert('$message');</script>";
}
Also pretty sure you might actually want to compare to an email like so.
"SELECT email FROM customer where email = :email"
I also wouldn't replace the unwanted character in the email it could be that they type "!" instead of "#" by accident and your email wouldn't be valid. I would suggest notifying that the email isn't valid and for what reason.
Hi I am sending confirmation e-mail after signup.How can the link be expired after a few seconds can anyone suggest me.Because if i click on the link after few days also it is getting activated.That should not be happen.Here is my code:
<?php
session_start();
$sessionCaptcha = $_SESSION['vercode'];
$inputStream = file_get_contents("php://input");
$data = json_decode($inputStream);
$connection = mysql_connect("localhost", "enjoytax_account", "account") or die(mysql_error());
$db = mysql_select_db("enjoytax_accounting", $connection);
if($db)
{
$confirm_code=md5(uniqid(rand()));
$username = $data->username;
$email = $data->email;
$password = md5($data->password);
$confirmpassword = md5($data->confirmpassword);
$mobileno = $data->mobileno;
$captcha=$data->captcha;
$check=mysql_query("select email from register where email = '$email'");
$num_rows = mysql_num_rows($check);
if ($num_rows == 0)
{
if($captcha == $sessionCaptcha)
{
$query = mysql_query("insert into register(username,email, password, repassword,mobile,confirm_code) values ('$username','$email', '$password' , '$confirmpassword', '$mobileno','$confirm_code')");
if ($query)
{
$from .= 'info#mail.com' . "\r\n\r\n";
$to = $data->email;
$subject="Your confirmation link here";
$message.="Click on this link to activate your account \r\n";
$message.="http://www.example.com/model/confirmation.php?email=$email&passkey=$confirm_code";
$success = mail($to, $subject, $message);
$successJson='{"success":"We have sent a verification email ' .
'to your email id '.$email.', please check your ' .
'Inbox and verify your email in order to proceed further."}';
print_r($successJson);
}else{
$failureJson='{"error":"We are encountering some issue. Please try after some time."}';
print_r($failureJson);
}
}else{
$failureJson='{"error":"Please Enter Correct Captcha."}';
print_r($failureJson);
}
}else{
$failureJson='{"error":"Email-Id already Exists."}';
print_r($failureJson);
}
}
?>
I have not tested the code but this might help you.
session_start();
if ($query)
{
$from .= 'info#mail.com' . "\r\n\r\n";
$to = $data->email;
$subject="Your confirmation link here";
$message.="Click on this link to activate your account \r\n";
$message.="http://www.example.com/model/confirmation.php?email=$email&passkey=$confirm_code";
$success = mail($to, $subject, $message);
$successJson='{"success":"We have sent a verification email ' .
'to your email id '.$email.', please check your ' .
'Inbox and verify your email in order to proceed further."}';
$_SESSION['now'] = date('i:s');
$now =date('Y-m-d H:i:s');
$futureDate = $now+(60*5);
$formatDate = date("Y-m-d H:i:s", $futureDate);
if($_SESSION['now'] > $formatDate)
{
$failureJson='{"error":"We are encountering some issue. Please try after some time."}';
print_r($failureJson);
}
}
else
{
echo " Query Not Executed";
}
Hi actually I am new to json as I implemented the code for sending Emails in php now I need to integrate with json can anyone help me regrading this? Thanks In Advance.
This is my code:
<?php
session_start();
$inputStream = file_get_contents("php://input");
$data = json_decode($inputStream);
$confirm_code=md5(uniqid(rand()));
$username = $data->username;
$email = $data->email;
$password = $data->password;
$confirmpassword = $data->confirmpassword;
$mobileno = $data->mobileno;
$connection = mysql_connect("localhost", "accou", "accountant") or die(mysql_error());
$db = mysql_select_db("accountant", $connection);
$query = mysql_query("insert into register(username,email, password, repassword,mobile,confirm_code) values ('$username','$email', '$password' , '$confirmpassword', '$mobileno','$confirm_code')");
if ($query) {
$to = $_POST['email'];
$from .= 'mail#gmail.com' . "\r\n\r\n";
$subject="Your confirmation link here";
$message.="Click on this link to activate your account \r\n";
$message.="http://web.com/accountant/controller/confirmation.php?passkey=$confirm_code";
$success = mail($to, $subject, $message);
$successJson='{"success":"We have sent a verification email ' .
'to your email id '.$email.', please check your ' .
'Inbox and verify your email in order to proceed further."}';
print_r($successJson);
}else{
$failureJson='{"error":"We are encountering some issue. Please try after some time."}';
print_r($failureJson);
}
?>
Actually the data is inserted into the database but the email sending is not working can any one help me this?
Instead of writing the json string yourself, why not encode array into json.
$jsonObj = array("success" => "success text");
print_r(json_encode($jsonObj));
I need to send an email to a new user and myself when they register an account. I need to know how to it send through my admin email instead of the weird email address that the GoDaddy server uses to send it.
Here's my PHP code:
<?php
require_once('recaptchalib.php');
$privatekey = "privatekey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
die ("reCAPTCHA was wrong, try again!");
} else {
mysql_connect("host", "username", "password");
mysql_select_db("database");
$hash = sha1(rand (0,1000) );
$name = $_POST['name'];
$bmonth = $_POST['month'];
$bday = $_POST['day'];
$byear = $_POST['year'];
$sq = $_POST['security_q'];
$sq_ans = sha1($_POST['security_q_ans']);
$email = $_POST['email'];
$pass = sha1($_POST['pass']);
$insert_query = "INSERT INTO users (account_act_hash, name, bmonth, bday, byear, securityq, securityq_ans, email, password) VALUES ('$hash','$name','$bmonth','$bday','$byear','$sq','$sq_ans','$email','$pass')";
$insertion_result = mysql_query($insert_query);
if($insertion_result) {
$to = "my admin email";
$subject = "New account created";
$name = $_POST['name'];
$bmonth = $_POST['month'];
$bday = $_POST['day'];
$byear = $_POST['year'];
$email = $_POST['email'];
$ip = $_SERVER['REMOTE_ADDR'];
$message = 'EMAIL
Here is the account info.
Name: $name
Birthday: $bmonth-$bday-$byear
Email: $email
Registration IP Address: $ip
'
$header = "A new account has been created.";
}
if($_POST){
mail($to, $subject, $message, $header);
}
}
?>
<?php
$to2 = $_POST['email'];
$subject2 = "Activate Your Account";
$email2 = $_POST['email'];
$message2 = '
Thanks for registering an account!
Your account has been created and can be used when you activate your account by clicking the below link!
------------------------------------------------------------------------
Email: '.$email2.'
------------------------------------------------------------------------
Please click this link to activate your account:
https://www.mysite.com/activation.php?email='.$email2.'&account_act_hash='.$hash.'
';
if($_POST) {
mail($to2, $subject2, $message2);
}
?>
Directly from the mail doc page you need to specify from in the header:
// Additional headers
$headers .= 'From: Birthday Reminder <birthday#example.com>' . "\r\n";
You are getting a _ weird email address_ because you have not specified who the email should be coming from.
You have a bunch of additional problems:
HEREDOC
I'm assuming this is what you were trying to do
$message = <<<EMAIL
Here is the account info.
Name: $name
Birthday: $bmonth-$bday-$byear
Email: $email
Registration IP Address: $ip
EMAIL;
MySQL
mysql_* functions are deprecated, read the read box.
This will also lead to don't trust user input, prepared statements are going to be your friend.
Misc
When using double quotes, use curly braces with your variables:
$foo = 'test';
echo "This a {$foo}!"; // This is a test!
In this case die(), is a very harsh way to end a script in terms of user experience.
I would like an email sent to me if a someone has logged into the database. My config to connect and log in is below.
<?php
session_start();
require_once('connect.php');
// Retrieve username and password from database according to user's input
$input_username = mysql_real_escape_string($_POST['username']);
$login = mysql_query("SELECT * FROM user WHERE username = '".$input_username."'" );
// Check username and password match
$row = mysql_fetch_array($login);
if (mysql_num_rows($login)) {
if($row['password'] === md5($_POST['password'])){
$_SESSION['username'] = $_POST['username']; // store in session
$sql = "UPDATE user SET logindate = NOW() WHERE username = '" . mysql_real_escape_string($_SESSION['username']) . "'";
mysql_query($sql) or die("Error in SQL: " . mysql_error());
}
else{
// Invalid login
echo header('Location: loginerror.php');
exit;
}
?>
You can simply send mails with the PHP mail function.
You may want to add it like this, if you want to recieve an email every time a user logged in:
if ($rowcount == 1) {
$_SESSION['username'] = $_POST['username'];
$headers = "From:Me <no-reply#example.com>\r\n";
$headers .= "Reply-To: no-reply#example.com\r\n";
$email_to = "your#emailadress.tld";
$subject = "Someone logged in!";
$message = "User ".$_POST['username']." logged in!";
mail($email_to, $subject, $message, $headers);
header("Location: securedpage.php");
}
To check whether the mail function was successful or not you can use:
if(mail($email_to, $subject, $message, $headers)) {
// mail function was successful
} else {
// error; mail function was NOT successful
}
Edit:
Just a note: You do a query twice and in the second one you don't use escaped data. You should remove your first one and change the second one to the code below. Also use mysql_real_escape string for the password:
$input_password = mysql_real_escape_string($_POST['password']);
$login = mysql_query("SELECT * FROM tbuser WHERE (username = '" . $input_username . "') AND (password = '" . md5($input_password) . "')",$db);