How do I send an email through SMTP? - php

I need to send an email to a new user and myself when they register an account. I need to know how to it send through my admin email instead of the weird email address that the GoDaddy server uses to send it.
Here's my PHP code:
<?php
require_once('recaptchalib.php');
$privatekey = "privatekey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
die ("reCAPTCHA was wrong, try again!");
} else {
mysql_connect("host", "username", "password");
mysql_select_db("database");
$hash = sha1(rand (0,1000) );
$name = $_POST['name'];
$bmonth = $_POST['month'];
$bday = $_POST['day'];
$byear = $_POST['year'];
$sq = $_POST['security_q'];
$sq_ans = sha1($_POST['security_q_ans']);
$email = $_POST['email'];
$pass = sha1($_POST['pass']);
$insert_query = "INSERT INTO users (account_act_hash, name, bmonth, bday, byear, securityq, securityq_ans, email, password) VALUES ('$hash','$name','$bmonth','$bday','$byear','$sq','$sq_ans','$email','$pass')";
$insertion_result = mysql_query($insert_query);
if($insertion_result) {
$to = "my admin email";
$subject = "New account created";
$name = $_POST['name'];
$bmonth = $_POST['month'];
$bday = $_POST['day'];
$byear = $_POST['year'];
$email = $_POST['email'];
$ip = $_SERVER['REMOTE_ADDR'];
$message = 'EMAIL
Here is the account info.
Name: $name
Birthday: $bmonth-$bday-$byear
Email: $email
Registration IP Address: $ip
'
$header = "A new account has been created.";
}
if($_POST){
mail($to, $subject, $message, $header);
}
}
?>
<?php
$to2 = $_POST['email'];
$subject2 = "Activate Your Account";
$email2 = $_POST['email'];
$message2 = '
Thanks for registering an account!
Your account has been created and can be used when you activate your account by clicking the below link!
------------------------------------------------------------------------
Email: '.$email2.'
------------------------------------------------------------------------
Please click this link to activate your account:
https://www.mysite.com/activation.php?email='.$email2.'&account_act_hash='.$hash.'
';
if($_POST) {
mail($to2, $subject2, $message2);
}
?>

Directly from the mail doc page you need to specify from in the header:
// Additional headers
$headers .= 'From: Birthday Reminder <birthday#example.com>' . "\r\n";
You are getting a _ weird email address_ because you have not specified who the email should be coming from.
You have a bunch of additional problems:
HEREDOC
I'm assuming this is what you were trying to do
$message = <<<EMAIL
Here is the account info.
Name: $name
Birthday: $bmonth-$bday-$byear
Email: $email
Registration IP Address: $ip
EMAIL;
MySQL
mysql_* functions are deprecated, read the read box.
This will also lead to don't trust user input, prepared statements are going to be your friend.
Misc
When using double quotes, use curly braces with your variables:
$foo = 'test';
echo "This a {$foo}!"; // This is a test!
In this case die(), is a very harsh way to end a script in terms of user experience.

Related

How do I register a user

I currently have the following code: If that email is already registered then the user will be promoted with a message. However if the email is not already registered then they can register. When I run this code and register a user who has not already registered, they are still getting the alert that username already exists. I think it may be something with the brackets!
<?php
include ("dbConnect.php");
require 'libPassword.php';
function filter_email_header($email){
return preg_replace('/[\0\n\r\|\!\/\<\>\^\$\%\*\&]+/','',$email);
}
if(isset($_POST['submit'])){
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$telephone = $_POST['telephone'];
$address = $_POST['address'];
$medical_conditions = $_POST['medical_conditions'];
$dob = $_POST['dob'];
$email = $_POST['email'];
$password = $_POST['password'];
$last_login = date("Y-n-d");
$dbQuery=$db->prepare("SELECT email FROM customer where email > 0");
$dbParams = array('email'=>$email);
$dbQuery->execute($dbParams);
if ($dbQuery) {
$message = "username already exists";
echo "<script type='text/javascript'>alert('$message');</script>";
}//if
else{
$hashPassword = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
if($dbQuery->rowCount()==0){
$dbQuery=$db->prepare("INSERT INTO customer (forename, surname, telephone, address, medical_conditions, dob, email, password) VALUES (:forename, :surname, :telephone, :address, :medical_conditions, :dob, :email, :hashPassword)");
$dbParams = array('forename'=>$forename,'surname'=>$surname, 'telephone'=>$telephone, 'address'=>$address,'medical_conditions'=>$medical_conditions, 'dob'=>$dob, 'email'=>$email, 'hashPassword'=>$hashPassword);
$dbQuery->execute($dbParams);
if($dbQuery) {
header("Location: myProfile.php");
}//if
}//if
else{
echo('Please fill out all fields marked with *');
}//else2
}//else1
if(isset($email)){
$sender='jess#gymmembership.com';
$email = filter_email_header($email);
$headers = "From:". $sender;
$to = $email; // Send email to our user
$subject = 'Signup | Verification'; // Give the email a subject
$message = '
Thanks for signing up!
Here is your login details:
------------------------
Your email: '.$email.'
Password: '.$password.'
------------------------
You can now login to your account:
'; // Our message above including the link
$headers = 'From:gymmanagementsystem' . "\r\n"; // Set from headers
//mail($to, $subject, $message, $headers); // Send our email
$sent=mail($to, $subject, $message, $email);
}}
?>
Probably because you are checking if the query executed and not check whether or not you actually got a match. Check if your number of row are > 0.
if ($dbQuery) {
$message = "username already exists";
echo "<script type='text/javascript'>alert('$message');</script>";
}
Also pretty sure you might actually want to compare to an email like so.
"SELECT email FROM customer where email = :email"
I also wouldn't replace the unwanted character in the email it could be that they type "!" instead of "#" by accident and your email wouldn't be valid. I would suggest notifying that the email isn't valid and for what reason.

