Sending a Welcome Email after submitting form - php

Here is my sign_up.php code, I want users to receive a welcome email immediately after hitting the submit button, I have searched so many forums but they are not giving me what i need.
The user successfully signs up, and the details are stored in the database, but i also want to add a welcome mail feature such that the details will me sent to the email immediately after submitting the form
<?php
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password'], $_POST['passverif'], $_POST['email'], $_POST['avatar']) and $_POST['username']!='')
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$_POST['username'] = stripslashes($_POST['username']);
$_POST['password'] = stripslashes($_POST['password']);
$_POST['passverif'] = stripslashes($_POST['passverif']);
$_POST['email'] = stripslashes($_POST['email']);
$_POST['avatar'] = stripslashes($_POST['avatar']);
$_POST['mobile'] = stripslashes($_POST['mobile']);
}
//We check if the two passwords are identical
if($_POST['password']==$_POST['passverif'])
{
//We check if the password has 6 or more characters
if(strlen($_POST['password'])>=6)
{
//We check if the email form is valid
if(preg_match('#^(([a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+\.?)*[a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+)#(([a-z0-9-_]+\.?)*[a-z0-9-_]+)\.[a-z]{2,}$#i',$_POST['email']))
{
//We protect the variables
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$avatar = mysql_real_escape_string($_POST['avatar']);
$mobile = mysql_real_escape_string($_POST['mobile']);
//We check if there is no other user using the same username
$dn = mysql_num_rows(mysql_query('select id from users where username="'.$username.'"'));
if($dn==0)
{
//We count the number of users to give an ID to this one
$dn2 = mysql_num_rows(mysql_query('select id from users'));
$id = $dn2+1;
//We save the informations to the databse
if(mysql_query('insert into users(id, username, password, email, avatar, mobile, signup_date) values ('.$id.', "'.$username.'", "'.$password.'", "'.$email.'", "'.$avatar.'", "'.$mobile.'", "'.time().'")'))
{
//We dont display the form
$form = false;
//mail function
//mail end
?>
<div class="message">Your Registration was successful. Please login below<br />
Log in</div>
<?php
}
else
{
//Otherwise, we say that an error occured
$form = true;
$message = 'An error occurred while signing up.';
}
}
else
{
//Otherwise, we say the username is not available
$form = true;
$message = 'The username you want to use is not available, please choose another one.';
}
}
else
{
//Otherwise, we say the email is not valid
$form = true;
$message = 'The email you entered is not valid.';
}
}
else
{
//Otherwise, we say the password is too short
$form = true;
$message = 'Your password must contain at least 6 characters.';
}
}
else
{
//Otherwise, we say the passwords are not identical
$form = true;
$message = 'The passwords you entered are not identical.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
<div class="content">
<?php include('adverts.php'); ?>
<br />
<h1 style="color:#666;">New User Registration</h1>
<table class="message">
<form action="sign_up.php" method="post" class="message">
<tr>
<td>Username</td><td><input type="text" name="username" value="<?php if(isset($_POST['username'])){echo htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');} ?>" /></td>
</tr>
<tr>
<td>Password<span class="small">(6 characters min.)</span></td><td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Password<span class="small">(verification)</span></td><td><input type="password" name="passverif" /></td>
</tr>
<tr>
<td>Email</td><td><input type="text" name="email" value="<?php if(isset($_POST['email'])){echo htmlentities($_POST['email'], ENT_QUOTES, 'UTF-8');} ?>" /> </td>
</tr>
<tr>
<td>Gender<span class="small">(optional)</span></td><td><input type="text" name="avatar" value="<?php if(isset($_POST['avatar'])){echo htmlentities($_POST['avatar'], ENT_QUOTES, 'UTF-8');} ?>" /></td>
</tr>
<tr><td>Mobille</td><td><input type="text" name="mobile" value="<?php if(isset($_POST['mobile'])){echo htmlentities($_POST['mobile'], ENT_QUOTES, 'UTF-8');} ?>" /></td></tr>
<tr>
<td></td>
<td><input type="submit" value="Sign up" /></td>
</tr>
</form>
</table>
</div>
<?php
}
?>

on successful form submission you need to write code for your mail functionality
<?php
if(isset($_POST['submit'])){
$to = $_POST['email'];
$subject = $_POST['name'];
$message = $_POST['message'];
$from = "test#testcom";
$headers = "From:" . $from;
if(mail($to,$subject,$message,$headers))
{
echo "Mail Sent.";
}
else
{
echo "Something went wrong";
}
}
?>

