I am trying to make registration page for employees.
Once Employee register activation link should send to admin email and once admin click on that link Employee should get activated. and message should send to employee email that he can now login to his account... So far i write a code to store employee details in the database, and to send message in admin email heirs my code.
<?php
#database coding
if(!empty($_POST['txtfstname']) && !empty($_POST['txtlstname']) && !empty($_POST['txtemail']) && !empty($_POST['txtempno']))
{
$con=mysqli_connect("servername","username",'password',"database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['txtfstname']);
$lastname = mysqli_real_escape_string($con, $_POST['txtlstname']);
$empno = mysqli_real_escape_string($con, $_POST['txtempno']);
$pass = substr(hash('sha256', mt_rand()), 0, 50);
$email = mysqli_real_escape_string($con, $_POST['txtemail']);
$email_code = md5($_POST['txtfstname'] + microtime());
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
}
else
{
$sql="INSERT INTO empreg (first_name, last_name, email, emp_no, password, email_code)
VALUES ('$firstname', '$lastname','$email','$empno','$pass','$email_code')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
mysqli_close($con);
#email Coding
# It's best to just make sure each element isn't empty, using the empty() function.
# Note that if a field is not set, it is NULL, which is consdered empty, so there
# is no need to use the isset() function as well.
$firstname = trim(stripslashes(htmlspecialchars($_POST['txtfstname'])));
$lastname = trim(stripslashes(htmlspecialchars($_POST['txtlstname'])));
$email = trim(stripslashes(htmlspecialchars($_POST['txtemail'])));
$ip = $_SERVER['REMOTE_ADDR'];
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
{
# Return Error - Invalid Email
$msg = 'The email you have entered is invalid, please try again.';
}
else
{
# Sending the Email Message
# I moved this into the else clause. By putting it outside it was getting
# sent even if the email was invalid, which isn't exactly a good idea :)
$to = 'adminemail#something.com'; // Send email to receipient
$subject = 'Employee Registration'; // Give the email a subject
$message = 'From: ' . $firstname . "\r\r\n" . $lastname . "\r\r\r\n" . 'IP Address: ' . $ip; // Our message above including who sent it
$message_body .= "Please click on link to activate Employee \n\n email=$email $email_code ";
# Here I am capturing the return value of the mail() function so that I
# can check if it was actually successful. Just because the function is
# executed does not mean the email was sent. The return value tells us
# whether it was or not.
$success = mail($to,$subject,$message_body); // Send our email
if($success)
{
# The email was sent successfully!
$msg = 'Thank you for your message.';
}
else
{
# Email failed to send.
$msg = 'An error occured. The mail could not be sent.';
}
}
}
else if (!isset($_POST['submit']))
{
# If the form hasn't been submitted yet, then do nothing. Do not prompt to enter a name just yet.
}
# One of the fields was empty. This finds out which one and creates a message
# to indicate which it was.
else
{
$msg = "*";
if(empty($_POST['txtfstname']))
{
$msg .= "Please enter your first name";
}
elseif(empty($_POST['txtlstname']))
{
$msg .= "Please enter your last name";
}
elseif(empty($_POST['txtemail']))
{
$msg .= "Please enter your email";
}
else
{
$msg .= "Please enter your employee number";
}
}
?>
<form id="contact" class="form" action="" method="post" name="contact"><strong>Employee Registration</strong>
<em>Please enter the following information and submit. Once the administrator approves your registration, you will receive a confirmation email with login details.</em>
<p><?php echo $msg ?></p>
<table>
<tbody>
<tr>
<td>First Name:</td>
<td><input id="name" class="required" name="txtfstname" type="text" value="<?php echo $_POST['txtfstname']; ?>" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input id="name" class="required" name="txtlstname" type="text" value="<?php echo $_POST['txtlstname']; ?>" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input id="name" class="required" name="txtemail" type="text" value="<?php echo $_POST['txtemail']; ?>" /></td>
</tr>
<tr>
<td>Employee No:</td>
<td><input id="name" class="required" name="txtempno" type="text" value="<?php echo $_POST['txtempno']; ?>" /></td>
</tr>
<tr>
<td><input name="submit" type="submit" value="Send" /></td>
</tr>
</tbody>
</table>
</form>
here is my database columns.
ID ,
first_name,
last_name,
email,
emp_no,
password,
status,
email_code
now i want few things heir which i am not able to figure it out
1. how to update status form 0 to 1 when admin click activation link in email
2. how to send email to employees that he is activated and now can login to his account when admin activate employee.
3. when employee register mail send to admin is getting inside SPAM folder. but i want it inside Inbox. what to do for that.
Any help is appreciable thanks in advance.
Ok, so, basically click the link, redirect this way:
The $user variable must be having the username of the user who is getting their account activated.
Activate
So, in the activate.php:
<?php
if(isset($_GET['user']) && strlen($_GET['user']) > 0) {
// Update the users activated status from 0 to 1 by running a query.
// Mail to the employee of his account activation
} else {
// No user selected.
}
To resolve the issue of the Mail being received in Spam folder, save the email to your contacts/unblock that email and it will be received in the Inbox.
I am not really experienced in PHP, but I have sent emails before using the mail() function.
To learn more about these you can look on:
W3Schools
Php Documentation
I hope this helps you :)
Related
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
The following is a "forgot password" script I have on my site. I have one MYSQL table where I store the email addresses of users. It is called 'members' and has 2 columns: 'user' (users' email addresses) and 'pass' (their passwords).
The email address adamjwilkins1604#gmail.com exists in the members table. When I input this email address in the forgot password form, I get this error. I am having a lot of trouble debugging this.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#gmail.com' at line 1
Forgot password script:
<?php // forgot_password.php
include_once 'header.php';
if (isset($_POST['submitted']))
{ // Handle the form.
if (empty($_POST['email']))
{
$uid = FALSE;
echo 'You forgot to enter your registered email address!';
}
else
{
// Check for the existence of the inputted email address.
$email = trim(sanitizeString($_POST['email']));
$result = queryMysql("SELECT user FROM members WHERE user='$email'");
if (mysql_num_rows($result) == 1)
{
// Retrieve the user's email address
list($uid) = mysql_fetch_array ($result, MYSQL_NUM);
}
else
{
echo '<p><font color="red" size="+1">The submitted email address does not match those on file!</font></p>';
$uid = FALSE;
}
}
if ($uid)
{
$p = substr(md5(uniqid(rand(),1)),3,10);
$result = queryMysql("UPDATE members SET pass=SHA('$p') WHERE user = $uid");
if (mysql_affected_rows() == 1)
{
// If it ran OK, send an email.
$email = trim(sanitizeString($_POST['email']));
$body = "Your password has been temporarily changed to '$p'. Please log in using this password and your username.";
mail ($email, 'Your temporary password.', $body, 'From: admin#mywebsite.com');
echo '<h3>Your password has been changed. You will receive the new, temporary password at the email address with which you registered. Once you have logged in with this password, you may change it by clicking on the "change password" link.</h3>';
mysql_close(); // Close the database connection.
}
else
{
// If it did not run OK.
echo '<p><font color="red" size="+1">Your password could not be changed due to a system error. We apologize for any inconvenience.</font></p>';
}
}
else // Failed the validation test.
{
echo '<p><font color="red" size="+1">Please try again.</font></p>';
}
} // End of the main Submit conditional.
?>
<h1>Reset Your Password</h1>
<p>Enter your email address below and your password will be reset.</p>
<form action="forgot_password.php" method="post">
<fieldset>
<p><b>Your registered email address:</b> <input type="text" name="email" size="20" maxlength="40" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Reset My Password" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
</div>
You forgot to quote $uid in your UPDATE statement. And you forgot to escape it as well.
Below is my code for register.php on my website. This code allows the user to register for my website, creating a MySQL entry for username, email, password, etc. on clicking the submit button.
The button is named "reg" and uses a $_POST. Upon clicking the submit button the PHP code runs through multiple if statements to ensure the information the user entered is valid and does not preexist.
If a user exists, or an error is made in submission it sets PHP variable $errormessage and is supposed to echo it out. Right now, my SUBMIT button does not act like it is being pressed. No error messages, no SQL row is inserted, nothing.
<?php
if( $_POST['reg']){
/* Make sure values are correct and valid */
$getuser = $_POST['user'];
$getemail = $_POST['email'];
$getpass = $_POST['password'];
$getrepass = $_POST['retypepassword'];
/* Check to see if username entererd */
if($getuser){
/* Check to see if email entererd */
if($getemail){
/* Check to see if password entererd */
if($getpass){
/* Check to see if retyped password entererd */
if($getrepass){
/* Check to see if passwords are the EXACT same */
if($getpass === $getrepass){
/* Check to see if VALID email is entered */
if( (strlen($getemail) >= 7) &&
(strstr($getemail, "#")) &&
(strstr($getemail, ".")) ){
/* Email is valid mysql query */
require ("./connect.php");
$query = mysql_query("SELECT * FROM users WHERE username ='$getuser'");
/* If mysql returns zero, the user does not exist. */
$numrows = mysql_num_rows($query);
/* Check if email exists */
if($numrows == 0) {
$query = mysql_query("SELECT * FROM users WHERE email ='$getemail'");
$numrows = mysql_num_rows($query);
if($numrows == 0){
$date = date("F d, Y");
$code = md5(rand());
mysql_query("INSERT INTO users VALUES ('', '$getuser', '$getpass', '$getemail', '0', '$code', '$date')");
$query = mysql_query ("SELECT ALL * FROM users WHERE username = '$getuser'");
$numrows = mysql_num_rows($query);
/* Check to make user was generated */
if($numrows == 1){
$site = "http://www.midnightnachos.com/gs";
$webmaster = "universitydb#gmail.com";
$headers = "From: $webmaster";
$subject = "Activate Your Account";
$message = "Thanks for registering. Click the link below to activate your account.\n";
$message .= "$site/activate.php?user=$getuser&code=$code\n";
$message .= "You must activate your account to login.";
if (mail($getemail, $subject, $message, $headers)){
$errormessage = "You have been registered. You must activate your account from the activation link sent to your email.";
echo $form;
$getuser = "";
$getpass = "";
}
else
echo "An error has occured. Your activation email was not sent.";
}
else
$errormessage = "An error has occurred. Account not created.";
}
else
$errormessage = "Email address already in use.";
}
else
$errormessage = "Username already exists.";
mysql_close;
}
else
$errormessage = "You did not enter a valid email.";
}
else
$errormessage = "Your passwords did not match.";
}
else
$errormessage = "You must retype your password.";
}
else
$errormessage = "You must enter your password.";
}
else
$errormessage = "You must enter an email to register.";
}
else
$errormessage = "You must enter a username to register.";
echo $form;
}
$form = "
<div class='splash'>
<h1>Register for Game Swap</h1>
<p>Register for Game Swap to browse what games other local
users have added to their library. Propose trades,
chat, and meet to swap games. Your email address
will only be used to notify you when someone has
sent a trade offer. No newsletters, advertisements or
updates will be sent by us. We will also never sell
your contact information to third parties.</p>
<br />
<p align='center'>Fill out the form below to get started</p>
<br />
<form align='center' action='./register.php' method='POST'>
<input type='text' name='user' value='$getuser' class='box' size='30' placeholder='Username' /><br />
<input type='password' name='password' class='box' size='30' placeholder='Password' /><br />
<input type='password' name='retypepassword' class='box' size='30' placeholder='Retype Password' /><br />
<input type='text' name ='email' value='$getemail' class='box' size='30' placeholder='Email Address' /><br />
<input type='button' name='reg' class='loginbutton' value='Register' /><br />
</form>
</div>
<br/> $errormessage";
echo $form;
?>
</body>
</html>
I think you mixed up the button's type attribute, i.e. it's not button, but submit.
So, I guess you have a normal text input field, but your CSS is cheating your eyes. Try writing into it :)
To submit forms via buttons you can use:
<input type="submit" name="reg" value="Register!"/>
<button name="reg" value="1-or-anything">Register!</button>
And as for a possible different way of coding (getting all the validation errors at once):
$error_list = array();
if ($condition1) $error_list[] = 'My Error message 1';
if ($condition2) $error_list[] = 'My Error message 2';
if ($condition3) $error_list[] = 'My Error message 3';
...
if (empty($error_list)) the_fun_part();
else {
foreach($error_list as $msg)
echo "{$msg}<br/>";
}
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;
...
}
?>
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.