Mail could not be send using php - php

Hope all of my experts are fine. Buddy's i stuck in a very simple code. Actually i have to insert a form and then fetch values from it to send mail to the user who fills the form. All the values are inserting into the database and also fetch from database but mail is not sending. The same code was sending mail one day ago. But today it is not sending mail. Please help me out in this.
<?php
require("dbconnect.php");
require("DBConnection.php");
session_start();
if(isset($_POST['postadd'])){
$title = $_POST['adtitle'];
$area = $_POST['area'];
$addesc = $_POST['addesc'];
$email = $_POST['email'];
$showemail = $_POST['showemail'];
$userpic = ($_FILES['pic1']['tmp_name']);
$compath = "UploadPictures/".md5($_FILES['pic1']['name']);
$comFileType=$_FILES['pic1']['type'];
$comFileSize=$_FILES['pic1']['size'];
$comFileSize=$comFileSize/1024;
if($comFileSize<1000)
{
$arrFileType=array("image/jpeg","image/png","image/gif","image/bmp");
if(in_array($comFileType,$arrFileType))
{
move_uploaded_file($userpic,$compath);
}
else
{
("Invalid Image Format");
}
}
else
{
("File Size Error");
}
$pic2 = ($_FILES['pic2']['tmp_name']);
$compath2 = "UploadPictures/".md5($_FILES['pic2']['name']);
$comFileType2=$_FILES['pic2']['type'];
$comFileSize2=$_FILES['pic2']['size'];
$comFileSize2=$comFileSize2/1024;
if($comFileSize2<1000)
{
$arrFileType2=array("image/jpeg","image/png","image/gif","image/bmp");
if(in_array($comFileType2,$arrFileType2))
{
move_uploaded_file($pic2,$compath2);
}
else
{
("Invalid Image Format");
}
}
else
{
("File Size Error");
}
$pic3 = ($_FILES['pic3']['tmp_name']);
$compath3 = "UploadPictures/".md5($_FILES['pic2']['name']);
$comFileType3=$_FILES['pic3']['type'];
$comFileSize3=$_FILES['pic3']['size'];
$comFileSize3=$comFileSize3/1024;
if($comFileSize3<1000)
{
$arrFileType3=array("image/jpeg","image/png","image/gif","image/bmp");
if(in_array($comFileType3,$arrFileType3))
{
move_uploaded_file($pic3,$compath3);
}
else
{
("Invalid Image Format");
}
}
else
{
("File Size Error");
}
$pic4 = ($_FILES['pic4']['tmp_name']);
$compath4 = "UploadPictures/".md5($_FILES['pic4']['name']);
$comFileType4=$_FILES['pic4']['type'];
$comFileSize4=$_FILES['pic4']['size'];
$comFileSize4=$comFileSize4/1024;
if($comFileSize4<1000)
{
$arrFileType4=array("image/jpeg","image/png","image/gif","image/bmp");
if(in_array($comFileType4,$arrFileType4))
{
move_uploaded_file($pic4,$compath4);
}
else
{
("Invalid Image Format");
}
}
else
{
("File Size Error");
}
$agree = $_POST['checkbox'];
$subcat = $_SESSION['subcat'];
$cat = $_SESSION['cat'];
$rand = rand();
$datecreated = date("Y-m-d h:i:s");
$obj = new DBConnection();
$arr_Field = array("title","location","post","email","radio","pic1","pic2","pic3","pic4","agree","cat","subcat","random","datecreated");
$arr_values = array("$title","$area","$addesc","$email","$showemail","$compath","$compath2","$compath3","$compath4","$agree", "$cat", "$subcat" ,"$rand","$datecreated");
$obj->InsertRecord("ads",$arr_Field,$arr_values) or die (mysql_error());
$object = new DBConnection();
$condition = "ORDER BY id DESC LIMIT 1";
$selquery = $object->SelectRecord(array("*"),"ads","$condition") or die(mysql_error());
while($get = mysql_fetch_array($selquery)){
$email = $get['email'];
$id = $get['id'];
}
//echo $email;
//exit();
$to = $email;
$subject = "Admin";
$message = "
<html>
<head>
<title>Admin</title>
</head>
<body>
<p>Please Click on this Link to verify your post</p>
<p><a href='http://almughnisolutions.com/almughniclassified/summary.php?summary=".$id."'>http://almughnisolutions.com/almughniclassified/summary.php?summary=".$id."</a></p>
</body>
</html>
";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= 'From: <admin#almughniclassfied.com>' . "\r\n";
mail($to,$subject,$message,$headers) or die("Mail Cannot sent");
//header("Location:verifyadd.php");
}
?>

