newsletter confirmation / subscription confirmation [duplicate] - php

This question already has answers here:
How to validate an Email in PHP?
(7 answers)
Closed 9 years ago.
I have a newsletter subscribe form on my website and i want it to go to a page that
confirms the user has been signed up. At the moment it just refreshes the page and gives
you a little message where the form box was. Having tested it, it also doesn't care whether
you put the email address in wrongly etc. I would like it so it checks this info and only
submits correct email addresses. The code that is there at the moment is
<?php
// get vars
$email_address = strtolower(trim($_REQUEST['email_address']));
if((strlen($email_address) > 0) && (strpos($email_address, "#")))
{
// add to db
$newsletterQry = db_query("SELECT * FROM newsletter_subscribers WHERE email='" . mysql_real_escape_string($email_address) . "'");
if(db_num_rows($newsletterQry) == 0)
{
// add
db_query("INSERT INTO newsletter_subscribers (email, created) VALUES ('" . mysql_real_escape_string($email_address) . "', NOW())");
}
}
// return back to the index page with confirmation
header("location: ".$_SERVER["HTTP_REFERER"]."?nlMsg=".urlencode("You've been added to the site newsletter."));
exit;
?>

See the solution on How to validate an Email in PHP.
You want to sanitize e-mail addresses using either RegEx, or PHP's built-in filter_var() function.
<?php
$email_address = strtolower(trim($_REQUEST['email_address']));
if (filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
// This email address is valid insert into newsletter
}

Related

