Jump to content

PHP mail sending 4 emails.


dardime

Recommended Posts

Hi 

I just need help on why my php mail function sends out 4 emails. Two emails each will be sent on 131 and 139. Im configuring a payment merchant. Thank you

<?php 
#Inlcude PxPay objects
include "PxPay_Curl.inc.php";

  $PxPay_Url    = "";
  //$PxPay_Url    = "";
  $PxPay_Userid = ""; #Important! Update with your UserId
  $PxPay_Key    =  ""; #Important! Update with your Key
  
  #
  # MAIN
  #

  $pxpay = new PxPay_Curl( $PxPay_Url, $PxPay_Userid, $PxPay_Key );

  if (isset($_REQUEST["result"]))
  {
    # this is a redirection from the payments page.
    print_result();
  }
  elseif (isset($_REQUEST["Submit"]))
  {
    # this is a post back -- redirect to payments page.
	
	//START OF ADDITION BY JOHNREY
		
		include_once('includes/config.php');	
		include_once('includes/payment.php'); 
		include_once('includes/generic.php');
		$payment = new payment();
		$generic = new generic();	
		
		if(!empty($_POST)){
		$arr = array(
			"name" => $_POST["name"],
			"address" => $_POST["Address1"],
			"email" => $_POST["Address3"],
			"contact" => $_POST["contact"],
			"job" => $_POST["job"],
			"amount" => $_POST["Quantity"],
		);
		
		$validate = $generic->validate($arr);
		
		if(!$validate["error"]){
			$arr = array(
				"reference_no" => stripslashes($_POST["Reference"]),
				"name" => stripslashes($_POST["name"]),
				"address" => stripslashes($_POST["Address1"]),
				"email" => stripslashes($_POST["Address3"]),	
				"contact" => stripslashes($_POST["contact"]),
				"job" => stripslashes($_POST["job"]),
				"description" => stripslashes($_POST["description"]),
				"amount" => stripslashes($_POST["Quantity"]),
				"date" => date('Y-m-d H:i:s')
			);
					
		$payments = $payment->addPayment($arr);
		}
	 } 
	//END OF ADDITION BY JOHNREY
	
    redirect_form();
  }
  else
  {
    # this is a fresh request -- display the purchase form.
    //print_form();
  }