The function for sending mail is mail()
add this mail($email,'Subject','Message_body'); after if(mysql_query('insert into users...
http://www.w3schools.com/php/php_mail.asp

just use the mail function and send the mail as shown below
<?php
$result = mysql_query('insert into users(id, username, password, email, avatar, mobile, signup_date) values ('.$id.', "'.$username.'", "'.$password.'", "'.$email.'", "'.$avatar.'", "'.$mobile.'", "'.time().'")');
if($result){
//We dont display the form
$form = false;
//mail function
mail("mail_address#mail.com",'Subject','Message_body');
//mail end
?>
<div class="message">Your Registration was successful. Please login below<br />
Log in</div>
<?php
}
?>

Try it user and admin will get mail
<?php
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password'], $_POST['passverif'], $_POST['email'], $_POST['avatar']) and $_POST['username']!='')
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$_POST['username'] = stripslashes($_POST['username']);
$_POST['password'] = stripslashes($_POST['password']);
$_POST['passverif'] = stripslashes($_POST['passverif']);
$_POST['email'] = stripslashes($_POST['email']);
$_POST['avatar'] = stripslashes($_POST['avatar']);
$_POST['mobile'] = stripslashes($_POST['mobile']);
}
//We check if the two passwords are identical
if($_POST['password']==$_POST['passverif'])
{
//We check if the password has 6 or more characters
if(strlen($_POST['password'])>=6)
{
//We check if the email form is valid
if(preg_match('#^(([a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+\.?)*[a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+)#(([a-z0-9-_]+\.?)*[a-z0-9-_]+)\.[a-z]{2,}$#i',$_POST['email']))
{
//We protect the variables
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$avatar = mysql_real_escape_string($_POST['avatar']);
$mobile = mysql_real_escape_string($_POST['mobile']);
//We check if there is no other user using the same username
$dn = mysql_num_rows(mysql_query('select id from users where username="'.$username.'"'));
if($dn==0)
{
//We count the number of users to give an ID to this one
$dn2 = mysql_num_rows(mysql_query('select id from users'));
$id = $dn2+1;
//We save the informations to the databse
if(mysql_query('insert into users(id, username, password, email, avatar, mobile, signup_date) values ('.$id.', "'.$username.'", "'.$password.'", "'.$email.'", "'.$avatar.'", "'.$mobile.'", "'.time().'")'))
{
//We dont display the form
$form = false;
//mail function
//mail end
$to = "$email";
$subject = "Welcome to";
$message = " Hi $username,<br /><br />
Thank you for signing up with us.<br />
Thanks <br />";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= 'From: <test#gmail.com>' . "\r\n";
$mail=mail($to,$subject,$message,$headers);
if($mail)
{
$to = "admin#gmail.com";
$subject = "Following Customer Signed Up";
$message = " $username,Customer is signed up with us,<br /><br />
Customer Details:<br />First Name:$firstname<br/>Last Name:$lastname<br/>Email:$email<br/>
Phone:$phone<br/>Zip Code:$zip<br/>
Thanks <br />";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= 'From: <'.$email.'>' . "\r\n";
$mail=mail($to,$subject,$message,$headers);
}
?>
<div class="message">Your Registration was successful. Please login below<br />
Log in</div>
<?php
}
else
{
//Otherwise, we say that an error occured
$form = true;
$message = 'An error occurred while signing up.';
}
}
else
{
//Otherwise, we say the username is not available
$form = true;
$message = 'The username you want to use is not available, please choose another one.';
}
}
else
{
//Otherwise, we say the email is not valid
$form = true;
$message = 'The email you entered is not valid.';
}
}
else
{
//Otherwise, we say the password is too short
$form = true;
$message = 'Your password must contain at least 6 characters.';
}
}
else
{
//Otherwise, we say the passwords are not identical
$form = true;
$message = 'The passwords you entered are not identical.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
<div class="content">
<?php include('adverts.php'); ?>
<br />
<h1 style="color:#666;">New User Registration</h1>
<table class="message">
<form action="sign_up.php" method="post" class="message">
<tr>
<td>Username</td><td><input type="text" name="username" value="<?php if(isset($_POST['username'])){echo htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');} ?>" /></td>
</tr>
<tr>
<td>Password<span class="small">(6 characters min.)</span></td><td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Password<span class="small">(verification)</span></td><td><input type="password" name="passverif" /></td>
</tr>
<tr>
<td>Email</td><td><input type="text" name="email" value="<?php if(isset($_POST['email'])){echo htmlentities($_POST['email'], ENT_QUOTES, 'UTF-8');} ?>" /> </td>
</tr>
<tr>
<td>Gender<span class="small">(optional)</span></td><td><input type="text" name="avatar" value="<?php if(isset($_POST['avatar'])){echo htmlentities($_POST['avatar'], ENT_QUOTES, 'UTF-8');} ?>" /></td>
</tr>
<tr><td>Mobille</td><td><input type="text" name="mobile" value="<?php if(isset($_POST['mobile'])){echo htmlentities($_POST['mobile'], ENT_QUOTES, 'UTF-8');} ?>" /></td></tr>
<tr>
<td></td>
<td><input type="submit" value="Sign up" /></td>
</tr>
</form>
</table>
</div>
<?php
}
?>

Thank you all for your help.
I have successfully added a simple mail function with the help you all have contributed, here is what i did:
I added
mail($email,'Subject','Message_body');
after
if(mysql_query('insert into users(id, username, password, email, avatar, signup_date) values ('.$id.', "'.$username.'", "'.$password.'", "'.$email.'", "'.$avatar.'", "'.time().'")'))
{
//We dont display the form
$form = false;
just like this:
mail("$email",'Welcome To Naijabloom','Dear user, <br /> Welcome to Naijabloom.com, you will start receiving mails from us to keep you updated. Remember to be active in our forums and invite your friends here. Thanks. <br /> Naijanloom Team.', 'info#naijabloom.com');
and it worked for me, thanks

Related

undefined index for validation

I am trying build a simple registration form with validation. When I leave a field blank and submit my form I keep getting this error undefined index email or undefined index password.For eg I fill in all fields except lastname I will get a notice saying email is undefined and if i fill all the fields I get username ,email and password is undefined. I googled it and the sugesstions i could get was isset , I tried using isset but it still does not work. Can anyone please help?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sign Up</title>
<style>
label{
width:100px;
float:left;
}
</style>
</head>
<body>
<?php
session_start();
$Firstname=isset($_SESSION['Firstname']);
$Lastname=isset($_SESSION['Lastname']);
$username=isset($_SESSION['username']);
$email=isset($_SESSION['email']);
$password=isset($_SESSION['password']);
if(isset($_SESSION['error']))
{
echo '<p>'.$_SESSION['error']['Firstname'].'</p>';
echo '<p>'.$_SESSION['error']['Lastname'].'</p>';
echo '<p>'.$_SESSION['error']['username'].'</p>';
echo '<p>'.$_SESSION['error']['email'].'</p>';
echo '<p>'.$_SESSION['error']['password'].'</p>';
unset($_SESSION['error']);
}
?>
<div class="signup_form">
<form action="registerUser.php" method="post" >
<p>
<label for="Firstname">First Name:</label>
<input name="Firstname" type="text" id="Firstname" size="30"/>
</p>
<p>
<label for="Lastname">Last Name:</label>
<input name="Firstname" type="text" id="Lastname" size="30"/>
</p>
<p>
<label for="username">User Name:</label>
<input name="username" type="text" id="username" size="30"/>
</p>
<p>
<label for="email">E-mail:</label>
<input name="email" type="text" id="email" size="30"/>
</p>
<p>
<label for="password">Password:</label>
<input name="password" type="password" id="password" size="30 "/>
</p>
<p>
<input name="submit" type="submit" value="Submit"/>
</p>
</form>
</div>
<p>Login</p>
</body>
</html>
Here is registeruser.php
<?php
session_start();
include('dbconnect.php');
if(isset($_POST['submit']))
{
//whether the username is blank
if($_POST['FirstName'] == '')
{
$_SESSION['error']['Firstname'] = " FirstName is required.";
}
if($_POST['LastName'] == '')
{
$_SESSION['error']['Lastname'] = " LastName is required.";
}
//whether the email is blank
if($_POST['email'] == '')
{
$_SESSION['error']['email'] = "E-mail is required.";
}
else
{
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$personcon=$conn;
$sql1 = "SELECT * FROM TBLUSERS WHERE email = '$email'";
$personinfo=oci_parse($personcon,$sql1);
oci_execute($personinfo);
oci_free_statement($personinfo);
if (oci_num_rows($personinfo) > 0)
{
$_SESSION['error']['email'] = "This Email is already used.";
}
}
else
{
//this error will set if the email format is not correct
$_SESSION['error']['email'] = "Your email is not valid.";
}
}
//whether the password is blank
if($_POST['password'] == '')
{
$_SESSION['error']['password'] = "Password is required.";
}
if($_POST['username'] == '')
{
$_SESSION['error']['username'] = "username is required.";
}
if(isset($_SESSION['error']))
{
header("Location: index.php");
exit;
}
else
{
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$email = $_POST['email'];
$username=$_POST['$username'];
$password = $_POST['password'];
$sql2 = "INSERT INTO TBLUSERS (FirstName,LastName,email, username,password) VALUES ('$FirstName', $LastName, '$email', '$username','$password')";
$personinfo2=oci_parse($personcon,$sql2);
oci_execute($personinfo2);
oci_free_statement($personinfo2);
if($personinfo2)
{
/* $from=praveen.mohan#students.mq.edu.au */
$to = $email;
$subject = "Confirmation from TutsforWeb to $username";
$header = "TutsforWeb: Confirmation from TutsforWeb";
$message = "Please click the link below to verify and activate your account. rn";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail)
{
echo "Your Confirmation link Has Been Sent To Your Email Address.";
}
else
{
echo "Cannot send Confirmation link to your e-mail address";
}
oci_close($personcon);
}
}
}
?>
When you do not fill a field, its index will not exist in the $_POST associative array. You need to check with isset whether it exists like this:
<?php
session_start();
include('dbconnect.php');
$_SESSION['error'] = array();
if(isset($_POST['submit'])) {
//whether the username is blank
if((!isset($_POST['FirstName'])) || ($_POST['FirstName'] == '')) {
$_SESSION['error']['Firstname'] = " FirstName is required.";
if((!isset($_POST['LastName'])) || ($_POST['LastName'] == '')) {
$_SESSION['error']['Lastname'] = " LastName is required.";
if((!isset($_POST['email'])) || ($_POST['email'] == '')) {
$_SESSION['error']['email'] = "E-mail is required.";
} else {
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email'])) {
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$personcon=$conn;
$sql1 = "SELECT * FROM TBLUSERS WHERE email = '$email'";
$personinfo=oci_parse($personcon,$sql1);
oci_execute($personinfo);
oci_free_statement($personinfo);
if (oci_num_rows($personinfo) > 0) {
$_SESSION['error']['email'] = "This Email is already used.";
}
} else {
//this error will set if the email format is not correct
$_SESSION['error']['email'] = "Your email is not valid.";
}
}
//whether the password is blank
if((!isset($_POST['password'])) || ($_POST['password'] == '')) {
$_SESSION['error']['password'] = "Password is required.";
}
if((!isset($_POST['username'])) || ($_POST['username'] == '')) {
$_SESSION['error']['username'] = "username is required.";
}
if(isset($_SESSION['error'])) {
header("Location: index.php");
exit;
} else {
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$email = $_POST['email'];
$username=$_POST['$username'];
$password = $_POST['password'];
$sql2 = "INSERT INTO TBLUSERS (FirstName,LastName,email, username,password) VALUES ('$FirstName', $LastName, '$email', '$username','$password')";
$personinfo2=oci_parse($personcon,$sql2);
oci_execute($personinfo2);
oci_free_statement($personinfo2);
if($personinfo2) {
/* $from=praveen.mohan#students.mq.edu.au */
$to = $email;
$subject = "Confirmation from TutsforWeb to $username";
$header = "TutsforWeb: Confirmation from TutsforWeb";
$message = "Please click the link below to verify and activate your account. rn";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail) {
echo "Your Confirmation link Has Been Sent To Your Email Address.";
} else {
echo "Cannot send Confirmation link to your e-mail address";
}
oci_close($personcon);
}
}
}
?>
For example
((!isset($_POST['FirstName'])) || ($_POST['FirstName'] == ''))
will be true if there is no 'FirstName' in $_POST or it is an empty string. The trick is that the second operand will not be checked if the first is true, preventing the problem you have mentioned in the question.
Further observations:
your code assumes that there is a $_SESSION['error'] element. You might get errors if this is not properly initialized
your code is vulnerable to SQL injection
your code is not properly structured, which makes it difficult to maintain
your code mixes up sql with php, which is not elegant
The first issue is that your HTML input names don't match the PHP names you expect.
if($_POST['FirstName'] == '') //Upper case N
While in the markup you use <input name = "Firstname" ... with lower case N
Another issue with the markup is two inputs are named Firstname:
<label for="Lastname">Last Name:</label>
<input name="Firstname" type="text" id="Lastname" size="30"/> <!--Firstname should be Lastname-->
Finally one more problem lies within the index.php file where you try to flash the session variable which comes back from the registerUser.php. Either there should be only one $SESSION["error"] or isset(SESSION["error"]["field"]) must be used just like with the $POST["field"] in registerUser.php.
The flashing code would look like this after the change:
if(isset($_SESSION['error']))
{
if (isset($_SESSION['error']['Firstname'])) echo '<p>'.$_SESSION['error']['Firstname'].'</p>';
if (isset($_SESSION['error']['Lastname'])) echo '<p>'.$_SESSION['error']['Lastname'].'</p>';
if (isset($_SESSION['error']['username'])) echo '<p>'.$_SESSION['error']['username'].'</p>';
if (isset($_SESSION['error']['email'])) echo '<p>'.$_SESSION['error']['email'].'</p>';
if (isset($_SESSION['error']['password'])) echo '<p>'.$_SESSION['error']['password'].'</p>';
unset($_SESSION['error']);
}
I would also suggest looking up a good resource on the topic. Login/Register systems are hard to get right for the first time.

