Allow For Both Email and Database Entry On Submit - php

Hi I've had this in place for sometime and have been doing things the hard way. It simply goes to the database and I check it frequently, but as you can assume this is a terribly tedious way of doing things. Here is my current code.
<?php
$name = "";
$email = "";
$msg_to_user = "";
if ($_POST['name'] != "") {
include_once "newsletter/connect_to_mysql.php";
// Be sure to filter this data to deter SQL injection, filter before querying database
$name = $_POST['name'];
$email = $_POST['email'];
$sql = mysql_query("SELECT * FROM newsletter WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if (!$email) {
$msg_to_user = '<br /><br /><span style="font color="FF0000">Please type an email address ' . $name . '.</span>';
} else if ($numRows > 0) {
$msg_to_user = '<br /><br /><font color="FF0000">' . $email . ' is already in the system.</font>';
} else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime)
VALUES('$name','$email',now() )") or die (mysql_error());
$msg_to_user = '<br /><br /><div style="color=#F47926;width:180px;">Thanks ' . $name . ', expect an email shortly!</div>';
$name = "";
$email = "";
}
}
?>
I'm trying to add a simple way to do send and email with the email and name to my own email address. This way I'd not have to do any frequent checks of the database itself, but rather view them as they appear in my email. I hope this makes sense.

It would be wise to do some additional checks to validate the data being passed through $_POST.
Something like this should get you started.
$email = filter_var($_POST['Email'], FILTER_VALIDATE_EMAIL);
Here is how you would send an email message.
$message = 'Name: ' . $_POST['name'] . ', Email: ' . $_POST['email'];
mail('your#email.com', 'A New User Has Signed Up', $message);
http://php.net/manual/en/function.mail.php
http://php.net/manual/en/function.filter-var.php

i dont really know what needs to be done, but if you are askng for improvements or suggestions...
instead of this:
$msg_to_user = '<br /><br /><span style="font color="FF0000">Please type an email address ' . $name . '.</span>';
you can do this:
$msg_to_user = "<br /><br /><span style='color:FF0000'>Please type an email address {$name}.</span>";
note: use double quotes.

Related

PHP mail() vaildation