#******************************************************************************
# This function receives information back from the payments page,
# and displays it to the user.
#******************************************************************************
function print_result()
{
  global $pxpay;

  $enc_hex = $_REQUEST["result"];
  #getResponse method in PxPay object returns PxPayResponse object
  #which encapsulates all the response data
  $rsp = $pxpay->getResponse($enc_hex);


  # the following are the fields available in the PxPayResponse object
  $Success           = $rsp->getSuccess();   # =1 when request succeeds
  $AmountSettlement  = $rsp->getAmountSettlement();
  $AuthCode          = $rsp->getAuthCode();  # from bank
  $CardName          = $rsp->getCardName();  # e.g. "Visa"
  $CardNumber        = $rsp->getCardNumber(); # Truncated card number
  $DateExpiry        = $rsp->getDateExpiry(); # in mmyy format
  $DpsBillingId      = $rsp->getDpsBillingId();
  $BillingId    	 = $rsp->getBillingId();
  $CardHolderName    = $rsp->getCardHolderName();
  $DpsTxnRef	     = $rsp->getDpsTxnRef();
  $TxnType           = $rsp->getTxnType();
  $TxnData1          = $rsp->getTxnData1();
  $TxnData2          = $rsp->getTxnData2();
  $TxnData3          = $rsp->getTxnData3();
  $CurrencySettlement= $rsp->getCurrencySettlement();
  $ClientInfo        = $rsp->getClientInfo(); # The IP address of the user who submitted the transaction
  $TxnId             = $rsp->getTxnId();
  $CurrencyInput     = $rsp->getCurrencyInput();
  $EmailAddress      = $rsp->getEmailAddress();
  $MerchantReference = $rsp->getMerchantReference();
  $ResponseText		 = $rsp->getResponseText();
  $TxnMac            = $rsp->getTxnMac(); # An indication as to the uniqueness of a card used in relation to others
 
			
  if ($rsp->getSuccess() == "1")
  {  
	  
    $result = '<div class="alert-success">The transaction was approved.</div>';
	
		# Sending invoices/updating order status within database etc.
		
					
	if (!isProcessed($TxnId))
	{
		# Send emails, generate invoices, update order status etc.
		
			//MAILTO
					
			$emailto      = $TxnData3;
			$subjectto = "Online Payment";
			$messageto = "Payment Details: \r\n\n Reference No: OT" . $MerchantReference . "\r\n\n Name: " . $CardHolderName . "\r\n\n Address: " . $TxnData1 . "\r\n\n Email: " . $TxnData3 . "\r\n\n Amount Paid: NZD " . $AmountSettlement . "\r\n\n Payment Status: " . $ResponseText."\r\n\n If you have any urgent queries, please call our Help Desk.\r\n\n Best Regards,\n ";
			$headersto = 'From: email@email.co.nz' . "\r\n" .
			'Reply-To: email@email.co.nz' . "\r\n" .
			'X-Mailer: PHP/' . phpversion();
			mail($emailto, $subjectto, $messageto, $headersto);
			
			$to      = "email@email.co.nz";
			$subject = "Online Payment - Reference No: OT" . $MerchantReference ."";
			$msg = "Payment Details: \r\n\n Reference No: OT" . $MerchantReference . "\r\n\n Name: " . $CardHolderName . "\r\n\n Address: " . $TxnData1 . "\r\n\n Email: " . $TxnData3 . "\r\n\n Amount Paid: NZD " . $AmountSettlement . "\r\n\n Payment Status: " . $ResponseText;
			$headers = 'From: '. $TxnData3 . "\r\n" .
			'Reply-To: email@email.co.nz' . "\r\n" .
			'X-Mailer: PHP/' . phpversion();
			mail($to, $subject, $msg, $headers);
			
			//END OF //MAILTO	
	}
	
  }
  else
  {
    $result = '<div class="alert-danger">The transaction was declined.</div>';
  }

  print <<<HTMLEOF
<html>
<head>
<title>Direct Payment Solutions PxPay transaction result</title>
</head>
<body>
<p>$result</p>
</body>
</html>
HTMLEOF;
}

#******************************************************************************
# Database lookup to check the status of the order or shopping cart
#******************************************************************************

function isProcessed($TxnId)
{
	# Check database if order relating to TxnId has alread been processed
	return false;
}

#******************************************************************************
# This function prints a blank purchase form.
#******************************************************************************
function print_form()
{
  print <<<HTMLEOF
<html>
<head>
<title>Direct Payment Solutions PxPay transaction sample</title>
</head>
<body>
<h1>Direct Payment Solutions PxPay transaction result</h1>
<p>
You have indicated you would like to buy some widgets.
</p>
<p>
Please enter the number of widgets below, and enter your
shipping details.
</p>
<form method="post">
<table>
  <tr>
    <td>Quantity:</td>
    <td><input name="Quantity" type="text"/></td>
  </tr>
  <tr>
    <td>Reference:</td>
    <td><input name="Reference" type="text"/></td>
  </tr>  
  <tr>
    <td>Ship to</td>
    <td></td>
  </tr>
  <tr>
    <td>Address line 1:</td>
    <td><input name="Address1" type="text"/></td>
  </tr>
  <tr>
    <td>Address line 2</td>
    <td><input name="Address2" type="text"/></td>
  </tr>
    <tr>
    <td>Address line 3</td>
    <td><input name="Address3" type="text"/></td>
  </tr>
</table>
<input name="Submit" type="submit" value="Submit"/>
Click submit to go to the secure payment page.
</form>
</body>
</html>
HTMLEOF;
}