Register.php redirected to a blank page

I am trying to create a registration page in PHP with MYSQL . My index.php page has a form which I have to fill in , and upon registration , it is supposed to show the status of registration , whether it is successful or not , and whether confirmation link is being sent to the email. However , when I click register , it redirects to register.php where nothings is being shown - all i see is a blank page no matter what info i key in. Furthermore , upon checking my table (user) in database (users) , I realized that no data is being input. My database connection is correct since I have verified it and i suspect that the error is in register.php . can anyone take a look at it and guide me on what I might be doing wrong? Thanks in advance.
my index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sign Up</title>
<style>
label{
width:100px;
float:left;
}
</style>
</head>
<body>
<?php
session_start();
if(isset($_SESSION['error']))
{
echo '<p>'.$_SESSION['error']['username'].'</p>';
echo '<p>'.$_SESSION['error']['email'].'</p>';
echo '<p>'.$_SESSION['error']['password'].'</p>';
echo '<p>'.$_SESSION['error']['mail_add'].'</p>';
unset($_SESSION['error']);
}
?>
<div class="signup_form">
<form action="register.php" method="post" >
<p>
<label for="username">User Name:</label>
<input name="username" type="text" id="username" size="30"/>
</p>
<p>
<label for="email">E-mail:</label>
<input name="email" type="text" id="email" size="30"/>
</p>
<p>
<label for="password">Password:</label>
<input name="password" type="password" id="password" size="30 "/>
</p>
<p>
<label for="mail_add">Mailing:</label>
<input name="mail_add" type="text" id="mail_add" size="30"/>
</p>
<p>
<input name="submit" type="submit" value="Submit"/>
</p>
</form>
</div>
</body>
</html>
My register.php
<?php
session_start();
include('configdb.php');
if(isset($_POST['submit']))
{
//whether the username is blank
if($_POST['username'] == '')
{
$_SESSION['error']['username'] = "User Name is required.";
}
if($_POST['mail_add'] == '')
{
$_SESSION['error']['mail_add'] = "Mailing address is required.";
}
//whether the email is blank
if($_POST['email'] == '')
{
$_SESSION['error']['email'] = "E-mail is required.";
}
else
{
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$sql1 = "SELECT * FROM user WHERE email = '$email'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
if (mysqli_num_rows($result1) > 0)
{
$_SESSION['error']['email'] = "This Email is already used.";
}
}
else
{
//this error will set if the email format is not correct
$_SESSION['error']['email'] = "Your email is not valid.";
}
}
//whether the password is blank
if($_POST['password'] == '')
{
$_SESSION['error']['password'] = "Password is required.";
}
//if the error exist, we will go to registration form
if(isset($_SESSION['error']))
{
header("Location: index.php");
exit;
}
else
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$mail_add = $_POST['mail_add'];
$com_code = md5(uniqid(rand()));
$sql2 = "INSERT INTO user (username, email, password, com_code , mail_add) VALUES ('$username', '$email', '$password', '$com_code', '$mail_add')";
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
if($result2)
{
$to = $email;
$subject = "Confirmation from TutsforWeb to $username";
$header = "TutsforWeb: Confirmation from TutsforWeb";
$message = "Please click the link below to verify and activate your account. rn";
$message .= "http://www.yourname.com/confirm.php?passkey=$com_code";
$sentmail = mail($to,$subject,$message,$header);
echo "Records finally inserted into table.";
if($sentmail)
{
echo "Your Confirmation link Has Been Sent To Your Email Address.";
}
else
{
echo "Cannot send Confirmation link to your e-mail address";
}
}
else {
echo "Cannot insert into table";
}
}
}
?>
Thanks in advance.
Try:
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error($mysqli));
Enjoy your code

