PHP email subscription validation and check for existing - php

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? :)

Related

Forgotpassword function not working, sql, php

Not sure what happened but its suddenly stopped working...
I can enter the email and username (i know the credentials are correct) and get the message that it wont find any matching details...
The content of forgotpassword.php:
<?php
require_once("users.inc");
$PAGE_TITLE = "Forgotten Password";
include $PHP_USERS_HEADER_FILE;
?>
<h3>Forgot Your Password?</h3>
<p>If you've forgotten your password, just enter the username and email address that you registered with, and your password will be emailed to you immediately.</p>
<form method="post" action="emailpassword.php">
<p><b>Your Username: </b>
<input type="text" name="username" size="35" />
</p><p>
<b>Your Email Address: </b>
<input type="text" name="email" size="35" />
</p>
<input type=submit value="Submit" />
</form>
the content of emailpassword.php:
<?php
require_once("users.inc");
$PAGE_TITLE = "Forgotten Password";
connect_to_users_db();
$password = fnRandomPassword(8);
$encrypt_pwd = md5($password);
$sql = "UPDATE users SET password='$encrypt_pwd' WHERE email='".$_REQUEST['email']."' AND username='".$_REQUEST['username']."'";
$query = mysql_query($sql);
$sql1 = "SELECT email, username, password FROM users WHERE email='".$_REQUEST['email']."' AND username='".$_REQUEST['username']."'";
$query1 = mysql_query($sql1);
if ($query1 && (mysql_num_rows($query1) > 0)) {
while (list($email,$username) = mysql_fetch_row($query1)) {
mail($email, "Your Password", "Below is the username and password information you requested.\n\nUsername: '$username'\nPassword: '$password'.\n\n","From: $WEB_MASTER <$WEB_MASTER_EMAIL>\n");
}
}
include $PHP_USERS_HEADER_FILE;
?>
<h3>Forgot Your Password?</h3>
<?
echo "<p>";
//if ($query && mysql_num_rows($query) > 0) {
if (mysql_affected_rows() > 0) {
?>
<p>We've emailed your password. You should receive it within a minute. If you don't, please send mail to the <?=$WEB_MASTER?>.</p>
<?php
} else {
?>
<p>We could not find an email and username corresponding with the email address and username you entered. Perhaps you registered with a different email address/username. Use the form below to try again.</p>
<form method="post" action="emailpassword.php">
<p><b>Your Username: </b>
<input type="text" name="username" size="35" />
</p><p>
<b>Your Email Address:</b>
<input type="text" name="email" size="35" />
</p>
<input type="submit" value="Submit" />
</form>
<p>If you believe you have not registered before, you are welcome to sign up now with the following form:</br>
<?php include 'fragments/requestaccont.htm';?>
<?php
}
?>
Is there some outdated coding here or something?
It stopt working because you changed the line which checks the query. Now it will e-mail a new password and displays the 'not found' message.
You are using mysql_affected_rows() but the last query was a SELECT query which doesn't effect rows. Change the line:
if (mysql_affected_rows() > 0) {
Into this line:
if ($query1 && (mysql_num_rows($query1) > 0)) {
Also listen to Doon, mysql_* is deprecated.

php form submission to mysql database

I have a registration form. In the database, the username and email are unique index. When the form submits and username or email are already present in the database, the values are not inserted. I want to notify the user that the values were not inserted. How can i do this?
HTML
<form action="register.php" method="post" id="reg" onsubmit='return validate();'>
Company Name:
<input type="text" class="inputs" name="name" id="name" /><br />
Email:
<input type="text" class="inputs" name="email" id="txtEmail" /><br />
User name:
<input type="text" class="inputs" name="uname" id="uname"/><br />
Password:
<input type="password" class="inputs" name="pass" id="pass1"/><br />
Conferm Password:
<input type="password" class="inputs" name="cpass" id="pass2"/><br /><br />
<input type="submit" value="Register" class="button" />
</form>
register.php:
include ("db.php");
if (isset($_POST['register'])) {
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
mysqli_query($con,"INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','')");
}
*Sweet And Short *
First check that username or email is exist or not using select query if resulting is 0 (it means not exists), Insert query will run ahead
<?php
if($_POST['register']){
$uname = $_POST['uname'];
$email = $_POST['email'];
$name= $_POST['name'];
$pass= $_POST['pass'];
$result = mysqli_query($con, 'SELECT * from TABLE_NAME where email_id = "'.$email.'" or username = "'.$uname.'" ');
if(mysqli_num_rows($result) > 0){
echo "Username or email already exists.";
}else{
$query = mysqli_query($con , 'INSERT INTO TABLE_NAME (`email_id`, `username`,`name`,`pass`) VALUES("'.$email.'", "'.$email.'", "'.$uname.'","'.$name.'", "'.$pass.'")');
if($query){
echo "data are inserted successfully.";
}else{
echo "failed to insert data.";
}
}
}
?>
The query method would return true or false, depending on if the row has been inserted or not.
Try the following Code
include ("db.php");
if (isset($_POST['register']))
{
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
$var = mysqli_query('SELECT * from company_profile where email_id = "'.$email.'" or username = "'.$uname.'" ');
$num = mysqli_num_rows($var);
if($num==0)
{
$result = INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','');
$res = mysqli_query($result);
if($res)
{
echo "Records Inserted Successfully!!";
}
else
{
echo "Records Inserted Failed!!";
}
}
else
{
echo "User with the Details Already exists!!"
}
}

Multiple form sign up not working

I have a sign up process which involves two forms being submitted. The problem is with the first form not being submitted. Also, I need a way to relate the two forms as information from both is inserted into the same table row, I think this can be done by taking the previous table row id.
It is supposed to work like this: First a user must search for an item in the search bar. Matches are then displayed with radio buttons next to each one and a submit button at the bottom. When submitted, the form data (which is the result of the search that they checked with the radio) goes into the database table 'users'. The 'users' table contains a row for id, username, password and radio.
The radio option is submitted into radio. This also creates an id, which is auto incremented. That is the first form. Once the radio option is picked and the data is in a table row, the user must fill out the second form which asks for an email and a password, which is submitted into the same row that the radio option is in.
When I go through this process, the email (referred to as username in table) and password appear in the table along with the id, but the radio is always blank. Not sure why the radio option is not being submitted. Also not sure if i need a way to relate the forms. I am a beginner at this so, please try to make answers understandable. Thanks in advance, heres the code:
<?php
//This code runs if the form has been submitted
if (isset($_POST['submit'])) {
//This makes sure they did not leave any fields blank
if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) {
die('You did not complete all of the required fields');
}
// checks if the username is in use
if (!get_magic_quotes_gpc()) {
$_POST['username'] = addslashes($_POST['username']);
}
$usercheck = $_POST['username'];
$check = mysql_query("SELECT username FROM users WHERE username = '$usercheck'")
or die(mysql_error());
$check2 = mysql_num_rows($check);
//if the name exists it gives an error
if ($check2 != 0) {
die('The email '.$_POST['username'].' is already in use.');
}
// this makes sure both passwords entered match
if ($_POST['pass'] != $_POST['pass2']) {
die('Your passwords did not match. ');
}
// here we encrypt the password and add slashes if needed
$_POST['pass'] = md5($_POST['pass']);
if (!get_magic_quotes_gpc()) {
$_POST['pass'] = addslashes($_POST['pass']);
$_POST['username'] = addslashes($_POST['username']);
}
// now we insert it into the database
$insert = "INSERT INTO users (username, password, radio)
VALUES ('".$_POST['username']."', '".$_POST['pass']."', '".$_POST['radio']."')";
$add_member = mysql_query($insert);
?>
<h2><font color="red">Registered</font></h2>
<p>Thank you, you have registered - you may now login</a>.</p>
<?php
}
else
{
?>
<font color = #000000><h1>Sign Up</h1></font>
<?php
// Search Engine
// Only execute when button is pressed
if (isset($_POST['keyword'])) {
// Filter
$keyword = trim ($_POST['keyword']);
// Select statement
$search = "SELECT * FROM tbl_name WHERE cause_name LIKE '%$keyword%'";
// Display
$result = mysql_query($search) or die('That query returned no results');
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
while($result_arr = mysql_fetch_array( $result ))
{
?>
// Radio button
<input type="radio" name="radio">
<?php
echo $result_arr['cause_name'];
echo " ";
echo "<br>";
}
?>
<input type="submit" name="radio_submit" value="Select Item">
</form>
<?php
$anymatches=mysql_num_rows($result);
if ($anymatches == 0)
{
echo "We don't seem to have that cause. You may add a cause by filling out a short <a href='add.php'>form</a>.<br><br>";
}
}
?>
<!--Sign Up Form-->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="sign_up_form">
<input type="text" name="keyword" placeholder="Search" onFocus="this.select();" onMouseUp="return false;">
<input type="submit" name="search" value="Search">
<br />
<br />
<input type="email" name="username" maxlength="250" placeholder="Your email" onFocus="this.select();" onMouseUp="return false;">
<input type="password" name="pass" maxlength="50" placeholder="Password" onFocus="this.select();" onMouseUp="return false;">
<input type="password" name="pass2" maxlength="50" placeholder="Re-type Password" onFocus="this.select();" onMouseUp="return false;">
<br />
<input type="submit" name="submit" value="Sign Up">
</form>
<?php
}
?>
Modify your code like this
<input type="radio" name="radio" value="<?php echo $result_arr['cause_name']; ?>" >
and then submit it you should get the value
update the below query as well
<?php
echo $insert = "INSERT INTO users (username, password, radio) VALUES ('$_POST[username]', '$_POST[pass]', '$_REQUEST[radio]')";
$add_member = mysql_query($insert);
?>
change the below code
//This code runs if the form has been submitted
if (isset($_POST['radio_submit'])) {
/////
<?php
if (isset($_REQUEST['submit']))
{
$radio = $_REQUEST['radio'];
$insert = mysql_query("INSERT INTO users (radio) VALUE ('$radio')");
if (!$insert)
{
echo mysql_error();
}
}
?>
<form action="" method="get">
<input type="radio" name="radio" value="red">red
<input type="radio" name="radio" value="blue">blue
<input type="submit" name="submit" />
</form>

How to prevent duplicate email addresses from being registeres?

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
}

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;
...
}
?>

Categories