so i'm still relatively new to PHP and have been building a order form that can validate the fields before sending, as well as checking for spam.
From testing the below code works fine in returning errors and so on, but when I enter correct information I dont get any emails.
It was working fine before i added the Vaildation part to it but now im getting the problem above. Again i am still learning so any pointers would be nice, thanks
<?php
function spamcheck($field) {
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>
<?php
if (!isset($_POST["submit"])) {
?>
Form
<?php }
else
{
if (isset($_POST["email"])) {
$mailcheck = spamcheck($_POST["email"]);
if ($mailcheck==FALSE) {
echo "Invalid input";
}
//field vailation
else {
if (isset($_POST['submit'])) {
$errors = array();
if (!empty($_POST["fullname"])) {
$fullname = $_POST["fullname"];
$pattern = "/^[a-zA-Z0-9\_]{2,20}/";
if (preg_match($pattern,$fullname)){ $fullname = $_POST["fullname"];}
else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}
} else {$errors[] = 'You forgot to enter your First Name.';}
if (!empty($_POST["contact"])) {
$contact = $_POST["contact"];
$pattern = "/^[0-9\_]{6,20}/";
if (preg_match($pattern,$contact)){ $contact = $_POST["contact"];}
else{ $errors[] = 'Your contact number can only be numbers, or is too short';}
} else {$errors[] = 'You forgot to enter your contact number.';}
}
//end vaildation
else{
$fullname = $_POST["fullname"];
$email = $_POST["email"];
$address = $_POST["address"];
$address2 = $_POST["address2"];
$town = $_POST["town"];
$postcode = $_POST["postcode"];
$contact = $_POST["contact"];
$shipping = $_POST["shipping"];
$extra = $_POST["extra"];
$extra = wordwrap($extra, 70);
$message = '
Full Name: ' . $fullname . '
Delivery Address: ' . $address . '
Delivery Address2: ' . $address2 . '
Town/City: ' . $town . '
Postal Code: ' . $postcode . '
Contact: ' . $contact . '
Email Address: ' . $email . '
Special instructions: ' . $extra . '
Shipping Method: ' . $shipping . '
';
mail("myemail#myaddress.com","Order form",$message,"email: $email\n");
echo
"<html>
<body><br><br>
Order successful, we will be in contact shortly<br>
</body>
</html>";
}
}
}
}
?>
<?php
if (isset($_POST['submit'])) {
if (!empty($errors)) {
echo '<hr /><h3>The following occurred:</h3><ul>';
foreach ($errors as $msg) { echo '<li>'. $msg . '</li>';}
echo '</ul><h3>Your mail could not be sent due to input errors.</h3><hr />';}
else{echo
"<html>
<body><br><br>
Order successful, we will be in contact shortly<br>
</body>
</html>";
}
}
?>
After using error_reporting(E_ALL); ive noticed that im getting an error unexpected 'else' (T_ELSE) for the else at the top of the second block of code, so I tried moving code to :
<?php
error_reporting(E_ALL);
if (!isset($_POST["submit"])) {
}
else
{
And left the form above this so that when the sumbit button is pressed the forms wont dissapear. Which is not giving me any errors but still not email once submitted

Capture ip address of machine of the user

<?php
if (isset($_GET['action']) && ($_GET['action'] == 'submit')) {
$name = $_POST['name'];
$message = $_POST['message'];
$email = $_POST['email'];
$ip = $_SERVER["REMOTE_ADDR"];
$messageip = "User IP: $ip\n\n" . $messageip;
$sql = "SELECT * FROM tbl_user WHERE email = '" . $email . "'";
$query = mysql_query($sql);
$count = mysql_num_rows($query);
if ($count >= 1) {
echo "User Already in Exists<br/>";
} else {
$newUser = "INSERT INTO tbl_user(name,message,email,ip_address) values('$name','$message','$email','$messageip')";
$query2 = mysql_query($newUser);
if ($query2) {
echo "You are now registered<br/>";
} else {
echo "Error adding user in database<br/>";
}
}
echo $name . '<br/>';
echo $message . '<br/>';
echo $email . '<br/>';
echo $messageip . '<br/>';
}
?>
I am using this code to capture the ip address but i cannot get the machine ip of the particular user from which i can display the address by dynamically, so can anyone help me out on this topic?
You seem to be concatenating a wrong (empty) var.
Try changing this:
$messageip = "User IP: $ip\n\n" . $messageip;
to this:
$messageip = "User IP: $ip\n\n" . $ip;

Simple query not running

First off, I am aware I am open to SQL injection, this is just a prototype. But it still should be working.
For the life of me I can't figure out why I can't pull an item out of my array. What could I possibly be doing wrong? I've been fiddling with this seemingly simple query for way too long and I can't seem to get it to pull out data. I feel like it is something so simple....
$query = 'SELECT * FROM users WHERE email = "' . $email . '"';
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$ID = $row['ID'];
I am getting no result for $ID ....
Here is my entire code:
<html>
<head>
<?php
$email = $_GET["email"];
$servername="localhost";
$username="*****";
$password="*****";
$database="*****";
$conn= mysql_connect($servername,$username,$password)or die(mysql_error());
mysql_select_db("$database",$conn);
$query = 'SELECT email FROM users WHERE email = "' . $email . '"';
$result = mysql_query($query) or die(mysql_error());
//Checks if the email address exists in the system already
if (mysql_num_rows($result) ) {
die("Duplicate email found!");
}
else {
//use current date/time combination times the number 11 times the ID to get a unique confirmation number.
$query = 'SELECT * FROM users WHERE email = "' . $email . '"';
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$ID = $row['ID'];
echo $row;
$date = date("mydhis");
$date2 = $date * 11 * $ID;
echo $ID . " <-> " . $date . " <-> <p>" . $date2;
$sql="insert into users (first,last,displayname,email,password,verification_email)values('$_GET[first]','$_GET[last]','$_GET[display]','$_GET[email]','$_GET[password]','$date2')";
$result=mysql_query($sql,$conn) or $string = mysql_error();
$confirmlink = "http://www.somewebsite.com/android/confirm.php?" . $date2;
$to = $_GET['email'];
$subject = "Thank you for Registering!";
$message = "Hello " . $_GET['display'] . " and thank you for registering with the Smeet app! To confirm your email address (and let us know you aren't a bot), please click the following link: " . $confirmlink;
$from = "noreply#smeet.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers) or die('You have successfully registered however mail servers are currently down, you may or may not receive a confirmation email');
print "<h1>You have registered successfully</h1>";
print "You will receive an email shortly with instructions on how to confirm your email address.</a>";
}
?>
</body>
</html>
Thanks for any help at resolving this.
It was a simple answer and I figured it out!
My $ID was being pulled before the record was created, that's why it was blank! Dumb mistake on my part.

PHP sending emails twice and not uploading images correctly :/

I have been designing a website and everything has been working perfectly, until I started adding in little extras so it would work EXACTLY how I wanted it to work.
This is the script for a website that uploads a title, description, name of a person, image, email address and password for the advert that they are putting online. However it no longer wants to correctly name the image and it sends out an email twice, once in the instance that there may be an image and it instantly does it in the instance where someone may not upload an image, but it is reading it as if it is doing both because there is an error with the file upload.
Btw this is the first PHP script I have ever created so it may seem mashy as I have been kind of mixing it up from different things that I have found online :)
p.s the page where the magic happens is www.afterswap.com/give.php
p.p.s I have a global config file that sets all of the DB connection info etc, hence it being non-existent here.
<?PHP
include("inc/header.php");
foreach ($_POST as $key => $val)
$_POST[$key] = mysqli_real_escape_string($con, $val);
$back = "<a href='give.php'>Click Here To Go Back And Try Again</a>";
if (isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) {
$title = mysqli_real_escape_string($title123);
$title123 = mysqli_real_escape_string($_POST['title']);
$description = mysqli_real_escape_string($description123);
$description123 = mysqli_real_escape_string($_POST['description']);
$Sell_by = $_POST['Sell_by'];
$name = mysqli_real_escape_string($name123);
$name123 = mysqli_real_escape_string($_POST['name']);
$email = $_POST['email'];
$password = $_POST['password'];
$imagename = basename($_FILES['userfile']['name']);
$uploadedfile = $_FILES['userfile']['tmp_name'];
if (empty($imagename)) {
$error = 1;
echo "<h2 class='error'>The name of the image was not found.</h2>" . $back;
}
if ($error != 1 && $noimg != 1) {
$filename = stripslashes($_FILES['userfile']['name']);
$extension = substr(strrchr($filename, '.'), 1);
$extension = strtolower($extension);
}
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
echo '<h2 class="error">Error. Images Must Be Jpg, Gif, or Png Format! Please Go Back And Try Another Image.</h2>' . $back . '';
$errors = 1;
} else {
$time = time();
$newimage = "/photos/" . $time . $imagename;
$result = move_uploaded_file($_FILES['userfile']['tmp_name'], $newimage);
if (empty($result)) {
$error = 1;
echo "<h2 class='error'>There was an error uploading your image.</h2><br/>" . $back . "";
}
$date = date("Y/m/d H:i:s");
$query = "INSERT INTO classifieds (adid, title, description, Sell_by, name, email, password, picture, date, views, authorized ) VALUES ('', '$title123', '$description123', '$Sell_by', '$name123', '$email', '$password', '$newimage', '$date', '0', '0')";
mysqli_query($query) or die(mysqli_error());
$pullback = "SELECT * FROM classifieds WHERE title = '$title123' AND email ='$email' limit 1";
$query2 = mysqli_query($pullback) or die(mysqli_error());
while ($row = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
$newid = $row['adid'];
$pass = $row['pass'];
}
$url = "http://";
$url .= getenv("HTTP_HOST");
$Name = "AfterSwap";
$emailf = "noreply#afterswap.com";
$recipient = $email;
$mail_body = "Thank you for posting a new listing!<br /><br />You May Now Manage Your Ad by selecting one of the following options:<br /><br />Approve your listing: <a href='" . $url . "/approve.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Edit your listing: <a href='$url/edit.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Remove your listing: <a href='" . $url . "/remove.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br /><br />Regards,<br /><br />The AfterSwap Team";
$subject = "AfterSwap Ad Details";
$headers = "From: " . $Name . " <" . $emailf . ">\r\n";
$headers .= "Content-type: text/html\r\n";
mail($recipient, $subject, $mail_body, $headers);
echo "<div align='justify'><div class='success'>Your listing '" . $name123 . "' Has Been Submitted Successfully! <br/><br/>Please take note: Your listing will not show on the website until you verify it via the email sent to you. This email also allows you to edit and remove your listing as well.</div></div>";
}
} elseif (isset($_POST['upload'])) {
$title = mysqli_real_escape_string($title123);
$title123 = mysqli_real_escape_string($_POST['title']);
$description = mysqli_real_escape_string($description123);
$description123 = mysqli_real_escape_string($_POST['description']);
$Sell_by = $_POST['Sell_by'];
$name = mysqli_real_escape_string($name123);
$name123 = mysqli_real_escape_string($_POST['name']);
$email = $_POST['email'];
$password = $_POST['password'];
$date = date("Y/m/d H:i:s");
$query = "INSERT INTO classifieds (adid, title, description, cat, Sell_by, name, email, password, picture, date, views, authorized ) VALUES ('', '$title123', '$description123', '$category', '$Sell_by', '$name123', '$email', '$password', 'images/noimage.jpg', '$date', '0', '0')";
mysqli_query($query) or die(mysqli_error());
$pullback = "SELECT * FROM classifieds WHERE title = '$title123' AND email ='$email' limit 1";
$query2 = mysqli_query($pullback) or die(mysqli_error());
while ($row = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
$newid = $row['adid'];
$pass = $row['pass'];
}
$url = "http://";
$url .= getenv("HTTP_HOST");
$Name = "AfterSwap";
$emailf = "noreply#afterswap.com";
$recipient = $email;
$mail_body = "Thank you for posting a new listing!<br /><br />You May Now Manage Your Ad by selecting one of the following options:<br /><br />Approve your listing: <a href='" . $url . "/approve.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Edit your listing: <a href='$url/edit.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Remove your listing: <a href='" . $url . "/remove.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br /><br />Regards,<br /><br />The AfterSwap Team";
$subject = "AfterSwap Ad Details";
$headers = "From: " . $Name . " <" . $emailf . ">\r\n";
$headers .= "Content-type: text/html\r\n";
mail($recipient, $subject, $mail_body, $headers);
echo "<div align='justify'><div class='success'>Thank you " . $name123 . ", your listing has been submitted successfully! <br/><br/>Please take note: Your isting will not show on the website until you verify it via the email sent to you. This email also allows you to edit and remove your listing as well.</div></div>";
} else {
?>
/* HTML Form here */
<?PHP } ?>
Try this
Change this line
} elseif (isset($_POST['upload'])) {
to
} elseif (isset ( $_POST ['upload'] ) && empty($_FILES)) {
The only thing I can think of would be a if, elseif, or else being passed twice because the condition is being met twice. You may want to revise the code with better indentation, and checking when the elseif, if, and else blocks are passed. Also, it would be a really good idea to take the advice from the two people that commented on your post, MYSQLI is a great way to go! One more thing: You should never pass $_POST unsanitized!! Here is a short easy sanitization script!
MYSQLI:
foreach($_POST as $key=>$val)
$_POST[$key] = mysqli_real_escape_string($con, $val);
MYSQL:
foreach($_POST as $key=>$val)
$_POST[$key] = mysql_real_escape_string($con, $val);

Php If statement not working as expected

I am making an email script in php. What happens is a mysql query is made, and the output of this is stored in the following strings :
$personal1 = $userinfo->salutation;
$personal2 = $userinfo->surname;
$business = $userinfo->businessname;
Next I have an if statement, this checks to see if the surname is blank, if it is, it then substitutes the salutation + surname with the business name. The problem I am having is that the emails keep being sent out with Dear, Business Name , even if the surname field is not blank, I am not sure what I am doing wrong with the following code for it to do this though ?.
if ($personal2=="") {
$name = $business; }
else {
$name = $personal1 . ' ' . $personal2;};
EDIT >>>>>>>>>>
If I echo out the contents of the strings I get :
personal1 = Mr
personal2 = Johnson
business = Hat Trick Media
Edit 2 >>>>>>>
This is some of the code, it is then passed onto the mailer.
<?php
$cf_uid = $_GET['token'];
$query = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addupdatelead WHERE cf_uid = '$cf_uid'") or die(mysql_error());
$userinfo = mysql_fetch_object($query);
$personal2 = $userinfo->surname;
$personal1 = $userinfo->salutation;
$business = $userinfo->businessname;
?>
<?php
$result = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addemailtemplate");
while ($row = mysql_fetch_object($result)) {
echo '<tr class="table-row">';
echo '<th class="template-name">';
echo '<div class="namerow">';
$id = $row->cf_uid;
$form_id = $row->form_id;
$query = mysql_query("SELECT `$form_id` FROM email_history WHERE cf_id = '$user_id'") or die(mysql_error());
$datesent = mysql_fetch_object($query);
$date = $datesent->$form_id;
if ($personal2=="") {
$name = $business; }
else {
$name = $personal1 . ' ' . $personal2;};
Is your code a valid statement? Your code structure is awful. Instead of...
if ($personal2=="") {
$name = $business; }
else {
$name = $personal1 . ' ' . $personal2;};
Use
if ($personal2=="") {
$name = $business;
}
else {
$name = $personal1 . ' ' . $personal2;
}
You seem to have an extra ; that you dont need.
You also dont seem to close the while loop in the code you posted...
Ok, I have found out what the problem was, $name was coming in the session from the previous page and overwriting $name on this page, I have now set it to destroy the session before it loads this page and it seems to have sorted it now, thanks for everyone's help :-)

Categories