email sending on php form registration

Can't seem to get thhis script work. Although registration part works fine and data gets inserted but shows error in result page:
Not found your email in our databaseCannot send Confirmation link to your e-mail address
Code:
<?php
$con=mysqli_connect("localhost","","");
if (!$con) { die("Database connection failed: " . mysqli_error());}
$db_select=mysqli_select_db($con, "");
if (!$db_select) { die("Database selection failed: " . mysqli_error());}
if (isset($_POST['register'])) {
$username = mysqli_real_escape_string($con,$_POST['user']);
$password1 = mysqli_real_escape_string($con,$_POST['pass1']);
$password2 = mysqli_real_escape_string($con,$_POST['pass2']);
$name = mysqli_real_escape_string($con,$_POST['name']);
$phone = mysqli_real_escape_string($con,$_POST['phone']);
$email = mysqli_real_escape_string($con,$_POST['email1']);
if(isset($_POST['country'])){ $country = $_POST['country'];}
if(isset($_POST['state'])){ $state = $_POST['state'];}
// Random confirmation code
$confirm_code=md5(uniqid(rand()));
/* Data Insertion & PASSWORD 1 = 2 CHECK */
if($password1==$password2 && !empty($username) && !empty($name) && !empty($phone) && !empty($email) && !empty($country) && !empty($state)){ /* IF PASSWORD1 IS THE SAME WITH PASSWORD2 */
/* INSERT QUERY */
$query = "INSERT INTO temp_users (confirm_code,username,password,name,phone,email,country,state) VALUES ('$confirm_code','$username','$password1','$name','$phone','$email','".$country."','".$state."')";
$result=mysqli_query($con, $query);
if ($result) {
$to = $email;
$subject = "Activate Vacation Rental Link";
// From
$header = "VacationByChoice <enquiry#craigburst.com>";
// message
$message = "Your Confirmation link \r\n";
$message.="Click on this link to activate your account \r\n";
$message.="https://craigburst.com/confirmation-link-validation.php?passkey=$confirm_code";
// send email
if(!mail($to, $subject, $message, $header)) {
echo "Cannot send Confirmation link to your e-mail address";
} else {
echo "Your Confirmation link Has Been Sent To Your Email Address.";}
} else {
echo "Not found your email in our database";}}}
?>
Form:
Username:<input type="text" name="user" maxlength="20" class="username" value="<?php echo $username; ?>" /><?php if (!empty($username) === false){echo '<font style="color:#FF0000">* Username</font>';
} else /* duplicate username Validation */ $check_user = ("SELECT username FROM temp_users WHERE username='$username'"); $run = mysqli_query($con,$check_user);
if(mysqli_num_rows($run)>0) {
echo "<font style='color:#FF0000'>* User Exists</font>";} ?>
Choose Password:<input type="password" maxlength="20" name="pass1" value="<?php echo $password1; ?>" /><?php if (!empty($password1) === false){
echo '<font style="color:#FF0000">* Password</font>';} ?>
Repeat Password:<input type="password" maxlength="20" name="pass2" value="<?php echo $password2; ?>" /><?php if (!empty($password2) === false){
echo '<font style="color:#FF0000">* Password</font>';}
elseif($password1!=$password2) { echo '<font style="color:#FF0000">* No Match</font>';} ?>
Full Name:<input type="text" maxlength="50" name="name" value="<?php echo $name; ?>" /><?php if (!empty($name) === false){
echo '<font style="color:#FF0000">* Name</font>';} ?>
Phone:<input type="text" maxlength="20" name="phone" value="<?php echo $phone; ?>" /><?php if (!empty($phone) === false){
echo '<font style="color:#FF0000">* Phone</font>';} ?>
Email:<input type="text" maxlength="50" name="email1" value="<?php echo $email; ?>" /><?php if (!empty($email) === false){
echo '<font style="color:#FF0000">* Email</font>';}
elseif (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
echo '<font style="color:#FF0000">* email';} else
/* duplicate Entry Validation */
$check_email = "SELECT email FROM temp_users WHERE email='$email'";
$run = mysqli_query($con,$check_email);
if(mysqli_num_rows($run)>0) {
echo "<font style='color:#FF0000'>* Email Exists</font><br/>";} ?>
Country:<select id="country" class="style" name="country">
<option>Select</option></select><?php if ($country=['select']){
echo '<font style="color:#FF0000">* Country</font>';} ?>
State/ Province:<select id="state" class="style" name="state"></select><?php if ($state=['select']){
echo '<font style="color:#FF0000">* State</font>';} ?>
<img src="captcha.php" alt="Captcha" /><input type="text" name="vercode" /><?php /* Captcha Validation */
if ($_POST['vercode']!=$_SESSION['vercode'] OR $_SESSION["vercode"]===''){
echo '<font style="color:#FF0000">* code</font>';} ?>
<input type="submit" name="register" value="Sign Up" />
Seeking help on this. Error reporting has been added already.
As my brother from another mother has suggested. You can try this.
Firstly set error reports on to help you debug this further.
ini_set('display_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
That should help you narrow down the cause of your errors.
Now on to your query. As you can see, you're setting your query like this:
$query = mysqli_query($con,"INSERT INTO temp_users (confirm_code,username,password,name,phone,email,country,state) VALUES ('$confirm_code','$username','$password1','$name','$phone','$email','$country','$state')");
$result=mysqli_query($query);
Which means, you're trying to run it like this: mysqli_query(mysqli_query('sql query in here')). That won't work. Try setting it up like this:
$query = "INSERT INTO temp_users (confirm_code,username,password,name,phone,email,country,state) VALUES ('$confirm_code','$username','$password1','$name','$phone','$email','$country','$state')";
$result=mysqli_query($con, $query);
You see how $query is the actual query string and $result runs the query through mysqli_query().
And now keeping in scope, you should do something like this with your code blocks for better management:
if ($result) {
$to = $email;
$subject = "Avtivate Vacation Rental Link";
// From
$header = "VacationByChoice <enquiry#craigburst.com>";
// message
$message = "Your Comfirmation link \r\n";
$message.="Click on this link to activate your account \r\n";
$message.="https://craigburst.com/confirmation-link-validation.php?passkey=$confirm_code";
// send email
if(!mail($to, $subject, $message, $header)) {
echo "Cannot send Confirmation link to your e-mail address";
} else {
echo "Your Confirmation link Has Been Sent To Your Email Address.";
}
} else {
echo "Not found your email in our database";
}
Notice how we removed the whole $sentmail and check mail directly with the if statement.
Does that help you out?
Notes
Just a few side notes; you have a typo here:
$subject="Avtivate Vacation Rental Link";
should be
$subject="Activate Vacation Rental Link";
and
$message="Your Comfirmation link \r\n";
should be
$message="Your Confirmation link \r\n";
Just had to be picky or Fred will beat me:P

How can I messages between separate sections of one page?

Basically, in the following code:
<?php
$hostname = '';
$username = '';
$password = '';
$dbn = '';
try {
$dbh = mysqli_connect($hostname , $username, $password ,$dbn);
//echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if (isset($_POST['formsubmitted'])) {
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$email1 = $_POST['email1'];
$password1 = $_POST['password1'];
$dob = $_POST['dob'];
$query_verify_email = "SELECT * FROM User WHERE Email = '$email1'";
$result_verify_email = mysqli_query($dbh, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
//$id= uniqid();
$query_insert_user = "INSERT INTO `User` ( `Name`, `Username`, `Email`, `Password`, `DOB`, `Activation`) VALUES ( '$fullname', '$username', '$email1', '$password1', '$dob', '$activation')";
$result_insert_user = mysqli_query($dbh, $query_insert_user);
if (!$result_insert_user) {
echo 'Query did not work ';
}
if (mysqli_affected_rows($dbh) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = " To activate your account, please click on this link:\n\n";
$message .= 'http://website' . '/active.php?email=' . urlencode($email1) . "&key=$activation";
mail($email1, 'Registration Confirmation', $message, 'From: a#b.com');
// Flush the buffered output.
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to '.$email1.' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >That email address has already been registered.
</div>';
}
mysqli_close($dbh);//Close the DB Connection
}// End of the main Submit conditional.
?>
<html>
<head>
</head>
<body>
<form name="f1" action="Main.php" method="post">
<p>Full name: <br/><input class="tb10" type="text" name="fullname" /></p>
<p>Username: <br/><input class="tb10" type="text" id="username" name="username" /><br/>
<p>Email: <br/><input class="tb10" type="text" id="email1" name="email1" /></p>
<p>Re-Enter Email: <br/><input class="tb10" type="text" name="email2" /></p> <br/>
<p>Password: <br/><input class="tb10" type="password" name="password1" /></p>
<p>Re-Enter Password: <br/><input class="tb10" type="password" name="password2" /></p><br/>
<p>Date of Birth: <br/><input class="tb10" type="text" name="dob" /></br><img src="img/calendar1.gif" alt="Calendar" onclick="displayCalendar(document.forms[0].dob,'yyyy/mm/dd',this)"/></p><br/>
<div class="submit">
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" value="Submit" class="button" />
</div>
</form>
</body>
</html>
The problem is I want to show the message that show up in the top (before the html part) in the body part. That means when the user completes the registration, the message will show up instead of the fields in the body section (Name, UserName, Email ,....).
To illustrate it:
If the registration is valid, I want the message:
Thank you for registering! A confirmation email has been sent to '.$email1.' Please click on the Activation Link to Activate your account
Appears in the body part (instead of the fields).
I hope you understand my explanation.
You set a variable, let it be regSuccess, in the php part to either true to false depending on whether user registration was successfull or not
Then in the html part, you checkk for the value of this variable in an if condition and output the corresponding html.
<?php
if($regSuccess == TRUE) {
?>
Thank you message
<?php
}
else
{ ?>
the input fields
<?php
} ?>
you could create a variable to store you error message instead of echo it directly.
And add a 'IF' case in the <body> for validation occur error, echo the error, otherwise print the register form.
Utilize a $_SESSION variable to indicate that the user successfully registered. You will start a session on your page and check if that value is set before doing anything else. If the variable exists, then display the activation message, otherwise provide the registration fields and continue with your existing code.
The reason for utilizing $_SESSION is to persist state information between page requests.
<?php
session_start();
if(isset($_SESSION['registered_email'])){
//Display message indicating user has already registered
echo 'Thank you for registering! A confirmation email has been sent to '. $_SESSION['registered_email'] .' Please click on the Activation Link to Activate your account';
}else{
// The rest of your code
...
// set session variable to indicate the registration was successful
$_SESSION['registered_email'] = $email1;
...
}
?>

Difficulty on retrieving email address on a register form with php and mysql

Hi im am trying to allow users to be members in a website. The code I have does not look to have any bugs or anything. When i try to register as a user it keeps show me an error that i haven't inserted the email address. The email field does exists in the database and i cannot find the problem.
PHP Script
$errorMsg = "";
// First we check to see if the form has been submitted
if (isset($_POST['username'])){
//Connect to the database through our include
include_once "connect_to_mysql.php";
// Filter the posted variables
$username = str_replace("[^A-Z a-z0-9]", "", $_POST['username']); // filter everything but numbers and letters
$country = str_replace("[^A-Z a-z0-9]", "", $_POST['country']); // filter everything but spaces, numbers, and letters
$county = str_replace("[^A-Z a-z0-9]", "", $_POST['county']); // filter everything but spaces, numbers, and letters
$city = str_replace("[^A-Z a-z0-9]", "", $_POST['city']); // filter everything but spaces, numbers, and letters
$accounttype = str_replace("[^a-z]", "", $_POST['accounttype']); // filter everything but lowercase letters
$email=str_replace( '/#/', '#', $email );
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = str_replace("[^A-Z a-z0-9]", "", $_POST['password']); // filter everything but numbers and letters
// Check to see if the user filled all fields with
// the "Required"(*) symbol next to them in the join form
// and print out to them what they have forgotten to put in
if((!$username) || (!$country) || (!$county) || (!$city) || (!$accounttype) || (!$email) || (!$password)){
$errorMsg = "You did not submit the following required information!<br /><br />";
if(!$username){
$errorMsg .= "--- User Name";
} else if(!$country){
$errorMsg .= "--- Country";
} else if(!$county){
$errorMsg .= "--- State";
} else if(!$city){
$errorMsg .= "--- City";
} else if(!$accounttype){
$errorMsg .= "--- Account Type";
} else if(!$email){
$errorMsg .= "--- Email Address";
} else if(!$password){
$errorMsg .= "--- Password";
}
} else {
// Database duplicate Fields Check
$sql_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$sql_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$username_check = mysql_num_rows($sql_username_check);
$email_check = mysql_num_rows($sql_email_check);
if ($username_check > 0){
$errorMsg = "<u>ERROR:</u><br />Your User Name is already in use inside our system. Please try another.";
} else if ($email_check > 0){
$errorMsg = "<u>ERROR:</u><br />Your Email address is already in use inside our system. Please try another.";
} else {
// Add MD5 Hash to the password variable
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, country, county, city, accounttype, email, password, signupdate)
VALUES('$username','$country','$state','$city','$accounttype','$email','$hashedPass', now())") or die (mysql_error());
// Get the inserted ID here to use in the activation email
$id = mysql_insert_id();
// Create directory(folder) to hold each user files(pics, MP3s, etc.)
mkdir("memberFiles/$id", 0755);
// Start assembly of Email Member the activation link
$to = "$email";
// Change this to your site admin email
$from = "info#chrysikourtina.x10.mx";
$subject = "Complete your registration";
//Begin HTML Email Message where you need to change the activation URL inside
$message = '<html>
<body bgcolor="#FFFFFF">
Hi ' . $username . ',
<br /><br />
You must complete this step to activate your account with us.
<br /><br />
Please click here to activate now >>
<a href="http://http://chrysikourtina.x10.mx/activation.php?id=' . $id . '">
ACTIVATE NOW</a>
<br /><br />
Your Login Data is as follows:
<br /><br />
E-mail Address: ' . $email . ' <br />
Password: ' . $password . '
<br /><br />
Thanks!
</body>
</html>';
// end of message
$headers = "From: $from\r\n";
$headers .= "Content-type: text/html\r\n";
$to = "$to";
// Finally send the activation email to the member
mail($to, $subject, $message, $headers);
// Then print a message to the browser for the joiner
print "<br /><br /><br /><h4>OK $firstname, one last step to verify your email identity:</h4><br />
We just sent an Activation link to: $email<br /><br />
<strong><font color=\"#990000\">Please check your email inbox in a moment</font></strong> to click on the Activation <br />
Link inside the message. After email activation you can log in.";
exit(); // Exit so the form and page does not display, just this success message
} // Close else after database duplicate field value checks
} // Close else after missing vars check
} //Close if $_POST
?>
HTML Form
<table width="600" align="center" cellpadding="4">
<tr>
<td width="7%">REGISTER AS A MEMBER HERE </td>
</tr>
</table>
<table width="600" align="center" cellpadding="5">
<form action="join_form.php" method="post" enctype="multipart/form-data">
<tr>
<td colspan="2"><font color="#FF0000"><?php echo "$errorMsg"; ?></font></td>
</tr>
<tr>
<td width="163"><div align="right">User Name:</div></td>
<td width="409"><input name="username" type="text" value="<?php echo "$username"; ?>" /></td>
</tr>
<tr>
<td><div align="right">Country:</div></td>
<td><select name="country">
<option value="<?php echo "$country"; ?>"><?php echo "$country"; ?></option>
<option value="Cyprus">Cyprus</option>
<option value="United Kingdom">United Kingdom</option>
</select></td>
</tr>
<tr>
<td><div align="right">County: </div></td>
<td><input name="county" type="text" value="<?php echo "$county"; ?>" /></td>
</tr>
<tr>
<td><div align="right">City: </div></td>
<td>
<input name="city" type="text" value="<?php echo "$city"; ?>" />
</td>
</tr>
<tr>
<td><div align="right">Account Type: </div></td>
<td><select name="accounttype">
<option value="<?php echo "$accounttype"; ?>"><?php echo "$accounttype"; ?></option>
<option value="a">Normal User</option>
<option value="b">Expert User</option>
<option value="c">Super User</option>
</select></td>
</tr>
<tr>
<td><div align="right">Email: </div></td>
<td><input name="email" type="text" id="<?php echo "$email"; ?>" value="<?php echo "$email"; ?>" />
</td>
</tr>
<tr>
<td><div align="right"> Password: </div></td>
<td><input name="password" type="password" value="<?php echo "$password"; ?>" />
<font size="-2" color="#006600">(letters or numbers only, no spaces no symbols)</font></td>
</tr>
<tr>
<td><div align="right"> Captcha: </div></td>
<td>Add Captcha Here for security</td>
</tr>
<tr>
<td><div align="right"></div></td>
<td><input type="submit" name="Submit" value="Submit Form" /></td>
</tr>
</form>
</table>
Error : You did not submit the following required information!
--- Email Address
All the other fields seem to be working fine!! If anyone has any idea of what is causing the problem please tell me!! Thanks
EDIT: IF you still get the same result the problem is with mysql_real_escape_string
because it's the only function which return FALSE.
You forgot to define the value of the email variable.
add this:
$email = $_POST['email'];
above this:
$email=str_replace( '/#/', '#', $email );
and add this below:
$email = mysql_real_escape_string(strip_tags(stripslashes($email)));
I believe you need to first get post value, then play with it. So consider the order change as below:
$email = stripslashes($_POST['email']);
$email=str_replace( '/#/', '#', $email );
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
Also a check in html file may work for further errors.
<?php $email = isset($_POST['email']) ? $_POST['email'] : ''; ?>
Hope this works.
Use echo to display your variable's values. See what $mail is when it is posted but before any filters are applied, and after each filter is applied. This can narrow down your search to where the error is actually occurring.

Categories