Cannot get mail() to work correctly

Sorry for the hatchet job of this code. It is a conversion from some I have had for quite some time.

I had the code working until my Linux server died and discovered I did not have a backup of the working files. I am close to full recovery but am having issues with a call to the Postfix mail() function in one of my older files. It worked before and similar mail code is working with another file. I am stumped!

The data posting and call and insert to the tables works fine but the sending of the two emails in the code shows no result. Any help would be appreciated. I have spent many hours trying to figure it out.

As a side note: This code is not used on a public website.

The db.php stores many of the program variables.


//pay-working-3-8-try.php

<?php
session_start();

include("db.php");

global $dbServer, $dbUser, $dbPass, $dbName;
global $zones, $rates, $totwt, $totwtchg;
global $carttable, $itemtable;
$cxn = @mysqli_connect($dbServer, $dbUser, $dbPass, $dbName);


if (empty($_POST['sel_record'])){
	echo "<h2>STOP!!!!</h2><h3>Sorry, a zip code was not chosen. Please use the Back button<br>and choose one from the list to continue payment operation.</h3>";
	echo "<a href='javascript:history.go(-1);'>Back</a>";
}
else{
ShowCart();	
}
?>
<?php
function ShowCart()
{
// Gets each item from the cart table and display them in
// a tabulated format, as well as a final for the cart
global $dbServer, $dbUser, $dbPass, $dbName;
global $zones, $rates, $totwt, $totwtchg, $ft;
global $carttable, $itemtable, $paytitle, $payheader, $headercolor;
global $returncart, $subtext, $shiptext, $fttext, $totaltext, $paytxt;
global $carttottext, $ft;
// Get a connection to the database
$cxn = @mysqli_connect($dbServer, $dbUser, $dbPass, $dbName);
$totalCost = 0;
$result = mysqli_query($cxn, "select * from $carttable inner join $itemtable on $carttable.itemId = $itemtable.itemId where $carttable.cookieId = '" . GetCartId() . "' order by $itemtable.itemName asc");

//Reading zip code post and determining shipping zone
$sql_3 = mysqli_query($cxn, "SELECT * FROM $zones WHERE ZIP = '$_POST[sel_record]'");
//$sql_result = mysqli_query($sql_3) or die (mysqli_error());
                if (!$sql_3) {
                        echo "Something has gone wrong!";
                } else {
                        //loop through record and get values
                        while ($record = mysqli_fetch_array($sql_3)) {
				$zip = stripslashes($record['zip']);
				$zone = stripslashes($record['zone']);
        }
		}
//Figuring total weight
$totalWt = 0;
$result_4 = mysqli_query($cxn, "select * from $carttable inner join $itemtable on $carttable.itemId = $itemtable.itemId where $carttable.cookieId = '" . GetCartId() . "' order by $itemtable.itemName asc");
while($row = mysqli_fetch_array($result_4))
{
// Increment through and determine total weight
$totalWt += ($row["qty"] * $row["ship_weight"]);
}

//FIX THIS FOR MAX WEIGHT!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/*if ($totalWt > $totwt){
	$totalWt = $totwtchg;
}
*/

$wtCharge = ceil($totalWt);

$fwtCharge = $wtCharge + 1;

//Figure shipping charges
$result_6 = mysqli_query($cxn, "select * from $rates where $rates.zone = '$zone' and $rates.weight = '$fwtCharge'");
while($row = mysqli_fetch_array($result_6))
{
				$zone_1 = ($row['zone']);
				$wt = stripslashes($row['weight']);
				$ft .= stripslashes($row['fcharge']);
}	


?>
		
<head>


<script language="JavaScript">
		
</script>

</head>
<body bgcolor="#ffffff">
<form name="frmCart" method="get">
<table width="100%" cellspacing="0" cellpadding="0" border="0">


<?php
while($row = mysqli_fetch_array($result))
{
// Increment the total cost of all items
$totalCost += ($row["qty"] * $row["itemPrice"]);

$cookie = GetCartId();

?>


				
<?php
}
?>
					
<td width="30%" colspan="2">
<font face="verdana" size="2" color="red">
<b> <?php echo $subtext ; ?>  $<?php echo number_format($totalCost, 2, ".", ","); ?></b>
</font>
</td>
</tr>

<td width="30%" colspan="2">
<font face="verdana" size="2" color="red">
<b> <?php echo $fttext ; ?> $<?php echo $ft ?> - Shipping Wt: (<?php echo $fwtCharge?> lbs.) <<< LOOK AT FREIGHT COSTS!! WILL LOWER QTY WORK?</b>
</font>
</td>
</tr>

<?php

$totalOrder = 0;
$totalOrder = $totalCost + $ft;

?>

<td width="30%" colspan="2">
<font face="verdana" size="2" color="red">
<b> <?php echo $totaltext ; ?> $<?php echo number_format($totalOrder, 2, ".", ","); ?> <<< TOTAL ORDER COST!! LOWER QTY TO SAVE $$?<br></b>
</font>
</td>
</tr>