It would probably be a safe assumption that your code is not to blame. A cursory review of it seems like it shuold work if the SMPT server is behaving correctly. I would recommend testing the server. There are a some web based tools to do this:
https://www.wormly.com/test_smtp_server
You could also just use telnet to test from your machine if it's something that will need to be done internally:
http://technet.microsoft.com/en-us/library/aa995718%28v=exchg.65%29.aspx

Related

Insert Images PHP Mysql

I'm trying to insert four images to the database but first image only getting inserted. The first image I could fetch but other images are not returned. But in the table image name are showing.
<?php
header("Location:../index.php");
// Create database connection
$db = mysqli_connect("localhost", "root", "", "alu");
// Initialize message variable
$msg = "";
//If upload button is clicked ...
if (isset($_POST['submit'])) {
//Get image name
$txtproducttitle = $_POST['txtproducttitle'];
$txtProductDescription = $_POST['txtProductDescription'];
$txtProdutPrice = $_POST['txtProdutPrice'];
$AdCondition = $_POST['AdCondition'];
$PrImg1 = $_FILES['PrImg1']['name'];
$PrImg2 = $_FILES['PrImg2']['name'];
$PrImg3 = $_FILES['PrImg3']['name'];
$PrImg4 = $_FILES['PrImg4']['name'];
$AdCategory = $_POST['AdCategory'];
$AdLocation = $_POST['AdLocation'];
$txtname = $_POST['txtname'];
$txtuseremail = $_POST['txtuseremail'];
$txtContact = $_POST['txtContact'];
$AdPayment = $_POST['AdPayment'];
$target = "../upload/".basename($PrImg1);
$sql = "INSERT INTO advertisement (AdTitle, AdDes, AdPrice,
AdCondition, AdImg1, AdImg2, AdImg3, AdImg4, AdCategory, AdLocation,
AdSellName, AdSellMail, AdSellContact, AdPayment)
VALUES ('$txtproducttitle','$txtProductDescription','$txtProdutPrice','$AdCondition','$PrImg1','$PrImg2','$PrImg3','$PrImg4','$AdCategory','$AdLocation','$txtname','$txtuseremail','$txtContact','$AdPayment')";
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['PrImg1']['tmp_name'], $target)) {
$msg = "Ad Successfully Posted";
}else
{
$msg = "Failed To Post Ad";
}
}
$result = mysqli_query($db, "SELECT * FROM advertisement");
You need to use move_uploaded_file function for other images.
Use:
if (move_uploaded_file($_FILES['PrImg2']['tmp_name'], $target2)) {
$msg = "Ad2 Successfully Posted";
}
else
{
$msg = "Failed To Post Ad2";
}
if (move_uploaded_file($_FILES['PrImg3']['tmp_name'], $target2)) {
$msg = "Ad3 Successfully Posted";
}
else
{
$msg = "Failed To Post Ad2";
}
if (move_uploaded_file($_FILES['PrImg4']['tmp_name'], $target2)) {
$msg = "Ad4 Successfully Posted";
}
else
{
$msg = "Failed To Post Ad4";
}

php email reminder script issue