#******************************************************************************
# This function formats data into a request and redirects to the
# Payments Page.
#******************************************************************************
function redirect_form()
{
  global $pxpay;

  $request = new PxPayRequest();

  $http_host   = getenv("HTTP_HOST");
  $request_uri = getenv("SCRIPT_NAME");
  $server_url  = "http://$http_host";
  #$script_url  = "$server_url/$request_uri"; //using this code before PHP version 4.3.4
  #$script_url  = "$server_url$request_uri"; //Using this code after PHP version 4.3.4
  $script_url = (version_compare(PHP_VERSION, "4.3.4", ">=")) ?"$server_url$request_uri" : "$server_url/$request_uri";


  # the following variables are read from the form
  $Quantity = $_REQUEST["Quantity"];
  $MerchantReference = $_REQUEST["Reference"];  
  $Address1 = $_REQUEST["Address1"];
  $Address2 = $_REQUEST["Address2"];
  $Address3 = $_REQUEST["Address3"];
  
  #Calculate AmountInput
  $AmountInput = $Quantity;
  
  #Generate a unique identifier for the transaction
  $TxnId = uniqid("ID");
  
  #Set PxPay properties
  $request->setMerchantReference($MerchantReference);
  $request->setAmountInput($AmountInput);
  $request->setTxnData1($Address1);
  $request->setTxnData2($Address2);
  $request->setTxnData3($Address3);
  $request->setTxnType("Purchase");
  $request->setCurrencyInput("NZD");
  $request->setEmailAddress($EmailAddress);
  $request->setUrlFail($script_url);			# can be a dedicated failure page
  $request->setUrlSuccess($script_url);			# can be a dedicated success page
  $request->setTxnId($TxnId);  
  
  #The following properties are not used in this case
  # $request->setEnableAddBillCard($EnableAddBillCard);    
  # $request->setBillingId($BillingId);
  # $request->setOpt($Opt);
  

  
  #Call makeRequest function to obtain input XML
  $request_string = $pxpay->makeRequest($request);
   
  #Obtain output XML
  $response = new MifMessage($request_string);
  
  #Parse output XML
  $url = $response->get_element_text("URI");
  $valid = $response->get_attribute("valid");
   
   #Redirect to payment page
   header("Location: ".$url);
}
?>