<tr>
<td width="70%" colspan="2">
<font face="verdana" size="2" color="black">
<a href="cart.php">&lt;&lt; <?php echo $returncart ; ?></a>
</font>
</td>

</tr>

</table>
</form>

<?php
}
?>

<?php
//set the random id length 
$random_id_length = 3; 

//generate a random id encrypt it and store it in $rnd_id 
$rnd_id = uniqid(rand(),1); 

//to remove any slashes that might have come 
$rnd_id = strip_tags(stripslashes($rnd_id)); 

//Removing any . or / and reversing the string 
$rnd_id = str_replace(".","",$rnd_id); 
$rnd_id = strrev(str_replace("/","",$rnd_id)); 

//finally I take the first 3 characters from the $rnd_id 
$rnd_id = substr($rnd_id,0,$random_id_length); 

date_default_timezone_set('America/Los_Angeles');
$info = getdate();
$date = $info['mday'];
$month = $info['mon'];
$year = $info['year'];
$hour = $info['hours'];
$min = $info['minutes'];

$date_id = date('ymd');

$current_date = "$month/$date/$year - $hour:$min";

$order_oid = "$date_id-$rnd_id";


			$etotalCost = 0;
			
			$etcresult = mysqli_query($cxn, "select * from $carttable inner join $itemtable on $carttable.itemId = $itemtable.itemId where $carttable.cookieId = '" . GetCartId() . "' order by $itemtable.itemName asc");
			
			while($tcrow = mysqli_fetch_array($etcresult))
			{
			// Increment the total cost of all items
			$etotalCost += ($tcrow["qty"] * $tcrow["itemPrice"]);
	  	}
	  	
			$distotal = money_format("%10.2n",$etotalCost);


	if($_POST['formSubmit'] == "Submit") 
    {
		$errorMessage = "";
		
		if(empty($_POST['formSales'])) 
        {
			$errorMessage .= "<li>You forgot to enter a saleperson!</li>";
		}
				if(empty($_POST['formFname'])) 
        {
			$errorMessage .= "<li>You forgot to enter a first name!</li>";
		}
						if(empty($_POST['formLname'])) 
        {
			$errorMessage .= "<li>You forgot to enter a last name!</li>";
		}
						if(empty($_POST['formAdd1'])) 
        {
			$errorMessage .= "<li>You forgot to enter an address!</li>";
		}
						if(empty($_POST['formCity'])) 
        {
			$errorMessage .= "<li>You forgot to enter a city!</li>";
		}
						if(empty($_POST['formState'])) 
        {
			$errorMessage .= "<li>You forgot to enter a state!</li>";
		}
						if(empty($_POST['formZip'])) 
        {
			$errorMessage .= "<li>You forgot to enter a zip code!</li>";
		}
		$varOID  = $_POST['formOID'];
		$varRND  = $_POST['formRND'];
		$varORD  = $_POST['formORD'];
		$varSales  = $_POST['formSales'];
		$varEmail = $_POST['formEmail']; 
	  $varCompany = $_POST['formCompany'];
		$varFname = $_POST['formFname'];
    $varLname = $_POST['formLname'];
    $varAdd1 = $_POST['formAdd1'];
    $varAdd2 = $_POST['formAdd2'];
    $varCity = $_POST['formCity'];
    $varState = $_POST['formState'];
    $varZip = $_POST['formZip'];
    $varPhone = $_POST['formPhone'];

		if(empty($errorMessage)) 
        {
			$conn = new mysqli($dbServer, $dbUser, $dbPass, $dbName);
		
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO orderinfo (oid, date, ordtotal, sales, company, fname, lname, add1, add2, city, state, zip, phone, freight, cookie)
VALUES ('".$_POST["formOID"]."','".$_POST["formRND"]."','".$_POST["formORD"]."','".$_POST["formSales"]."','".$_POST["formCompany"]."','".$_POST["formFname"]."','".$_POST["formLname"]."','".$_POST["formAdd1"]."','".$_POST["formAdd2"]."','".$_POST["formCity"]."','".$_POST["formState"]."','".$_POST["formZip"]."','".$_POST["formPhone"]."','".$_POST["formFreight"]."','".GetCartId()."')";

if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New record created successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}

			$result_m = mysqli_query($cxn, "select * from $carttable inner join $itemtable on $carttable.itemId = $itemtable.itemId where $carttable.cookieId = '" . GetCartId() . "' order by $itemtable.itemName asc");
			$i=1;
			while($row = mysqli_fetch_array($result_m))
			{
			$orddetail .= PHP_EOL . ' ' . $row['qty'] . ' - ' . $row['itemName'] . ', ' . $row['itemPrice'] . ' each' . PHP_EOL; 

			$i++;
			}

//$conn->close();		
		
header("Location: thankyou.html");				
			
			
			$to = "[email protected]";
			$subject = "Sample Order Request (Order ID - $varOID)";
			$message = "A Murphy order has been requested:\n
			Order ID: $varOID
			Salesman: $varSales\n
			Order Detail: 
			$orddetail
			Order Value Total: $distotal\n 
			Order Ship To: 
			$varCompany
			$varFname $varLname
			$varAdd1
			$varAdd2
			$varCity, $varState $varZip\n
			Phone: $varPhone\n";

			$from = $varSales;
			$headers = $varSemail;
		
					
			mail($to,$subject,$message,$headers);

			$to2 = $varEmail;
			$subject2 = "Sample Order Request - For $varSales (Order ID - $varOID)";
			$message2 = "A sample order has been requested:\n
			Order ID: $varOID
			Salesman: $varSales\n
			Order Detail: 
			$orddetail
			Order Value Total: $distotal\n 
			Order Ship To: 
			$varCompany
			$varFname $varLname
			$varAdd1
			$varAdd2
			$varCity, $varState $varZip\n
			Phone: $varPhone\n";

			$from = $varSales;
			$headers = $varSemail;
					
			mail($to2,$subject2,$message2,$headers);
			
			exit();
		}
	}