I am building a script that checks for dates that will expire within 7 days and sends out a email reminder to the admin owner and also update a date notified column in the database, I have got it sort of working, it updates the date notified column and sends the email out but it only lists one date in the email where as there should be two as I set two dates to expire within 7 days, can anyone help please, below is the coding I have
<?php
$db = mysqli_connect("localhost" , "", "") or die("Check connection parameters!");
// Optionally skip select_db and use: mysqli_connect(host,user,pass,dbname)
mysqli_select_db($db,"") or die(mysqli_error($db));
if (mysqli_connect_error()) {
die ('Failed to connect to MySQL');
} else {
/*SUCCESS MSG*/
echo '';
}
$sqlCommand = "SELECT
u.id
, domain_name_owner
, url
, DATE_FORMAT(domain_expiry_date, '%e %M %Y') as domain_expiration_date
, domain_owner_email
FROM websites u
WHERE domain_expiry_date BETWEEN CURDATE() AND CURDATE()+INTERVAL 7 DAY
";
$query = mysqli_query($db, $sqlCommand) or die (mysqli_error($db));
//fetch the data from the database
while ($row = mysqli_fetch_array($query)) {
$arr_ids[] = $row['id'];
$email = '';
$headers = "From: noreply#domain.co.uk\r\n";
$subject = "Domain Name Expiry Date(s)";
$message = '';
$id = $row['id'];
$owner = $row['domain_name_owner'];
$email = $row['domain_owner_email'];
$message = "Domain Name Owner: {$row['domain_name_owner']} \n\n";
$message .= "Your Domain Name {$row['url']} expiry date is: {$row['domain_expiration_date']}\n";
$to = $email;
$sendmail = mail($to, $subject, $message, $headers);
if ($sendmail) {
echo nl2br($message);
echo "<b>Email Successfully Sent</b><br><br>";
} else {
echo "<b>Error in Sending of Email to $to</b><br><br>";
}
}
if (isset($arr_ids)){
$sql = "UPDATE websites SET date_notified_of_domain_expiry = NOW() WHERE id IN (";
$sql .= implode("," , $arr_ids);
$sql .= ");";
print $sql;
}
//$db->query($sql);
$db->query($sql) or die(mysqli_error($db));
// Free the results
mysqli_free_result($query);
//close the connection
mysqli_close($db);
?>
Thank you in advance
Your Script is working fine, it should send one email per expiry date (based on your code), if the domain owner owns two domains, he will receive two separate emails that each one of them is related to a certain domain.
If you want to send the two domains on the same email, use the below script:
<?php
$db = mysqli_connect("localhost" , "", "") or die("Check connection parameters!");
// Optionally skip select_db and use: mysqli_connect(host,user,pass,dbname)
mysqli_select_db($db,"") or die(mysqli_error($db));
if (mysqli_connect_error()) {
die ('Failed to connect to MySQL');
} else {
/*SUCCESS MSG*/
echo '';
}
$sqlCommand = "SELECT
u.id
, domain_name_owner
, url
, DATE_FORMAT(domain_expiry_date, '%e %M %Y') as domain_expiration_date
, domain_owner_email
FROM websites u
WHERE domain_expiry_date BETWEEN CURDATE() AND CURDATE()+INTERVAL 7 DAY
";
$query = mysqli_query($db, $sqlCommand) or die (mysqli_error($db));
//fetch the data from the database
$message = '';
$email = '';
$prev_Email ='';
while ($row = mysqli_fetch_array($query)) {
$arr_ids[] = $row['id'];
$prev_Email = $email;
$headers = "From: noreply#domain.co.uk\r\n";
$subject = "Domain Name Expiry Date(s)";
$id = $row['id'];
$owner = $row['domain_name_owner'];
$email = $row['domain_owner_email'];
if($prev_Email == ""){
$prev_Email = $email;
}
if($email == $prev_email && $email != ""){
$message. = "Domain Name Owner: {$row['domain_name_owner']} \n\n";
$message .= "Your Domain Name {$row['url']} expiry date is: {$row['domain_expiration_date']}\n";
}else{
if($prev_Email != ""){
$to = $prev_Email;
$sendmail = mail($to, $subject, $message, $headers);
if ($sendmail) {
echo nl2br($message);
echo "<b>Email Successfully Sent</b><br><br>";
} else {
echo "<b>Error in Sending of Email to $to</b><br><br>";
}
$message = "Domain Name Owner: {$row['domain_name_owner']} \n\n";
$message .= "Your Domain Name {$row['url']} expiry date is: {$row['domain_expiration_date']}\n";
}
}
}
if (isset($arr_ids)){
$sql = "UPDATE websites SET date_notified_of_domain_expiry = NOW() WHERE id IN (";
$sql .= implode("," , $arr_ids);
$sql .= ");";
print $sql;
}
//$db->query($sql);
$db->query($sql) or die(mysqli_error($db));
// Free the results
mysqli_free_result($query);
//close the connection
mysqli_close($db);
?>

My php mail function is sending blank messages