<!DOCTYPE html>
<html lang="en">

    <head>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Online Payment</title>
        <!-- CSS -->
        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,100,300,500">
        <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
        <link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">
	<link rel="stylesheet" href="dist/css/form-elements.css">
        <link rel="stylesheet" href="dist/css/style.css">
        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
        <!-- Favicon and touch icons -->
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
        <script>
		function validateForm() {
			var a = document.forms["myform"]["name"].value;
			var x = document.forms["myform"]["Address1"].value;
			var c = document.forms["myform"]["Address3"].value;
					var atpos = c.indexOf("@");
					var dotpos = c.lastIndexOf(".");
					if (atpos<1 || dotpos<atpos+2 || dotpos+2>=c.length) {
						alert("Invalid e-mail address");
						return false;
					}
			var d = document.forms["myform"]["contact"].value;
			var e = document.forms["myform"]["job"].value;
			//var f = document.forms["myform"]["description"].value;
			var g = document.forms["myform"]["Quantity"].value;

			if (a == null || a == "") {
				alert("Name must be filled out");
				return false;
			}
			if (x == null || x == "") {
				alert("Address must be filled out");
				return false;
			}
			if (d == null || d == "") {
				alert("Contact No. must be filled out");
				return false;
			}
			if (e == null || e == "") {
				alert("Job No. must be filled out");
				return false;
			}
			//if (f == null || f == "") {
				//alert("Post Code must be filled out");
				//return false;
			//}
			if (g == null || g == "") {
				alert("Amount must be filled out");
				return false;
			}		
		}
		</script>
    </head>
    
    <body>

		<!-- Top menu -->
        <!-- Top content -->
        <div class="top-content">
        	
            <div class="inner-bg">
                <div class="container">
                    
                    <div class="row">
                        <div class="col-sm-6 col-sm-offset-3 form-box">
                        	<div class="form-top">
                        		<div align="center"; style="padding-top:10px">
                   			    	<img src="includes/logo.png"> 
                                </div>
                                  <div align="center">
                        			<h3>Online Payment</h3>
                        		</div>                       		
                            </div>
                            <div class="form-bottom contact-form">                         	
                             <?php
							 	//START OF ADDITION BY JOHNREY
		
								include_once('includes/config.php');	
								include_once('includes/payment.php'); 
								include_once('includes/generic.php');
								$payment = new payment();
								$generic = new generic();
								
								if(!empty($_POST)){
								$arr = array(
									"name" => $_POST["name"],
									"address" => $_POST["Address1"],
									"email" => $_POST["Address3"],
									"contact" => $_POST["contact"],
									"job" => $_POST["job"],
									"amount" => $_POST["Quantity"],
								);
								
								$validate = $generic->validate($arr);							
								
							 } 
							//END OF ADDITION BY JOHNREY
							?>                         
          <div class="alert-danger" style="margin-bottom:20px;"><?php if(empty($error)){ echo ''; }else{ echo '<div class="msg" style="text-align:left;">'.$error.'</div>'; } ?></div>
	<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" onsubmit="return validateForm()" name="myform" id="myform">
                                		<?php
											  $refquery = mysql_query("SELECT * FROM `tbpayment` ORDER BY payment_id DESC");
											  if($refquery) {
												$ref = mysql_fetch_assoc($refquery);
												$ref_no = intval($ref["reference_no"]) + 1;
											  }
											  else
												$ref_no = 100000;
												
											  $str = strval($ref_no);
											  $limit = 11-strlen($str);
											  $reference = "";
											  for($i=0; $i<$limit; $i++) {
												$reference .= "0";
											  }
											  $reference = $ref_no;
									    ?>
                                   <div class="form-group">
			                        	Reference No: OT<?php echo $reference; ?>
			                        </div>         
                              <input class="form-control" type="hidden" name="Reference" id="Reference" value="<?php echo $reference; ?>">
                                      
                                	 <div class="form-group">
                            </div>
                             		Customer Details
                                    <div class="form-group">
			                    		<label class="sr-only" for="contact-name">Name</label>
			                        	<input type="text" name="name" placeholder="Name" class="contact-name form-control" id="name" value="<?php if(!empty($_POST["name"]) && !empty($error)) { echo $_POST["name"]; } ?>" required>
			                        </div>
                                    <div class="form-group">			                        	
			                        	<textarea name="Address1" placeholder="Address" class="contact-message form-control" id="Address1"><?php if(!empty($_POST["Address1"]) && !empty($error)) { echo $_POST["Address1"]; } ?></textarea>
			                        </div>
			                    	<div class="form-group">
			                    		<label class="sr-only" for="contact-email">Email</label>
			                        	<input type="text" name="Address3" placeholder="Email" class="contact-email form-control" id="Address3" value="<?php if(!empty($_POST["Address3"]) && !empty($error)) { echo $_POST["Address3"]; } ?>" required>
			                        </div>
			                        <div class="form-group">
			                        	<label class="sr-only" for="contact-number">Contact Number</label>
			                        	<input type="text" name="contact" placeholder="Contact Number" class="contact-number form-control" id="contact" value="<?php if(!empty($_POST["contact"]) && !empty($error)) { echo $_POST["contact"]; } ?>" required>
			                        </div>
                                    Payment Details
                                    <div class="form-group">
			                        	<label class="sr-only" for="contact-job">Job Number</label>
			                        	<input type="text" name="job" placeholder="Job Number" class="contact-job form-control" id="job" value="<?php if(!empty($_POST["job"]) && !empty($error)) { echo $_POST["job"]; } ?>" required>
			                        </div>
                                    <div class="form-group">
			                        	<label class="sr-only" for="contact-job">Invoice Description</label>
			                        	<input readonly type="text" name="description" placeholder="Invoice Description" class="contact-job form-control" id="description" value="Mobile Phone Repair" required>
			                        </div>
                                     <div class="form-group">
			                        	<label class="sr-only" for="contact-job">Amount</label>
			                        	<input type="text" name="Quantity" placeholder="Amount" class="contact-job form-control" id="Quantity" value="<?php if(!empty($_POST["Quantity"]) && !empty($error)) { echo $_POST["Quantity"]; } ?>" required>
                                                                        			                        
                                    <div align="center" style="padding-top:20px"><input name="Submit" type="submit" class="btn btn-primary" value="Pay Now"></div>
			                    </form>
		                    </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Javascript -->
        <script src="bower_components/jquery/dist/jquery.min.js"></script>
        <script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
        <script src="dist/js/jquery.backstretch.min.js"></script>
        <script src="dist/js/scripts.js"></script>
        <!--[if lt IE 10]>
            <script src="assets/js/placeholder.js"></script>
        <![endif]-->

    </body>

</html>

Link to comment
Share on other sites

The mailing happens in print_result, which happens if $_REQUEST["result"] is set. It won't trigger on the same request with the one that does the redirect (which, by the way, should have an exit; after the header() so that your script stops doing any more processing).

 

Take a look at your web server's access logs to see if that page is being loaded more than howevermany times it should be - which sounds like two.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.