?>

<html>
<head>
	<title>PHP Form processing example</title>
<style>
label,a 
{
	font-family : Arial, Helvetica, sans-serif;
	font-size : 12px; 
}

</style>	
</head>

<body>

       <?php
		    if(!empty($errorMessage)) 
		    {
			    echo("<p>There was an error with your form:</p>\n");
			    echo("<ul>" . $errorMessage . "</ul>\n");
            }
        ?>

		    <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
				<input type='hidden' name='formOID' value="<?=$order_oid;?>" />
				<input type='hidden' name='formRND' value="<?=$current_date;?>" />
				<input type='hidden' name='formORD' value="<?=$distotal;?>" />
				<label for='formSales'>Salesperson:</label><br/>
				<select name="formSales">
					<?php
					// Get a connection to the database
					$cxn6 = @mysqli_connect($dbServer, $dbUser, $dbPass, $dbName);
					$sql6 = mysqli_query($cxn6, "SELECT * FROM salespersons ORDER BY name");
					while ($row = mysqli_fetch_array($sql6)) {
					$code = $row["name"];
					$semail = $row["email"];
					echo "<option value=\"$code\">$code </option>";
					}
					?>
				</select>
						<br/>
				<input type='hidden' name='formEmail' value="<?=$semail;?>" />		
				<label for='formCompany'>Ship To - Company:</label><br/>
				<input type="text" name="formCompany" maxlength="50" value="<?=$varCompany;?>" /><br/>
				
				<label for='formFname'>First Name</label><br/>
				<input type="text" name="formFname" maxlength="50" value="<?=$varFname;?>" /><br/>
			
				<label for='formLname'>Last Name</label><br/>
				<input type="text" name="formLname" maxlength="50" value="<?=$varLname;?>" /><br/>

				<label for='formAdd1'>Address 1</label><br/>
				<input type="text" name="formAdd1" maxlength="50" value="<?=$varAdd1;?>" /><br/>
		
				<label for='formAdd2'>Address 2 (if necessary)</label><br/>
				<input type="text" name="formAdd2" maxlength="50" value="<?=$varAdd2;?>" /><br/>

				<label for='formCity'>City</label><br/>
				<input type="text" name="formCity" maxlength="50" value="<?=$varCity;?>" /><br/>

				<label for='formState'>State</label><br/>
				<input type="text" name="formState" maxlength="50" value="<?=$varState;?>" /><br/>

				<label for='formZip'>Zip</label><br/>
				<input type="text" name="formZip" maxlength="50" value="<?=$varZip;?>" /><br/>

				<label for='formPone'>Phone no:</label><br/>
				<input type="text" name="formPhone" maxlength="50" value="<?=$varPhone;?>" /><br/>
				<input type='hidden' name='formFreight' value="<?=$ft;?>" />
			Press the Submit button only once to submit the order.<br>
			Wait for the confirmation page before closing.<br>
			<input type="submit" name="formSubmit" value="Submit" />
		</form>	
</body>
</html>

What debugging steps have you taken?

  1. Is the code where the mail() calls at being executed?
  2. Do the variables being used in the mail() calls contain what you expect?
  3. Do you have php’s error related settings setup so that all php detected errors will be displayed or logged?
  4. Why don’t you have error handling logic for the mail() calls?

I would just like to add that you are using way too many global variables. Either use functions or connect them via the include or require statement from a different php page. And STOP SUPPRESSING ERRORS with @ in front mysqli calls!

2 Likes

Separate your logical php code and your view.

Remember that the mail function is just a gate to the mailserver. if php isn’t properly configured or the mail functionality is simply disabled it will not send any mail at all. To test that you could send a very simple email to yourself:

mail('[email protected]', 'Mail test', 'This mail has been sent to see if the php mail function works properly.');

Alternatively you could use PHPMailer to send your emails through a SMTP server of your choice. (the one you may use from your ISP)

Thanks for all the suggestions. I found the issue with your help!!

Sponsor our Newsletter | Privacy Policy | Terms of Service