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.
Related
I would like to be able to run a php validate script to stop users form entering gibberish as their email address. I know we can have the form input type as email but that can be easily bypassed in developer tools and the database integrity damaged.
My insert page looks like this:
$email = $conn->real_escape_string($_POST['emailpost']);
$password = $conn->real_escape_string($_POST['passpost']);
$firstname = $conn->real_escape_string($_POST['firstnamepost']);
$lastname = $conn->real_escape_string($_POST['lastnamepost']);
$phonenumber = $conn->real_escape_string($_POST['phonenumberpost']);
$education = $conn->real_escape_string($_POST['institutionpost']);
$facebook = $conn->real_escape_string($_POST['facebookpost']);
$twitter = $conn->real_escape_string($_POST['twitterpost']);
$instagram = $conn->real_escape_string($_POST['instagrampost']);
$filename = $_FILES['uploadprofileimg']['name'];
$filename = $ran.$filename;
$filetmp = $_FILES['uploadprofileimg']['tmp_name'];
$filetype = $_FILES['uploadprofileimg']['type'];
move_uploaded_file($filetmp, "../userimages/".$filename);
$insertuser = "INSERT INTO elmtree_users (user, email, pw, firstName, lastName, profileimg, learninginstitute, phone, facebook, twitter, instagram) VALUES
('$username', '$email', '$password', '$firstname', '$lastname', '$filename', '$education', '$phonenumber', '$facebook', '$twitter', '$instagram')";
$resultinsert = $conn -> query($insertuser);
if(!$resultinsert){
echo $conn->error;
}else{
echo "<h2> Account successfully registered!</h2>
<h4>Please <a href='login.php'> <font class='text-success'><strong>login.</strong></font></a></h4><br><br><br><br>";
Like everyone is pointing out
making your own logging system is tricky. it required you to do additional steps to make the content secured. Not only to hackers but you as administrator of the database shouldn't have access to see your customers password in PlainText Most users will use the same password on your site as they used for there email password they registered with on your site..
It is more advisable to create login tools like laravel, Or simply research how to build a secure login system, because what we are seeing here in your code, is BAD, Not syntactically, but from a security stand point.
Me knowing you store passwords like that, I wouldn't register onto your website.
Any how not only that, But you really should have a look into mysqli binding
Or even, and something I like better is PDO_Mysql
Your code will not only be more clear to read, but will bind values directly to a a field within mysql ( no need to use real_escape_string no more )
Now to actually answer your question.
You probably should make some kind of javascript live validator on the field of your form directly.
then on PHP side, You can do a simple condition with REGXP and preg_match()
Have a look at https://regex101.com/r/SOgUIV/1 this is a regex that will validate EMAILs.
With this link, You should then experiment a bit with it, it has not only documentation on the side but also possibles quantifier and such.
if(preg_match("/^((?!\.)[\w-_.]*[^.])(#\w+)(\.\w+(\.\w+)?[^.\W])$/i",trim($_POST['Email']))){
//What ever is in here will get process when $_POST['emailpost'] is valid.
}
Edited ----
As some user pointed out in comments.
You would probably be better of using
if(filter_var($_POST['emailpost'],FILTER_VALIDATE_EMAIL){
//What ever is in here will get process when $_POST['emailpost'] is valid
}
Also if you want to make sure user has access to the email address account, You could also add two column within your users table, isConfirmed,ConfirmationCode
When the user register, You create a unique code and put it into ConfirmationCode then send the user an email with something along those line "Please click the following link to activate account www.yourWebSite.com/confirmationPage.php?Code=$TheActualCodeYouCreatedForThatUser"
Then once user get to that page, Change the field isConfirmed to '1' or true.
Once there on your website, you will be able to assume that only emails with isConfirmed is a real user.
To validate email you need to check a lot of stuff like
if the email already exists
if its a real email i.e check for presence of #
check for funny characters which are not supposed to be in an email.
then always encrypt your password
if ($_POST['submit']) {
$errors = array();
$email = $conn->real_escape_string($_POST['emailpost']);
$password = $conn->real_escape_string($_POST['passpost']);
$firstname = $conn->real_escape_string($_POST['firstnamepost']);
$lastname = $conn->real_escape_string($_POST['lastnamepost']);
$phonenumber = $conn->real_escape_string($_POST['phonenumberpost']);
$education = $conn->real_escape_string($_POST['institutionpost']);
$facebook = $conn->real_escape_string($_POST['facebookpost']);
$twitter = $conn->real_escape_string($_POST['twitterpost']);
$instagram = $conn->real_escape_string($_POST['instagrampost']);
$filename = $_FILES['uploadprofileimg']['name'];
$filename = $ran.$filename;
$filetmp = $_FILES['uploadprofileimg']['tmp_name'];
$filetype = $_FILES['uploadprofileimg']['type'];
move_uploaded_file($filetmp, "../userimages/".$filename);
if (strlen($email) && strlen($password) && strlen($firstname) && strlen($lastname) && strlen($phonenumber) && strlen($education) && strlen($facebook) && strlen($twitter) && strlen($instagram)) {
//check for a valid email
if(preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^",$email))
$errors['email'] = 'invalid email address';
//check for presence of # in email
if (!stristr($em,"#") OR !stristr($em,".") $errors['email'] = 'please enter an email';
//echeck if email already exists in database
$checkemail = $conn->get_row("SELECT * FROM elmtree_users WHERE email=".$email);
if( $conn->num_rows( $checkemail ) > 0 ) $errors['email'] = "User already exists with the email: " . $email;
//validate password
$minpasslen = 8;
if (strlen($password) < $minpasslen)
$errors['email'] = 'password is too short';
$finalpassword = MD5($password);
if (empty($errors)) {
$insertuser = "INSERT INTO elmtree_users (user, email, pw, firstName, lastName, profileimg, learninginstitute, phone, facebook, twitter, instagram) VALUES
('$username', '$email', '$finalpassword', '$firstname', '$lastname', '$filename', '$education', '$phonenumber', '$facebook', '$twitter', '$instagram')";
$resultinsert = $conn -> query($insertuser);
if(!$resultinsert){
echo $conn->error;
} else {
echo "<h2> Account successfully registered!</h2>
<h4>Please <a href='login.php'> <font class='text-success'><strong>login.</strong></font></a></h4><br><br><br><br>";
} else {
echo implode('<br>', $errors);
}
}
}
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
So I'm making a registration/login/you know what I'm talking about system, and I need to verify the user's email addresses in case they forget their password. To do that, I assign them a random PIN which gets sent to them by email. Then, they enter that PIN in the account activation page and yay their account becomes active.
Now, my problem is the e-mail just isn't sending.
I'm using PHP 5.5 on Hostinger, my MX records aren't set up but from the questions that I've read about this, it's not what's causing the problem. Here is the code:
<?php
// connect to database, I'll omit the details because no one cares
$pin=rand(1000,9999);
$email=$_POST['email'];
$rawUser=$_POST['user'];
$user=// hash username but I'm not gonna tell you how because safety reasons
$rawPassA=$_POST['pass1'];
$rawPassB=$_POST['pass2'];
if($rawPassA==$rawPassB){
// hash password, again I'm not gonna tell you how
} else{
echo "<script type='text/javascript'>
window.location.href = 'http://komodokrew.ml/error/login/pass_no_match';
</script>";
};
$first=$_POST['first'];
$checkForUserQuery='SELECT count(*) FROM tableNameThatImNotGonnaTellYouBecauseSqlInjection WHERE user = \'' . $user . '\';';
$checkForUser=mysql_query($checkForUserQuery);
$checkForUserA=mysql_fetch_row($checkForUser);
$checkForUserF=$checkForUserA[0];
if($checkForUserF==0){
$query='INSERT INTO tableNameThatImNotGonnaTellYouBecauseSqlInjection (`user`,`first_name`,`pin`,`password`,`email`,`active`) VALUES (\'' . $user . '\',\'' . $first . '\',' . $pin . ',\'' . $pass . '\',\'' . $email . '\',1);';
mysql_query($query);
$subject='KomoDoKrew - account activation';
$message='You have recently registered an account on KomoDoKrew, under the username ' . $rawUser . '. Please activate your account by visiting komodokrew.ml/activate and entering the following PIN code, your username, and your password. PIN code: ' . $pin . '. Thank you for registering an account with KomoDoKrew! Make sure to join the community at komodokrew.ml/forum.';
$from='admin#komodokrew.ml';
$headers='From:' . $from;
mail($email,$subject,$message,$headers);
echo "<script type='text/javascript'>
window.location.href = 'http://komodokrew.ml/success/login/register';
</script>";
} else{
echo "<script type='text/javascript'>
window.location.href = 'http://komodokrew.ml/error/login/user_exists';
</script>";
};
mysql_close();
?>
Also, yes I KNOW that I'm vulnerable to SQL injections, I'm working on learning prepared statements and PDO, and yes I KNOW that mysql_* is way outdated, I'm working on learning the new PDO stuff, okay? But even if they SQL-injected me, it redirects them after they register anyways, and passwords and usernames are hashed with a varying salt several hundreds of thousands of times, so I'm not too worried at the moment.
This is the typical log that's sent in php_mail.log:
[23-Nov-2016 22:20:28 UTC] mail() on [/home/u964873932/public_html/register/register.php:40]: To: <myEmailAddressThatImNotGonnaTellYou> -- Headers: From:admin#komodokrew.ml
It's not a problem with PHP not being able to get the POST, because the email address of the user gets entered in the database successfully.
Thanks!
I would recommend to do 2 things first:
1. Enable error log:
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
2. And change the line where you are sending email
$status = mail($email,$subject,$message,$headers);
if($status)
{
echo '<p>Your mail has been sent!</p>';
} else {
echo '<p>Something went wrong, Please try again!</p>';
}
Then see if you got any error if no error then Follow this answer: PHP mail form doesn't complete sending e-mail
I've got email function setup and working by setting the code to email a specific email address. However, with this is that it goes to the same email address everytime the submit button is pressed based on the data entered in a text box who the mail comes from.
However, I want to change it so that when a user enters their username in the username box it checks my database table for that username and checks their email address and emails them all the information set for that user.
The code i'm using is ;
$username = $_POST['username'];
$my_query="SELECT * from loanusers where username = '$username'";
$result= mysqli_query($connection, $my_query);
$to = $myrow["emailaddess"];
$subject = 'CSG - Forgotten Password';
$sender = 'CSGLoanSystem#mail.com';
$password = $myrow["password"];
$admin = 'CSGLoanSystem Admin Team';
$body = <<< EMAIL
Hi {$username}, You have recently requested a notification of your password.
The Password registered with account {$username} is $password.
Thanks - {$admin}
EMAIL;
$header = "From:" . $sender;
if ($result):
mail($to, $subject, $body, $header);
$feedback = 'Email Sent';
endif;
At the moment when the submit button is pressed, the page refreshes but nothing actually happens and no email is received at the expected email address?
Pointing to the right direction:
Read up on MySQL and PDO. Also Read up on prepared statements and parameter binding.
Elaborating on the directions given:
There are many ways to connect to a database, and there are many different databases available. One popular database software is called MySQL, and the coding method that is most recommended to connect to that database is PDO for reasons such as having better methods for preventing security breaches.
You can find a lot of online tutorials on how to connect to a database, so I won't go into that, though I will however give you an example of a query you could use to do your email searching, and also I'll include prepared statements and parameter binding since these two details are often misunderstood by a lot of programmers.
If you have the following table:
users
______________________________
| username | email |
|------------+-----------------|
| john44 | abc#gmail.com |
|------------+-----------------|
| adam11 | 123#gmail.com |
|------------+-----------------|
the following code would allow you to retrieve john44's email:
$username = $_POST['username'];//getting the username written in the form
$sql = "SELECT email FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$username]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
//here I'm just outputting the obtained email for you to see
//it works, however you would then use the email saved in
//$result['email'] whichever way you want.
echo "email = {$result['email']}<br>";
Edited:
After you edited your code, I noticed you are not fetching the information you queried. Insert the following code after line $result= mysqli_query($connection, $my_query);:
$myrow = mysqli_fetch_assoc($result);
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
}
I use the following code to register users on my site. The problem is that when a user registers apache doesn't respond and crashes.
Is there a break in my code or something I am doing wrong????
<?php
include ('../includes/db_connect.php');
$firstname = $_POST['firstname'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = md5($_POST['password']);
// lets check to see if the username already exists
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
$username_exist = mysql_num_rows($checkuser);
if($username_exist > 0){
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
//include 'register.html';
exit();
}
// lf no errors present with the username
// use a query to insert the data into the database.
$query = "INSERT INTO users (firstname, email, username, password)
VALUES('$firstname', '$email', '$username', '$password')";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "You have successfully Registered";
// mail user their information
//$yoursite = ‘www.blahblah.com’;
//$webmaster = ‘yourname’;
//$youremail = ‘youremail’;
//
//$subject = "You have successfully registered at $yoursite...";
//$message = "Dear $firstname, you are now registered at our web site.
// To login, simply go to our web page and enter in the following details in the login form:
// Username: $username
// Password: $password
//
// Please print this information out and store it for future reference.
//
// Thanks,
// $webmaster";
//
//mail($email, $subject, $message, "From: $yoursite <$youremail>\nX-Mailer:PHP/" . phpversion());
//
//echo "Your information has been mailed to your email address.";
?>
this script will NOT cause apache to die. on this side theres nothing wrong with it.
however i dont know whats in db_connect.php
the mailing is deactivated, this indeed could take a very long time if the server settings are not correctly. e.g. if the server cant find its fully qualified domain name as your comments suggests.
do you have a session active? this could explain why you cant access any website while the other one is still running and sending the mail and it may look to you like apache crashed.
because you didnt call session_write_close and only once session can be active for writing at a time.
whats definately wrong is the vulnerability to mysql injection.
you absolutely need to change your variables the following way:
$firstname = mysql_real_escape_string($_POST['firstname']);
$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);
furthermore i would recommend just having a unique que on username and try the insert and see whether you get an error or if you get an mysq_insert_id. let mysql do the job.
but your check is fine too.. but you should have a constraint in the database too, just as a precaution.
and you should trim your values and maby allow only certain chars, its annoying if a username on a website is &%DTRFG$Ä←↓ff