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;
...
}
?>
Related
my code is here
<?php
// This section processes submissions from the login form.
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//connect to database
require ('mysqli_connect.php');
// Validate the email address:
if (!empty($_POST['email'])) {
$e = mysqli_real_escape_string($dbcon, $_POST['email']);
} else {
$e = FALSE;
echo '<p class="error">You forgot to enter your email address.</p>';
}
// Validate the password:
if (!empty($_POST['psword'])) {
$p = mysqli_real_escape_string($dbcon, $_POST['psword']);
} else {
$p = FALSE;
echo '<p class="error">You forgot to enter your password.</p>';
}
if ($e && $p){//if no problems
// Retrieve the user_id, first_name and user_level for that email/password combination:
$q = "SELECT user_id, fname, user_level FROM users WHERE (email='$e' AND psword=SHA1('$p'))";
$result = mysqli_query ($dbcon, $q);
// Check the result:
if (#mysqli_num_rows($result) == 1) {//The user input matched the database rcoord
// Start the session, fetch the record and insert the three values in an array
session_start();
//echo '<pre>';
//print_r($_SESSION);
//echo '</pre>';
$_SESSION = mysqli_fetch_array ($result, MYSQLI_ASSOC);
//echo '<br>33333333333333333333333333333333333<br>';
//echo '<pre>';
//print_r($_SESSION);
//echo '</pre>';
$_SESSION['user_level'] = (int) $_SESSION['user_level']; // Changes the 1 or 2 user level to an integer.
$url = ($_SESSION['user_level'] === 1) ? 'admin-page.php' : 'members- page.php'; // Ternary operation to set the URL
header('Location: ' . $url); // Makes the actual page jump. Keep in mind that $url is a relative path.
exit(); // Cancels the rest of the script.
mysqli_free_result($result);
mysqli_close($dbcon);
//ob_end_clean(); // Delete the buffer.
} else { // No match was made.
echo '<p class="error">The email address and password entered do not match our records.<br>Perhaps you need to register, click the Register button on the header menu</p>';
}
} else { // If there was a problem.
echo '<p class="error">Please try again.</p>';
}
mysqli_close($dbcon);
} // End of SUBMIT conditional.
?>
and my form is:
<h2>Login</h2>
<form action="login.php" method="post">
<p><label class="label" for="email">Email Address:</label>
<input id="email" type="text" name="email" size="30" maxlength="60" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" > </p>
<br>
<p><label class="label" for="psword">Password:</label>
<input id="psword" type="password" name="psword" size="12" maxlength="12" value="<?php if (isset($_POST['psword'])) echo $_POST['psword']; ?>" ><span> Between 8 and 12 characters.</span></p>
<p> </p><p><input id="submit" type="submit" name="submit" value="Login"></p>
</form><br>
why this code does not log to the admin-page.php or members-page.php
althogh i enter email and pass correctly.
result of this code pointed to the login page!
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 :)
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.
I have been making a login/register system and one problem I have run into is not allowing duplicate email addresses from being registered. I want it to work so that the database wont accept data from a duplicate email and the user will be alerted too. I am sort of new to PHP so I am unsure of how to do this. Thanks.
My PHP
if (empty($_POST['email'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._- ]+)+$/", $_POST['email'])) {
//regular expression for email validation
$Email = $_POST['email'];
} else {
$error[] = 'Your Email Address is invalid ';
}
}
if (empty($_POST['Password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['Password'];
}
if (empty($error)) //send to Database if there's no error '
{ // If everything's OK...
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM members WHERE Email ='$Email'";
$result_verify_email = mysqli_query($dbc, $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));
$query_insert_user = "INSERT INTO `members` ( `Username`, `Email`, `Password`, `Activation`) VALUES ( '$username', '$Email', '$Password', '$activation')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
mysqli_close($dbc);//Close the DB Connection
} // End of the main Submit conditional.
?>
The HTML
<form action="./index.php#openModal2" method="post" class="registration_form">
<fieldset>
<legend>Registration Form </legend>
<p>Create A new Account</p>
<div class="elements">
<label for="username">Name :</label>
<input type="text" id="username" name="username" size="25" />
</div>
<div class="elements">
<label for="email">E-mail :</label>
<input type="text" id="email" name="email" size="25" />
</div>
<div class="elements">
<label for="Password">Password:</label>
<input type="password" id="Password" name="Password" size="25" />
</div>
<div class="submit">
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" value="Register" />
</div>
Add a unique constraint on the email column in the table members:
ALTER TABLE members ADD UNIQUE (email);
Typically, you would do this when you create the table rather than altering the table afterwards.
Either add a unique constraint as Gordon Linoff said, or here is what I do..
$check_email_for_duplicates = mysqli_query($dbc, "select * from `members` where `Email` = '".mysqli_real_escape_string($email)."'");
if(mysqli_num_rows($check_email_for_duplicates) > 0) //Email address is unique within this system and must not be more than one
{
echo 'Sorry, the email <b>'.$email.'</b> is already in use. Please enter a different email.';
}
else {
//some code
}
I am creating an email subscription form in PHP and want to check for a valid address as well as if the email is already existing in my database.
My code is connecting to my database and inserting but the validation as well as checking for an existing email are not working.
No matter what I type into my form it inserts it into my database even if I don't type anything.
Here is all of my code:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<legend>Subscribe to Our Newsletter </legend>
<?php if ($feedback!='')
echo('<p>'.$feedback.'</p>'); ?>
<label>Name: <input name="name" type="text" value="<?php echo $name; ?>" /></label>
<label>Email: <input name="email" type="text" value="<?php echo $email; ?>" /></label>
<label><input type="submit" value="Sign Up!" /></label>
</fieldset>
</form>
<?php
$feedback='';
if (!$email) {
$feedback .= '<strong>Please enter your email address</strong><br />';
}
if (!$name) {
$feedback .= '<strong>Please enter your name</strong><br />';
}
list($username, $mailDomain) = explode("#", $email);
if (!#checkdnsrr($mailDomain, "MX")) {
$feedback .= '<strong>Invalid email domain</strong><br />';
}
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email)) {
$feedback .= '<strong>Your email address doesn\'t appear to be valid - please check and try again';
}
function cleaninput($value, $DB) {
if (get_magic_quotes_gpc()) {
$value = stripslashes( $value );
}
return mysql_real_escape_string( $value, $DB );
}
$name=$_POST['name'];
$email=$_POST['email'];
include_once "connect.php";
$sql = mysql_query("SELECT * FROM subscribers WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if ($numRows>0) {
$feedback = '<strong>That email address is already subscribed.</strong>';
}
$insertresult = mysql_query("INSERT INTO subscribers (name, email) VALUES('$name', '$email')") or die (mysql_error());
if ($insertresult) {
$completed = true;
}
if($competed=false) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?> method="post">
<fieldset>
<legend>Subscribe to OUr Newsletter </legend>
<?php
if ($feedback!='')
echo('<p>'.$feedback.'</p>'); ?>
<label>Name: <input name="name" type="text" value="<?php echo $name; ?>" /></label>
<label>Email: <input name="email" type="text" value="<?php echo $email; ?>" /></label>
<label><input type="submit" value="Sign Up!" /></label>
</fieldset>
</form>
<?php
}
else {
echo('Thanks - you have subscribed to our newsletter successfully. You can unsubscribe at any time by clicking the link at the bottom of each email we send.');
}
?>
Also the last echo in my script is always there. It is displayed under my my form always. Not sure why that is. Maybe I have it in the wrong place in my code.
else {
echo('Thanks - you have subscribed to our newsletter successfully. You can unsubscribe at any time by clicking the link at the bottom of each email we send.');
}
Thanks!
This code is a bit of a mess, to be honest :) It's slightly difficult to read, but I can see at least two problems: you write $competed rather than $completed in one of your if statements, and you don't actually have the INSERT query in an if block: it'll always execute. Try putting it in an else block after the if block that checks whether the address is already in your database, like this:
$sql = mysql_query("SELECT * FROM subscribers WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if ($numRows>0) {
$feedback = '<strong>That email address is already subscribed.</strong>';
}
else {
$insertresult = mysql_query("INSERT INTO subscribers (name, email) VALUES('$name', '$email')") or die (mysql_error());
}
You also don't need to use both addslashes and mysql_real_escape_string; just the latter will do. And I'm not sure why you have the same form in your code twice. Surely once should do? :)