So as the title states I receive blank emails from my contact form. The php code is below. I've checked the value of $msg and it appears correctly, I've also googled a ton and I can't find anything standard cause that apply to me.
<?php
main();
function main() {
$posted = setVariables();
$msg = setMessage($posted);
$result = sendMail($msg);
userFeedback($result);
}
function setVariables() {
$name;
if (isset($_POST['name'])){
$name=$_POST['name'];
if ($name == null) {
$name = "ERROR - name is null";
}
}
$email;
if (isset($_POST['email'])){
$email=$_POST['email'];
if ($email == null) {
$email = "ERROR - email is null";
}
}
$enquiry;
if (isset($_POST['enquiry'])){
$enquiry=$_POST['enquiry'];
if ($enquiry == null) {
$enquiry = "ERROR - enquiry is null";
}
}
$message;
if (isset($_POST['message'])){
$message=$_POST['message'];
if ($message == null) {
$message = "ERROR - message is null";
}
}
$posted = array($name,$email,$enquiry,$message);
return $posted;
}
function setMessage($posted) {
$msg = "Name: " . $posted[0] . "\r\nEmail: " . $posted[1] . "\r\nEnquiry: " . $posted[2] . "\r\nMessage: " . $posted[3];
$msg = wordwrap($msg,70);
$msg = Trim(stripslashes($_POST['Message']));
return $msg;
}
function sendMail($msg) {
$result = mail("social#georgeappleton.co.uk","Contact From Portfolio",$msg, "From: <info#yourdomain.co.uk>");
return $result;
}
function userFeedback($result) {
if ($result == false) {
echo "Message failed to send, please inform me through my email address. social#georgeappleton.co.uk";
} else {
echo "Message Sent!<br/><br/>Returning you to <a href='http://www.georgeappleton.co.uk'>georgeappleton.co.uk</a> in 5 seconds";
}
echo "<script>setTimeout(function() {window.location = 'http://www.georgeappleton.co.uk';},5000);</script>";
}
?>
Thanks guys, appreciate it a lot
-Shardj
Get rid of this line:
$msg = Trim(stripslashes($_POST['Message']));
It's overwriting $msg with the contents of a nonexistent parameter. It already contains the message text, which was in $posted[3].
It's your variable scope. $name withing setVariables()
$name=$_POST['name'];
if (strlen($name) < 1) {$name = "ERROR - name is null";}
$email=$_POST['email'];
if (strlen($email) < 1) {$email = "ERROR - email is null";}
$enquiry=$_POST['enquiry'];
if (strlen($enquiry) < 1) {$enquiry = "ERROR - enquiry is null";}
$posted = array($name,$email,$enquiry,$message);
$msg = setMessage($posted);
$result = sendMail($msg);
userFeedback($result);

Wordpress Help Redirect after form submission

I want to have my contact form redirect after form submission. I don't know how do it. This is my code and also it's giving me an error.
<?php
// If the form is submitted
if(isset($_POST['submit'])) {
// Include WordPress Core Functions
$wp_include = '../wp-load.php';
while(!#include_once($wp_include)) { $wp_include = '../'.$wp_include; }
//
// Field Validation
//
// Check to make sure that the name field is not empty
if(trim($_POST['cf_name']) == '') {
$has_error = true;
}
else {
$name = trim($_POST['cf_name']);
}
// Check to make sure that the subject field is not empty
if(trim($_POST['cf_subject']) == '') {
$has_error = true;
}
else {
$subject = trim($_POST['cf_subject']);
}
// Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$has_error = true;
}
elseif(!preg_match("/^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$/i", trim($_POST['email']))) {
$has_error = true;
}
else {
$email = trim($_POST['email']);
}
// Check to make sure comments were entered
if(trim($_POST['cf_message']) == '') {
$has_error = true;
}
else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['cf_message']));
}
else {
$message = trim($_POST['cf_message']);
}
}
//
// Send E-Mail
//
// Send the email if there is no error
if(!isset($has_error)) {
// Get recheiver
$receiver = ($_POST['cf_receiver']) ? $_POST['cf_receiver'] : get_option('admin_email');
$receiver = str_replace('[at]', '#', $receiver);
// Headers
$headers = "From: $name <$email>\n";
$headers.= "Content-Type: text/plain; charset=\"UTF-8\"\n";
// Message
if($_POST['cf_email_signature'] && $_POST['cf_email_signature'] != 'none') {
$message.= "\n\n---\n".$_POST['cf_email_signature'];
}
// Send E-Mail
$mail_sent = wp_mail($receiver, $subject, $message, $headers);
if($mail_sent)
echo "<p class='info-box success'>".$_POST['cf_success_msg']."</p>";
else
echo "<p class='info-box error'>The message couldn't be sent because an internal error occured.</p>";
echo "<p class='info-box error'>".$_POST['cf_error_msg']."</p>";
}
}
?>
The function for a redirect in wordpress is wp_redirect, e.g.
if( $mail_sent ) {
wp_redirect( '/my-target' );
exit();
} else {
//output your warning
}

Incorrect encoding with Cyrillic in PHP contact form