recaptcha not sending email after verify in php

<?php
if(isset($_POST['submit']))
{
$email=$_POST['email'];
$comment=$_POST['comment'];
$captcha=$_POST['g-recaptcha-response'];
if(!$captcha)
{
echo 'Please check the the captcha form.';
}
$response=file_get_contents("https://www.google.com/recaptcha/api/sitev erify?secret="secretkey" &response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
header('Location:http://mywebsite.com/.errordocs/404.html');
}
else
{
header('Location:http://mywebsite.com/thankyou.php');
}
}
if (isset ($_POST['Side_Form'])){
$name = $_POST['name'];
$last = $_POST['last'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
// Build the email (replace the address in the $to section with Enjoy's contact e-mail)
$to = 'somebody#somewhere.com';
$subject = "Main Contact Form";
$message = "Name: $name
Email: $email
Phone: $phone
Comments: $comments";
$headers = "From: $email \r\n";
mail($to, $subject, $message, $headers);
}
?>
The problem is when the recaptcha is verified on the form, it displays the checkmark, user can click submit, but I get a blank screen and email doesn't send. Any help is Greatly appreciated, have been working on this for about 3 weeks.
your currently redirecting before actually sending the email. here is your code restructured. also fixed the recaptcha response processing
<?php
if (isset($_POST['submit'])){
$email = $_POST['email'];
$comment = $_POST['comment'];
$captcha = $_POST['g-recaptcha-response'];
if (! $captcha){
echo 'Please check the the captcha form.';
exit();
}else{
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $secretkey . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
$responseKeys = json_decode($response,true);
if (intval($responseKeys["success"]) !== 1){
header('Location:http://mywebsite.com/.errordocs/404.html');
exit();
}else{
if (isset($_POST['Side_Form'])){//not sure what this is, hopefully you do :-)
$name = $_POST['name'];
$last = $_POST['last'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
// Build the email (replace the address in the $to section with Enjoy's contact e-mail)
$to = 'somebody#somewhere.com';
$subject = "Main Contact Form";
$message = "Name: $name
Email: $email
Phone: $phone
Comments: $comments";
$headers = "From: $email \r\n";
mail($to,$subject,$message,$headers);
header('Location:http://mywebsite.com/thankyou.php');
exit();
}
}
}
}
?>

How to disable the email confirmation link after few seconds in php

Hi I am sending confirmation e-mail after signup.How can the link be expired after a few seconds can anyone suggest me.Because if i click on the link after few days also it is getting activated.That should not be happen.Here is my code:
<?php
session_start();
$sessionCaptcha = $_SESSION['vercode'];
$inputStream = file_get_contents("php://input");
$data = json_decode($inputStream);
$connection = mysql_connect("localhost", "enjoytax_account", "account") or die(mysql_error());
$db = mysql_select_db("enjoytax_accounting", $connection);
if($db)
{
$confirm_code=md5(uniqid(rand()));
$username = $data->username;
$email = $data->email;
$password = md5($data->password);
$confirmpassword = md5($data->confirmpassword);
$mobileno = $data->mobileno;
$captcha=$data->captcha;
$check=mysql_query("select email from register where email = '$email'");
$num_rows = mysql_num_rows($check);
if ($num_rows == 0)
{
if($captcha == $sessionCaptcha)
{
$query = mysql_query("insert into register(username,email, password, repassword,mobile,confirm_code) values ('$username','$email', '$password' , '$confirmpassword', '$mobileno','$confirm_code')");
if ($query)
{
$from .= 'info#mail.com' . "\r\n\r\n";
$to = $data->email;
$subject="Your confirmation link here";
$message.="Click on this link to activate your account \r\n";
$message.="http://www.example.com/model/confirmation.php?email=$email&passkey=$confirm_code";
$success = mail($to, $subject, $message);
$successJson='{"success":"We have sent a verification email ' .
'to your email id '.$email.', please check your ' .
'Inbox and verify your email in order to proceed further."}';
print_r($successJson);
}else{
$failureJson='{"error":"We are encountering some issue. Please try after some time."}';
print_r($failureJson);
}
}else{
$failureJson='{"error":"Please Enter Correct Captcha."}';
print_r($failureJson);
}
}else{
$failureJson='{"error":"Email-Id already Exists."}';
print_r($failureJson);
}
}
?>
I have not tested the code but this might help you.
session_start();
if ($query)
{
$from .= 'info#mail.com' . "\r\n\r\n";
$to = $data->email;
$subject="Your confirmation link here";
$message.="Click on this link to activate your account \r\n";
$message.="http://www.example.com/model/confirmation.php?email=$email&passkey=$confirm_code";
$success = mail($to, $subject, $message);
$successJson='{"success":"We have sent a verification email ' .
'to your email id '.$email.', please check your ' .
'Inbox and verify your email in order to proceed further."}';
$_SESSION['now'] = date('i:s');
$now =date('Y-m-d H:i:s');
$futureDate = $now+(60*5);
$formatDate = date("Y-m-d H:i:s", $futureDate);
if($_SESSION['now'] > $formatDate)
{
$failureJson='{"error":"We are encountering some issue. Please try after some time."}';
print_r($failureJson);
}
}
else
{
echo " Query Not Executed";
}

PHP form processor not working

I just started learning php not long ago, and I am currently building a "contact us" form which will send the user input to my email. I have been on this for days thinking I will figure it out, but I am not getting it. I wanna also be able to receive the user's input in my email and also be able to detect the user's IP address. When I submitted the form, I received every other input but the IP address though I used "localhost".
I tried with the <input type="hidden" name="message" value="<?php echo $_SERVER['REMOTE_ADDR']; ?>"> but I read online that it's better to do it without the <input type="hidden"> and just process everything in the form processor script. Please kindly help me with this.
<?php
$emailError = "";
$messageError = "";
function getUserIp(){
$client = $_SERVER['HTTP_CLIENT_IP'];
$forward = $_SERVER['HTTP_X_FORWARD_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP)) {
$ip = $client;
}elseif(filter_var($forward, FILTER_VALIDATE_IP)) {
$ip = $client;
}else{
$ip = $remote;
}
return $ip;
}
if(isset($_POST['submit'])){
//declares variable
$email = $_POST["email"];
$subject = $_POST["subject"];
$message = $_POST["message"];
if(empty($_POST['email'])){
$emailError = "Please enter your email";
}
if(empty($_POST['subject'])){
$subjectError = "Please enter a subject?";
}
}
if(!empty($_POST['email']) && !empty($_POST['subject'])){
// Send the email
$to = "you#yourdomain.com";
$email = "From: $email";
$subject = "Subject: $subject";
$message = "$message" . "\n\n\n==- Sent from the website with IP Address: " . $ip . " -==";;
$headers = "From: $email,";
$send_contact=mail($to,$email,$subject,$message,$headers);
header("Location: domain");
}
?>
change below section --
if(!empty($_POST['email']) && !empty($_POST['subject'])){
// Send the email
$to = "you#yourdomain.com";
$ip =getUserIp();
$email = "From: $email";
$subject = "Subject: $subject";
$message = "$message" . "\n\n\n==- Sent from the website with IP Address: " . $ip . " -==";;
$headers = "From: $email,";
$send_contact=mail($to,$email,$subject,$message,$headers);
header("Location: domain");
}

error in PHP code for email validation

I am trying to create an email validation form for my database but am having a number of issues. When i try and run the code below i get the error no database selected.
I also get an undefined variable error. I want the put the name of the user into my database under the username field, but apparently $name is an undefined variable. error on line xx undefined variablemysql_query("INSERT INTO registrations (username, password, email, hash) VALUES( '". mysql_real_escape_string($name) ."',.
I am using WAMP server. The name of the database is sitememberdetails, and the name of the
table i need the information put into is registrations. I am pretty new to this - Could anyone tell me how i would define the variable and how i select the db( even though it already appears to be selected?)
<?php
$host = "localhost";
$username = "";
$password = "";
$databasename = "sitememberdetails";
$email="xxxxxx#xxxxxxxx.xxx";
$connection = mysql_connect($host,$username,$password) or die
("Error: ".mysql_error());
mysql_select_db($databasename);("sitememberdetails") or
die(mysql_error());
if(isset($_POST['name']) && !empty($_POST['name']) AND
isset($_POST['email']) && !empty($_POST['email'])){
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']); }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-
z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$msg = 'The email you have entered is invalid, please try again.';
}else{
$msg = 'Your account has been made, <br /> please verify it
by clicking the activation link that has been send to
your email.';
}
$hash = md5( rand(0,1000) );
$password = rand(1000,5000);
mysql_query("INSERT INTO registrations (username, password,
email, hash) VALUES(
'". mysql_real_escape_string($name) ."',
'". mysql_real_escape_string(md5($password)) ."',
'". mysql_real_escape_string($email) ."',
'". mysql_real_escape_string($hash) ."') ") or
die(mysql_error());
$to = $email; // Send email to our user
$subject = 'Signup | Verification'; // Give the email a subject
$message = '
Thanks for signing up!
Your account has been created, you can login with the following
credentials after you have activated your account by pressing
the url below.
Username: '.$name.'
Password: '.$password.'
Please click this link to activate your account:
http://www.yourwebsite.com/verify.php?email='.$email.'&
hash='.$hash.'
';
$headers = 'From:noreply#yourwebsite.com' . "\r\n"; // Set from
headers
mail($to, $subject, $message, $headers); // Send our email
?>
try changing this code
mysql_select_db($databasename);("sitememberdetails") or
die(mysql_error());
to this
mysql_select_db($databasename) or die(mysql_error());
EOL;
if (database_connection) {
unset($undefined_variable_error)
} else {
echo $undefined_variable_error;
}
// Because mysql_real_escape_string needs an open mysql connection
check out this modified code:
<?php
$host = "localhost";
$username = "";
$password = "";
$databasename = "sitememberdetails";
$email="xxxxxx#xxxxxxxx.xxx";
$connection = mysql_connect($host,$username,$password) or die ("Error: ".mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$name = "";
if(isset($_POST['name']) && !empty($_POST['name']) AND
isset($_POST['email']) && !empty($_POST['email'])){
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']); }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$msg = 'The email you have entered is invalid, please try again.'; }
else {
$msg = 'Your account has been made, <br /> please verify it
by clicking the activation link that has been send to your email.';
}
$hash = md5( rand(0,1000) );
$password = rand(1000,5000);
mysql_query("INSERT INTO registrations (username, password,email, hash) VALUES(
'". mysql_real_escape_string($name) ."',
'". mysql_real_escape_string(md5($password)) ."',
'". mysql_real_escape_string($email) ."',
'". mysql_real_escape_string($hash) ."') ") or die(mysql_error());
$to = $email; // Send email to our user
$subject = 'Signup | Verification'; // Give the email a subject
$message = ' Thanks for signing up!
Your account has been created, you can login with the following
credentials after you have activated your account by pressing
the url below.
Username: '.$name.'
Password: '.$password.'
Please click this link to activate your account:
http://www.yourwebsite.com/verify.php?email='.$email.'&
hash='.$hash.'
';
$headers = 'From:noreply#yourwebsite.com' . "\r\n"; // Set from
mail($to, $subject, $message, $headers); // Send our email
?>
and i advise you to use PDO instead of mysql_ functions
Seems like the $name value isn't getting posted to the form. You're mysql_escaping the name variable if it is set and isn't empty, but what happens if the name variable isn't set at all? There are no checks for this so it continues until it gets to the INSERT statement and causes an error.
Look at example #1 here to select the db. You have a semicolon after ($databasename); which doesn't make sense.
Here's some revised code, using PDO instead of mysql_*. Let me know if this one works and we can address any issues from there.
<?php
$host = 'localhost';
$dbname = 'sitememberdetails';
$user = '';
$pass = '';
try
{
$DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['email']) && !empty($_POST['email']))
{
$name = $_POST['name'];
$email = $_POST['email'];
}
else
{
$name = 'No Name';
$email = 'No Email';
}
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email))
{
$msg = 'The email you have entered is invalid, please try again.';
}else{
$msg = 'Your account has been made, <br /> please verify it by clicking the activation link that has been send to your email.';
}
$hash = md5( rand(0,1000) );
$password = rand(1000,5000);
$query = "INSERT INTO registrations (username, password, email, hash) VALUES('?', '?', '?', '?')";
$sth = $DB->prepare($query);
//By using ?'s and prepare/execute, PDO will prevent SQL Injection for you!
$sth->execute(array($name, md5($password), $email, $hash));
$to = $email; // Send email to our user
$subject = 'Signup | Verification'; // Give the email a subject
$message = 'Thanks for signing up! Your account has been created,
you can login with the following credentials after you
have activated your account by pressing the url below.
Username: '.$name.'
Password: '.$password.'
Please click this link to activate your account:
http://www.yourwebsite.com/verify.php?email='.$email.'&
hash='.$hash;
$headers = 'From:noreply#yourwebsite.com' . "\r\n"; // Set from header
mail($to, $subject, $message, $headers); // Send our email
?>

Categories