Send a mail from a registration form with PHP [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 1 year ago.
Is it possible to send a mail from the code?
I want to make a registration and the credentials should be sent to the user again.
but simply no email arrives
what am I doing wrong
Here is the whole code
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'C:/xampp/htdocs/Kulinarik/PHPMailer-master/src/Exception.php';
require 'C:/xampp/htdocs/Kulinarik/PHPMailer-master/src/PHPMailer.php';
require 'C:/xampp/htdocs/Kulinarik/PHPMailer-master/src/SMTP.php';
$con= mysqli_connect('localhost','root','123456', 'userdata',);
$email = $_POST['email'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$password = rand(0, 999999);
$result = $con->query("SELECT email FROM signup WHERE email = '$email'");
if($result->num_rows == 0) {
$sql = "INSERT INTO signup (firstname, lastname, email, password) VALUES ('$firstname', '$lastname', '$email', '$password')";
$mail = new PHPMailer();
|
|
|
|
|
|
if ($con->query($sql) === TRUE) {
header("Location: Login.html");
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
}
else {
echo "User ist bereits registriert";
}
?>
I would really appreciate your help
EDIT 1
i added the phpmailer to my file and loaded it into the code
but how am i going to send an email with it ?
I assume you're a windows user and you don't have a mail server installed, if so I'd recommend using phpmailer PHPmailer link, it's much easier to use and gives way more options then the regular mail()
PHP indeed has a mail() function, but using it with a simple String for its subject and text is bound to fail (it will either be considered as spam by your recipient, or won't be sent at all by your own server).
Properly using mail() required to set corrects headers and encoding.
As said in the comments, it would be easier to use the PHPMailer library instead.

How to use php to search if element already exists in mysql db

I've got a website and when a user registers I want to check, if the entered email has already been used to register another account.
database: users
row: email
new email: $email_register
$result = $pdo->prepare("IF email_register = ? IN email FROM users $same = TRUE");
$result->execute(array($email_register));
$user = $result->fetch();
if($same == TRUE)
{
echo email already used;
}
else
{
#continue registration process
}
I want a way to know if the email is already in the db, and if it is, for the user to be sent back to the registration page with an error message (error code transmitted via header).
Assuming that users should not have more than one account per email, an easy approach is to make the email column a unique key (or primary key) in the users table. This prevents an email being used more than once.
Try this way
// check if email is taken already
$stmt = $pdo->prepare("SELECT email FROM users WHERE email_register = :email");
$stmt->execute([
'email_register ' => $email
]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (isset($user) && !empty($user)){
// Username already taken
echo "email already used";
}else{
//redirect to registration process
}
There is no need for IF in the SQL query. Just write simple select statement like:
Select email from users where email = 'example#example.com';
if query return and result it means the email is already in database if not then you can continue to the registration process.
if($exist)
{
return false; or you redirect to registration page whatever you want to do.
}
#continue registration process

Checking if email exists in MySQLi database using PHP [duplicate]

This question already has answers here:
Check email exist with php mysqli [duplicate]
(2 answers)
Check if row exists in the database before inserting
(3 answers)
Closed 1 year ago.
I'm trying, as many others here have before me, to check if an email already exists in my database during account registration on my website, using PHP to interact with a MySQLi database. I've tried using as many guides as I could find here but still no luck.
Below is the code I originally wrote to insert the email of users into my database upon registration:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$database = new mysqli("localhost", "user", "dbpw", "dbname");
if($database->connect_error){
die( "Error connecting:" . $database->connect_error);
}
$email = $database->real_escape_string(htmlspecialchars($_POST["email"]));
$query = "SELECT email FROM Users WHERE email =$email";
$result = $database->query($query);
$numOfRows = $database->num_rows($result);
if($numOfRows > 0){
echo "Email already exists in our database.";
}else{
$query = "INSERT INTO Users (email) VALUES ('" . $email . "');
if(!$database->query($query)){echo("<p>Unable to add user for query: " . $query . " <br /> Error: " . $database->errno . " " . $database->error);}}
Prior to inserting the email check (the if($numOfRows) statement), my database was being updated properly.
However, after adding my attempted email check, the page completely broke. My database wouldn't update with unique passwords, and it wouldn't display the echoed message "Email already exists in our database" if the email was a duplicate. The page would load, but with just the basic header, footer, and background CSS I have linked to every page.
Instead of using
$numOfRows = $database->num_rows($result);
Use
if($result ->num_rows)
{
}
You need to add single quotation marks around the email variable. Like this '$email'. Check the below code.
$query = "SELECT email FROM Users WHERE email = '$email'";
And you need to edit your conditional statement to check whether its greater than or equal to 0 or you can just use variable as boolean in condition block.

mysql_affected_rows() work-around?

I'm using this code as part of an email confirmation script. It works great, except I can't figure out a way to distinguish between when somebody has provided an invalid email address vs when they have simply refreshed the page (ie. already confirmed their account). The only think I can think of is putting a time stamp field in the users table that always gets updated, but I'm hoping there is a better way. I thought REPLACE would do the trick, but, while email is unique, it is not the primary key.
if (isset ($email, $token, $correctToken)){
$success = FALSE; //Set the $success variable so that we don't get an error when testing for it later
if ($token == $correctToken) {
$confirm = mysql_query("UPDATE users
SET conf = 'TRUE'
WHERE email = '$email'");
if (mysql_affected_rows() == 1) {
echo "Thank you! Your email address is confirmed and your account is actived.";
$success = TRUE;
}
}
if (!$success) {
echo "There was a problem with the confirmation. Try the link in your email again or contact us at Support#WiseRenters.com";
// Send email to admin to notify of error
exit;
}
}
Thanks in advance for the advice!
Billy
EDIT: The $email and $token variables are provided through $_GET or $_POST, in case that wasn't obvious.
A redirection would stop them from refreshing - but what if they click the link in their email again?
You should check if the current user is activated or not.
$sql = "SELECT id, conf FROM users WHERE email = '{$email}'";
$exec = mysql_query($sql) or die(mysql_error());
list( $id, $conf ) = mysql_fetch_row($exec);
if( $conf ) {
// Redirect them to their profile with a message saying "your account has already been activated"
header("Location: /profile?already_activated");
exit;
}
// your code
$confirm = mysql_query("UPDATE users
SET conf = 'TRUE'
WHERE id = '{$id}'");
In response to your comment:
Keep in mind this will only add an additional query for a user who has not activated yet. If they have activated then the redirect occurs and the page is still running only 1 query.
To optimize this a bit, you can select the user ID and confirmation status based on the email address. Then, if they do need to be activated, you can activate them based on user ID instead of email. Since an integer key is much faster, the combined time of the 2 queries will be about the same as the 1 query where you are updating based on a string column. I updated the code to reflect this.
Also, this page will probably not be accessed very frequently. Any optimizations from here would really be micro- and not really that helpful.
By the way I hope you are using mysql_real_escape_string on the email, and that conf is a boolean true/false not a string 'true'/'false'.

Only members can submit this form php

New to php. I have a form that is only for members to submit. What php code do I need for the form to check that the email address on the form is found my members database and then its okay to submit the form?
If email address is not in the members database then I want to echo "Only members can submit this form." What php code do I need to connect to database in the form and do the check so I don't get forms submitted from non members?
Thanks
At the top of your php file you could do something like this:
if(isset($_POST['email'])) {
mysql_connect("hostname","username","password");
$result = mysql_query("SELECT * FROM users WHERE email = '".mysql_real_escape_string($_POST['email'])."'");
if($row = mysql_fetch_array($result)) {
// found email
} else {
// email wasn't found
}
}
Of course you would need to replace the hostname, username and password to correct values, also you should change the users and email in the select query to the name of your table and field.
Here is a dummy form:
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
<input type="text" name="email" />
<input type="submit" value="Send" />
</form>
You want to study Mysql query and other mysql functions. The code would basically look like:
$c = mysql_connect( ...);
mysql_select_db( 'database', $c);
$q = mysql_query( "SELECT COUNT(*) FROM users WHERE email = '" .
mysql_real_escape_string( $_POST['email'],$c) . "'");
$row = mysql_fetch_row( $q);
if( $row[0]){
echo "Thanks for submitting...";
} else {
echo "Only members...";
}
This is only brief example which is far from perfection but I think it's good place for you to start.
If someone is a registered member that implies you're very likely using a $_SESSION['id_member'] variable.
This will set the cookie's name that can be seen by the client to 'member'...
if (!headers_sent() && !isset($_SESSION))
{
session_name('member');
}
...then when a user authenticates assign a session variable and their permission...
$_SESSION['member_id'] = $mysql_row['id'];
$_SESSION['member_status'] = $mysql_row['id'];
Here is a status hierarchy that you might use or change but it should be a good point of reference...
10 - Super Admin (only you)
9 - Admin// mid-level admin
8 - Assistant//restrictive admin
7 - Moderator//Don't give this status to any jerks
6 - Premium Member//they gave you money!
5 - Registered Member//normal account status
4 - Frozen Account//not banned but did something wrong, will "thaw"
3 - Unverified Email Address//registered but did not verify email
2 - Unregistered Visitor//human
1 - Good Bots
0 - Banned
Generally first determine how to catch the form...
if ($_SERVER['REQUEST_METHOD']=='GET')
{
}
else if ($_SERVER['REQUEST_METHOD']=='POST')
{
if (isset($_POST['submit_button_name_value'])) {blog_post_ajax_comment();}
}
I add the name="value" attribute/value to submit buttons, why? Have two submit options (preview and publish in example) you may want to have the server trigger one function or the other, VERY simple and valid (X)HTML.
You should check if the variable isset (keep permissions in mind).
Then check if their user permissions are adequate, you can use a simple integer to represent this.
Then wrap the isset and permission if statements around two things, one the form and secondly make sure you use these conditions when PROCESSING the form.
I always test against things to reject and throwing in database query error handling to give you a little extra boost...
//function module_method_ajax_purpose()
function blog_post_ajax_comment()
{
if (!isset($_SESSION['member'])) {http_report('403',__FUNCTION__,'Error: you must be signed in to do that.');}
else if ($_SESSION['member_status']<=4) {http_report('403',__FUNCTION__,'Error: permission denied; your account has been flagged for abuse.');}
else if (flood_control($datetime,'60')!=1) {http_report('403',__FUNCTION__,'Error: you can only post a comment once every X seconds.');}
else if (!isset($_POST['post_form_name_1']) || !isset($_POST['post_form_name_2'])) {http_report('403',__FUNCTION__,'Error: permission denied.');}
else
{
// NOW process
$query1 = "SELECT * FROM table";
$result1 = mysql_query($query1);
if ($result1)
{
//successful, increment query number for further queries
}
else {mysql_error_report($query1,mysql_error(),__FUNCTION__);}
}
Error reporting is VERY powerful, use it for HTTP, JavaScript, PHP and MySQL. You could also benefit from my answer about real-time log reading here: jQueryUI tabs and Firefox: getBBox broken?

Categories