I'm new to using PHP and forms so if someone is willing to help, I'll be extremely grateful.
I have a contact form, but it doesn't send any Cyrillic characters correctly. I know that I have to put Content-type: text/plain; charset=UTF-8 somewhere in the code but I have no idea where to put it exactly. The form element is set to post in UTF-8, but it doesn't seem to work correctly with the PHP file.
error_reporting(E_ALL ^ E_NOTICE);
$my_email = "myemailaddress#mail.com";
$from_email = "";
$continue = "index.php";
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if (count($_COOKIE)) {
foreach(array_keys($_COOKIE) as $value) {
unset($_REQUEST[$value]);
}
}
// Validate email field.
if (isset($_REQUEST['email']) && !empty($_REQUEST['email']) && !empty($_REQUEST['family']) && !empty($_REQUEST['about'])) {
$_REQUEST['email'] = trim($_REQUEST['email']);
if (substr_count($_REQUEST['email'], "#") != 1 || stristr($_REQUEST['email'], " ")) {
$errors[] = "Email address is invalid";
} else {
$exploded_email = explode("#", $_REQUEST['email']);
if (empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])) {
$errors[] = "Email address is invalid";
} else {
if (substr_count($exploded_email[1], ".") == 0) {
$errors[] = "Email address is invalid";
} else {
$exploded_domain = explode(".", $exploded_email[1]);
if (in_array("", $exploded_domain)) {
$errors[] = "Email address is invalid";
} else {
foreach($exploded_domain as $value) {
if (strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i', $value)) {
$errors[] = "Email address is invalid";
break;
}
}
}
}
}
}
}
// Check referrer is from same site.
if (!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']))) {
$errors[] = "You must enable referrer logging to use the form";
}
// Check for a blank form.
function recursive_array_check_blank($element_value) {
global $set;
if (!is_array($element_value)) {
if (!empty($element_value)) {
$set = 1;
}
} else {
foreach($element_value as $value) {
if ($set) {
break;
}
recursive_array_check_blank($value);
}
}
}
recursive_array_check_blank($_REQUEST);
if (!$set) {
$errors[] = "You cannot send a blank form";
}
unset($set);
// Display any errors and exit if errors exist.
if (count($errors)) {
foreach($errors as $value) {
print "$value<br>";
}
exit;
}
if (!defined("PHP_EOL")) {
define("PHP_EOL", strtoupper(substr(PHP_OS, 0, 3) == "WIN") ? "\r\n" : "\n");
}
// Build message.
function build_message($request_input) {
if (!isset($message_output)) {
$message_output = "";
}
if (!is_array($request_input)) {
$message_output = $request_input;
} else {
foreach($request_input as $key = > $value) {
if (!empty($value)) {
if (!is_numeric($key)) {
$message_output. = str_replace("_", " ", ucfirst($key)).
": ".build_message($value).PHP_EOL.PHP_EOL;
} else {
$message_output. = build_message($value).
", ";
}
}
}
}
return rtrim($message_output, ", ");
}
$message = build_message($_REQUEST);
$message = $message.PHP_EOL.PHP_EOL.
"-- ".PHP_EOL.
"Thank you for using the contact form.";
$message = stripslashes($message);
$subject = $_REQUEST['about'];
$subject = stripslashes($subject);
if ($from_email) {
$headers = "From: ".$from_email;
$headers. = PHP_EOL;
$headers. = "Reply-To: ".$_REQUEST['email'];
} else {
$from_name = "";
if (isset($_REQUEST['name']) && !empty($_REQUEST['name'])) {
$from_name = stripslashes($_REQUEST['name']);
}
$headers = "From: {$from_name} <{$_REQUEST['email']}>";
}
mail($my_email, $subject, $message, $headers); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Your mail has been sent!</title>
<meta http-equiv="Content-Type" content="text/html; charset = utf - 8 ">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div>
<center>
<b>Thank you <?php if(isset($_REQUEST['name'])){print stripslashes($_REQUEST['name']);} ?></b>
<br>Your mail has been sent!
<p>Click here to continue</p>
</center>
</div>
</body>
</html>
Добави това:
$headers = "From: " . $from_email;
$headers .= PHP_EOL;
$headers .= "Reply-To: " . $_REQUEST['email'];
//новия код (new code)
$headers .= "MIME-Version: 1.0"."\r\n" ."Content-type: text/plain; charset='utf-8'". "\r\n";
Няма да е лошо да сложиш и някаква форма на верификация (картинка с код примерно, който трябва да се въведе, т.нар. CAPTCHA code) преди пращане от юзера, иначе всеки спам бот ще ти ползва формата за пращане на мейли, порови тук има доста начини за справяне с проблема.
Translated: (It is not bad idea to put some sort of verification code, an image with code inside of it, a so called CAPTCHA before sending the email, because otherwise every spam bot from Internet will use your form for mailing, check here for more ways to deal with the problem.)

Categories