I have a webhooks that i use in someone shop's for Shopify, but only this use the information to upload to my server.
When the owner of the shop is click on fullfil item the order going to my site, but in some cases the order appear two times only with one click, i am using php and curl.
this is my php file
<?php
//start a session
session_start();
//Webhook enviado por shopify
$webhookContent= "";
$webhook= fopen('php://input' , 'rb');
while (!feof($webhook)) {
$webhookContent .= fread($webhook, 4096);
}
fclose($webhook);
$data= json_decode($webhookContent,true);
//guardar datos ordenes
$file = 'shipping_innata.txt';
$print = print_r($webhookContent, true);
file_put_contents($file, $print, FILE_APPEND | LOCK_EX);
//obtener desde headers el dominio de shopify
$domain_header= $_SERVER['HTTP_X_SHOPIFY_SHOP_DOMAIN'];
//consulta en base 99min
$db = mysqli_connect("localhost", "root", "plas711", "minut_api");
//comprobar carrier
$shipping= $data ['shipping_lines']['0']['code'];
$express= '99minutos.com en menos de 99 minutos (L-V de 9 a 16 hrs) SOLO DF';
$program= '99minutos.com Programado mismo día (L-V de 9 a 16 hrs) SOLO DF';
//variables obtenidas desde json
$first_name= $data['shipping_address']['first_name'];
$last_name= $data['shipping_address']['last_name'];
$email= $data['email'];
$phone= $data['shipping_address']['phone'];
$address1= $data['shipping_address']['address1'];
$address2= $data['shipping_address']['address2'];
$province= $data['shipping_address']['province'];
$zip= $data['shipping_address']['zip'];
$city= $data['shipping_address']['city'];
$latitude= $data['shipping_address']['latitude'];
$longitude= $data['shipping_address']['longitude'];
$note= $data['note'];
$name= 'Orden: '.$data['name'];
$pago= $data['gateway'];
if($pago =="Pago contra entrega (SOLO DF Y AREA METROPOLITANA)"){
$total_price= $data['total_price'];
}
else{
$total_price=0;
}
//busqueda del correo del propietario de la tienda en base de datos
$mail_db= "SELECT * FROM tbl_usersettings WHERE store_name = '$domain_header'";
$mail_result= mysqli_query($db, $mail_db);
$mail_q= mysqli_fetch_array($mail_result, MYSQLI_ASSOC);
$mail_str= $mail_q['email'];
////////////////////////////////////////////////////
//url encode para producto en bodegas
function request()
{
global $total_price,$pago,$latitude, $longitude, $address1, $address2, $city, $province, $zip, $email, $phone, $first_name, $last_name, $productos, $name, $db, $shipping, $express, $program;
// variables
$api_key= '23894thfpoiq10fapo93fmapo';
$user_id= '4290583552';
if ($shipping == $express){
$delivery_type = '99minutos';
}
else if($shipping == $program){
$delivery_type = 'Programado';
}
$latlng= '19.346857%2C-99.2985648';
$destination_route= urlencode(implode(' ', array($address1,$address2)));
$destination_locality= urlencode($city);
$destination_administrative_area_level= urlencode($province);
$destination_postal_code= urlencode($zip);
$d_latlng= urlencode(implode(',', array($latitude,$longitude)));
$customer_phone= urlencode($phone);
$nombre = 'Cliente: '.implode(' ',array($first_name,$last_name));
//Variable que pasa al sistema de 99minutos los datos en la seccion de notas
//$notes=urlencode(implode(', ', array($name,$nombre)));
//url que sirve para hacer la peticion de envion al sistema de 99minutos
$request = "https://das-dot-line-76299minutos.appspot.com/2/delivery/request?";
$request.= "api_key=".$api_key."&";
$request.= "user_id=".$user_id."&";
$request.= "delivery_type=".$delivery_type."&";
$request.= "route=ARTEAGA+Y+SALAZAR&";
$request.= "street_number=108&";
$request.= "neighborhood=Contadero&";
$request.= "locality=Mexico&";
$request.= "administrative_area_level_1=Distrito+Federal&";
$request.= "postal_code=05500&";
$request.= "country=Mexico&latlng=".$latlng."&";
$request.= "destination-route=".$destination_route."&";
$request.= "destination-street_number=&";
$request.= "destination-neighborhood=&";
$request.= "destination-locality=".$destination_locality."&";
$request.= "destination-administrative_area_level=".$destination_administrative_area_level."&";
$request.= "destination-postal_code=".$destination_postal_code."&";
$request.= "destination-country=Mexico&";
$request.= "destination-latlng=".$d_latlng."&";
$request.= "customer_email=".$email."&";
$request.= "customer_phone=".$customer_phone."&";
$request.= "notification_email=&";
if($pago =="Pago contra entrega (SOLO DF Y AREA METROPOLITANA)"){
$monto = "Cobro:".$total_price;
$notes = urlencode((implode(',', array($name,$nombre,$monto))));
$request.= "notes=".$notes."&";
$request.= "receivable_order=true&";
$request.= "amount=".$total_price."&";
}
else
{
$notes = urlencode((implode(',', array($name,$nombre))));
$request.= "notes=".$notes."&";
}
$request.= "dispatch=true";
//funcion curl para enviar la peticion de envio al sistema de 99minutos
$archivo = 'respaldo_innata.txt';
$texto = print_r($request, true);
file_put_contents($archivo, $texto, FILE_APPEND | LOCK_EX);
error_log("Request");
error_log(print_r($request, true));
$ch_request=curl_init();
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request);
curl_setopt($curl, CURLOPT_SSLVERSION, 3);
//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($curl);
curl_close ($curl);
error_log("Response");
error_log(print_r($response, TRUE));
die();
}
///////////////////////////////////////////////////
function mailprogramado()
{
global $domain_header, $name, $first_name, $last_name, $email, $phone, $address1, $address2, $province, $zip, $latitude, $longitude, $productos, $pago;
$to = "ens#99minutos.com";
$subject = "Envio Tienda Malabares";
$mail_body = '<html>';
$mail_body .='<body topmargin="25">';
$mail_body .='<h2> Dirección de Envio</h2>';
$mail_body .='<table width="500" border="1" cellspacing="10" cellpadding="10">';
$mail_body .='<tr> <td width="100" align="center"> Tienda: </td> <td align="left"> '. $domain_header .' </td> </tr>';
$mail_body .='<tr> <td width="100" align="center"> Orden: </td> <td align="left"> '. $name .' </td> </tr>';
$mail_body .='<tr> <td width="100" align="center"> Nombre: </td> <td align="left"> '. $first_name .' </td> </tr>';
$mail_body .='<tr> <td width="100" align="center"> Apellidos: </td> <td align="left"> '. $last_name .' </td> </tr>';
$mail_body .='<tr> <td width="100" align="center"> Correo: </td> <td align="left"> '. $email .' </td> </tr>';
$mail_body .='<tr> <td width="100" align="center"> Teléfono: </td> <td align="left"> '. $phone .' </td> </tr>';
$mail_body .='<tr> <td width="100" align="center"> Dirección: </td> <td align="left"> '. $address1 .' </td> </tr>';
$mail_body .='<tr> <td width="100" align="center"> Dirección: </td> <td align="left"> '. $address2 .' </td> </tr>';
$mail_body .='<tr> <td width="100" align="center"> Estado: </td> <td align="left"> '. $province .' </td> </tr>';
$mail_body .='<tr> <td width="100" align="center"> Codigo Postal: </td> <td align="left"> '. $zip .' </td> </tr>';
$mail_body .='<tr> <td width="100" align="center"> Latitud: </td> <td align="left"> '. $latitude .' </td> </tr>';
$mail_body .='<tr> <td width="100" align="center"> Longitud: </td> <td align="left"> '. $longitude .' </td> </tr>';
$mail_body .='<tr> <td width="100" align="center"> Metodo de pago: </td> <td align="left"> '. $pago .' </td> </tr>';
$mail_body .='</table>';
$mail_body .='</body>';
$mail_body .='</html>';
$headers = "From:ens#99minutos.com\r\n";
$headers .= "Content-type: text/html\r\n";
mail($to, $subject, $mail_body, $headers);
}
// error_log(print_r($data, true));
if($shipping == $express){
//Notificacion envio depar
mailprogramado();
//realizar pedido de envio
request();
//destruir sesion
session_destroy();
exit();
}
else if($shipping == $program){
//Notificacion envio depar
mailprogramado();
//realizar pedido de envio
request();
//destruir sesion
session_destroy();
exit();
}
?>
If I understand you correctly, you're wondering why do you get several requests from Shopify instead of just one.
I've faced the same problem recently, and I think it's a feature of Webhooks mechanism you have to deal with.
Consider this post: https://ecommerce.shopify.com/c/shopify-apis-and-technology/t/webhook-url-is-called-between-2-4-times-220007
Bottomline. You should expect Shopify will hit your endpoint more than once and you have to manage this by yourself to avoid duplicating entities and stuff.
Related
I beg your pardon if some part of the code is written in italian, but I'm trying to make a script for my work, and I want to split two scripts, where in the main script there is a call to another script with the require function.
The main script is the following:
\<?php
require('c:/include_connessione/ldbproxy.inc.php');
//define('DB2SERVER' , 'udbsrv0e:50004');
define('DB2SERVER' , '192.168.8.128:50004');
define('DB' , 'WAREHSOA');
define('DBUSR' , 'db2itsoa');
define('DBPWD' , 'db2itsoa');
$styleSpieg="style='font-family:arial;font-size: 10pt;text-align: left;'";
function TRACE($str)
{
$fp=fopen('c:/Manutenzione/confronti_itcam/confronti_itcam.log', 'a');
if($fp)
{
fprintf($fp, date('Y-m-d H:i:s') . ' ' . $str . "\n");
fclose($fp);
}
}
TRACE("START");
$conn = new ldbproxy();
if(! $conn->connect_db2(DB2SERVER, DB, DBUSR, DBPWD))
{
TRACE('cannot connect to ' . DB2SERVER . ': ' . $conn->errorMsg);
die();
}
$confronti_DataPower=require("confronti_itcam_DataPower.php");
$conn->close();
$subject = "Confronto eventi SOA del ".date('d-m-Y',strtotime("-1 days"));
$spiegazione = "<td $styleSpieg align=left >
<b>I dati che seguono hanno lo scopo di confrontare gli eventi dell'applicativo ITCAmfSOA che vengono scritti dall'agent di monitoraggio sulle tabelle del DB2 WAREHSOA, in particolare:<br>
- confronto tra eventi di request sulla tabella Services_Inventory_610 (di seguito SI) e la tabella Services_Inventory_ReqID_610 (di seguito SI_ReqID)<br>
- confronto tra eventi di fault sulla tabella Services_Inventory_610 (SI) e la tabella Fault_Log_Table_610 (di seguito FLT) </b>
</td>";
$header = 'From:tivoli#inps.it' . "\r\n";
$header .= "X-Mailer: \n";
$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
$header .= "Content-Transfer-Encoding: 7bit\n\n";
$out = "<html>
<body>
<table>
<tr>
$spiegazione
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
<td>
$confronti_DataPower
</td>
</tr>
<tr>
</tr>
</table>
</body>
</html>";
$header="";
$header = "From: Tivoli <tivoli#inps.it>\n";
$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
$header .= "Content-Transfer-Encoding: 7bit\n\n";
$to= 'f.gatta#man-con.com';
$res=mail($to,$subject,$out,$header);
($res)?TRACE("Mail inviata con successo"):TRACE("Errore invio mail");
TRACE("END");
?\>
The called script (titled "confronti_itcam_DataPower.php") in the require function has the following code:
\<?php
$data=array();
$temp=array("Request_SI"=>0,"Request_ReqID"=>0,"Fault_SI"=>0,"Fault_FLT"=>0,);
function Executequery($q,$type)
{
global $data;
global $conn;
global $temp;
$resultset=$conn->query($q);
if(!$resultset)
{
TRACE("Errore esecuzione query $type :" . $conn->errorMsg);
die();
}
while($row_object=$conn->fetch($resultset))
{
(!isset($data[$row_object['Server']]))?$data[$row_object['Server']]=$temp:'';
$data[$row_object['Server']][$type]=(($row_object['value']!="")?$row_object['value']:'');
}
}
//COSTRUZIONE TABELLA PER AMBIENTE DATAPOWER
function create_table()
{
global $data;
$keys=array_keys($data);
$styleTB="style='font-family:arial;background-color:#1a0da8;margin:3px 0pt 15px;font-size: 9pt;width: 100%;text-align: center;'";
$styleTHfirst="style='color:#f7fafa;background-color:#1a0da8;border:1px solid #FFF;padding:4px;font-size:18px;font-weight:bold;'";
$styleTHsecond="style='background-color:#d5eded;border:1px solid #FFF;padding:4px;font-size:15px;font-weight:bold;font-style:italic;'";
$styleTD="style='color:#3D3D3D;padding:4px;background-color:#FFF;vertical-align:top;'";
$rowTable="";
foreach($keys as $key)
{
$_Request_SI=$data[$key]['Request_SI'];
$_Request_ReqID=$data[$key]['Request_ReqID'];
$scostRequest=$_Request_SI-$_Request_ReqID;
//$scostRequestPerc=(($_Request_SI==0 && $_Request_ReqID==0)?"Nessuno":(($_Request_SI==0)?"100 %":number_format((($scostRequest/$_Request_SI)*100),2)." %"));
$_Fault_SI=$data[$key]['Fault_SI'];
$_Fault_FLT=$data[$key]['Fault_FLT'];
$scostFault=$_Fault_SI-$_Fault_FLT;
//$scostFaultPerc=(($_Fault_FLT==0 && $_Fault_SI==0)?"Nessuno":(($_Fault_SI==0)?"100 %":number_format((($scostFault/$_Fault_SI)*100),2)." %"));
$rowTable.="<tr>
<td $styleTD align=center >
<b>$key</b>
</td>
<td $styleTD align=center >
$_Request_SI
</td>
<td $styleTD align=center >
$_Request_ReqID
</td>
<td $styleTD align=center>
$scostRequest
</td>
<td $styleTD align=center >
$_Fault_SI
</td>
<td $styleTD align=center >
$_Fault_FLT
</td>
<td $styleTD align=center >
$scostFault
</td>
</tr>";
}
$table_confronti="<table $styleTB id='table_confronti' style='width:100%'>
<thead>
<th $styleTHfirst colspan=7 align=center >
Ambiente DataPower
</th>
</thead>
<tbody>
<tr>
<td $styleTHsecond align=center>
Server
</td>
<td $styleTHsecond align=center >
Request su SI
</td>
<td $styleTHsecond align=center >
Request su SI_ReqID
</td>
<td $styleTHsecond align=center >
Δ request
<td $styleTHsecond align=center>
Fault su SI
</td>
<td $styleTHsecond align=center >
Fault su FLT
</td>
<td $styleTHsecond align=center >
Δ fault
</td>
</tr>
$rowTable
</tbody>
</table>";
$tb=" <center>
<table style='width:100%'>
<tr>
<td>
<div >".$table_confronti."</div>
</td>
</tr>
</table>
</center>";
return $tb;
}
$yesterday_inf_sol= "1".substr(date('Ymd',strtotime("-2 days")),2)."230000000";
$yesterday_sup_sol= "1".substr(date('Ymd',strtotime("-1 days")),2)."230000000";
$yesterday_inf_leg= "1".substr(date('Ymd',strtotime("-2 days")),2)."220000000";
$yesterday_sup_leg= "1".substr(date('Ymd',strtotime("-1 days")),2)."220000000";
$query_SI_request='select
upper(substr("Origin_Node",13,17)) as "Server",
sum("Request_Count") as "value"
from
"Services_Inventory_610"
where
upper(substr("Local_Hostname_U",1,9))=\'CUSTMON03\' and "Service_Type"=1 and
CASE
WHEN "TMZDIFF"=\'-3600\' THEN ("Interval_Begin_Time">=\''.$yesterday_inf_sol.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_sol.'\')
WHEN "TMZDIFF"=\'-7200\' THEN ("Interval_Begin_Time">=\''.$yesterday_inf_leg.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_leg.'\')
END
group by upper(substr("Origin_Node",13,17))';
$query_ReqID='select
upper(substr("Origin_Node",13,17)) as "Server",
sum("Request_Count") as "value"
from
"Services_Inventory_ReqID_610"
where
upper(substr("Local_Hostname_U",1,9))=\'CUSTMON03\' and
CASE
WHEN "TMZDIFF"=\'-3600\' THEN ("Interval_Begin_Time">=\''.$yesterday_inf_sol.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_sol.'\')
WHEN "TMZDIFF"=\'-7200\' THEN ("Interval_Begin_Time">=\''.$yesterday_inf_leg.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_leg.'\')
END
group by upper(substr("Origin_Node",13,17))';
$query_SI_fault='select
sum("Fault_Count") as "value",
upper(substr("Origin_Node",13,17)) as "Server"
from
"Services_Inventory_610"
where upper(substr("Local_Hostname_U",1,9))=\'CUSTMON03\' and
CASE
WHEN "TMZDIFF"=\'-3600\' THEN ("Interval_Begin_Time">=\''.$yesterday_inf_sol.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_sol.'\')
WHEN "TMZDIFF"=\'-7200\' THEN ("Interval_Begin_Time">=\''.$yesterday_inf_leg.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_leg.'\')
END
group by upper(substr("Origin_Node",13,17)) ';
$query_FLT='select
count(*) as "value",
upper(substr("Origin_Node",13,17)) as "Server"
from
"Fault_Log_Table_610"
where upper(substr("Hostname_U",1,9))=\'CUSTMON03\' and
CASE
WHEN "TMZDIFF"=\'-3600\' THEN ("Message_Time">=\''.$yesterday_inf_sol.'\' and "Message_Time"<\''.$yesterday_sup_sol.'\')
WHEN "TMZDIFF"=\'-7200\' THEN ("Message_Time">=\''.$yesterday_inf_leg.'\' and "Message_Time"<\''.$yesterday_sup_leg.'\')
END
group by upper(substr("Origin_Node",13,17)) ';
Executequery($query_SI_request,'Request_SI');
Executequery($query_ReqID,'Request_ReqID');
Executequery($query_SI_fault,'Fault_SI');
Executequery($query_FLT,'Fault_FLT');
$result=create_table();
?\>
What I got when all the code was in one script is a table with data after the variable $spiegazione, now after the splitting I get "1" in place of the table after $spiegazione.
Where am I wrong?
I want to send the data from the order to the email + contact form send.
I do not know how to send cart data to an email with a contact form
function load_cart_data()
{
$.ajax({
url:"fetch_cart.php",
method:"POST",
dataType:"json",
success:function(data)
{
$('#cart_details').html(data.cart_details);
$('.total_price').text(data.total_price);
$('.badge').text(data.total_item);
}
});
}
Cart ....
<?php
//fetch_cart.php
session_start();
$total_price = 0;
$total_item = 0;
$output = '
<div class="table-responsive" id="order_table">
<table class="table table-bordered table-striped">
<tr>
<th width="40%">Product Name</th>
<th width="10%">Quantity</th>
<th width="20%">Price</th>
<th width="15%">Total</th>
<th width="5%">Action</th>
</tr>
';
if(!empty($_SESSION["shopping_cart"]))
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
$output .= '
<tr>
<td>'.$values["product_name"].'</td>
<td>'.$values["product_quantity"].'</td>
<td align="right">$ '.$values["product_price"].'</td>
<td align="right">$ '.number_format($values["product_quantity"] * $values["product_price"], 2).'</td>
<td><button name="delete" class="btn btn-danger btn-xs delete" id="'. $values["product_id"].'">Remove</button></td>
</tr>
';
$total_price = $total_price + ($values["product_quantity"] * $values["product_price"]);
$total_item = $total_item + 1;
}
$output .= '
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ '.number_format($total_price, 2).'</td>
<td></td>
</tr>
';
}
else
{
$output .= '
<tr>
<td colspan="5" align="center">
Your Cart is Empty!
</td>
</tr>
';
}
$output .= '</table></div>';
$data = array(
'cart_details' => $output,
'total_price' => '$' . number_format($total_price, 2),
'total_item' => $total_item
);
echo json_encode($data);
?>
email send
<?php
$namebusiness = $_POST['namebusiness'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$adress = $_POST['adress'];
$city = $_POST['city'];
$psc = $_POST['psc'];
$state = $_POST['state'];
$phone = $_POST['phone'];
$visitor_email = $_POST['email'];
$data = $_POST['data'];
$message = $_POST['cart_details'];
$email_subject = "Order";
$email_body = "Name Of Business: $namebusiness.\n "."First name: $firstname.\n "."Last name: $lastname.\n"."E-mail: $visitor_email.\n"."Adress: $adress.\n "."City: $city.\n "."Post Code / ZIP: $psc.\n "."State: $state.\n "."Phone number: $phone.\n";
$to = "patrikl123#seznam.cz";
$to = $_POST['email'];
$headers = 'From: domaci#potrebyhanka.cz' . "\r\n" .
'Reply-To: domaci#potrebyhanka.cz' . "\r\n" .
'Content-type: text/html; charset=UTF-8' . "\r\n".
'X-Mailer: PHP/' . phpversion();
mail($to, $email_subject,$message,$email_body,$headers);
header("Content-type: text/html; charset=UTF-8");
header("Location: index.php");
//https://stackoverflow.com/questions/30802674/retrieve-data-from-cart-and-send-using-mail
?>
The contact form at the bottom of this page http://nmfnebbs.preview.infomaniak.website/
is not working, when I fill all the fields and I click on the button to send, the error message is displayed and nothing is sent to my Email.
Here is the script for the contact form:
var submitContact = $('#submit_contact'),
message = $('#msg');
submitContact.on('click', function(e){
e.preventDefault();
var $this = $(this);
$.ajax({
type: "POST",
url: 'contact.php',
dataType: 'json',
cache: false,
data: $('#contact-form').serialize(),
success: function(data) {
if(data.info !== 'error'){
$this.parents('form').find('input[type=text],textarea,select').filter(':visible').val('');
message.hide().removeClass('success').removeClass('error').addClass('success').html(data.msg).fadeIn('slow').delay(5000).fadeOut('slow');
} else {
message.hide().removeClass('success').removeClass('error').addClass('error').html(data.msg).fadeIn('slow').delay(5000).fadeOut('slow');
}
}
});
});
and here is the content of contact.php (except my email address)
/* ========================== Define variables ========================== */
#Your e-mail address
define("__TO__", "my email address");
#Message subject
define("__SUBJECT__", "IT-vip.com.tn");
#Success message
define('__SUCCESS_MESSAGE__', "Votre message a bien été envoyé");
#Error message
define('__ERROR_MESSAGE__', "Erreur, Votre message n'a pas été envoyé");
#Messege when one or more fields are empty
define('__MESSAGE_EMPTY_FILDS__', "Veuillez remplir tous les champs");
/* ======================== End Define variables ======================== */
//Send mail function
function send_mail($to,$subject,$message,$headers){
if(#mail($to,$subject,$message,$headers)){
echo json_encode(array('info' => 'success', 'msg' => __SUCCESS_MESSAGE__));
} else {
echo json_encode(array('info' => 'error', 'msg' => __ERROR_MESSAGE__));
}
}
//Check e-mail validation
function check_email($email){
if(!#eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
return false;
} else {
return true;
}
}
//Get post data
if(isset($_POST['name']) and isset($_POST['mail']) and isset($_POST['comment'])){
$name = $_POST['name'];
$mail = $_POST['mail'];
$website = $_POST['website'];
$comment = $_POST['comment'];
if($name == '') {
echo json_encode(array('info' => 'error', 'msg' => "Veuillez saisir votre nom"));
exit();
} else if($mail == '' or check_email($mail) == false){
echo json_encode(array('info' => 'error', 'msg' => "Veuillez saisir votre e-mail valide"));
exit();
} else if($comment == ''){
echo json_encode(array('info' => 'error', 'msg' => "Veuillez saisir votre message."));
exit();
} else {
//Send Mail
$to = __TO__;
$subject = __SUBJECT__ . ' ' . $name;
$message = '
<html>
<head>
<title>Mail from '. $name .'</title>
</head>
<body>
<table style="width: 500px; font-family: arial; font-size: 14px;" border="1">
<tr style="height: 32px;">
<th align="right" style="width:150px; padding-right:5px;">Name:</th>
<td align="left" style="padding-left:5px; line-height: 20px;">'. $name .'</td>
</tr>
<tr style="height: 32px;">
<th align="right" style="width:150px; padding-right:5px;">E-mail:</th>
<td align="left" style="padding-left:5px; line-height: 20px;">'. $mail .'</td>
</tr>
<tr style="height: 32px;">
<th align="right" style="width:150px; padding-right:5px;">Website:</th>
<td align="left" style="padding-left:5px; line-height: 20px;">'. $website .'</td>
</tr>
<tr style="height: 32px;">
<th align="right" style="width:150px; padding-right:5px;">Comment:</th>
<td align="left" style="padding-left:5px; line-height: 20px;">'. $comment .'</td>
</tr>
</table>
</body>
</html>
';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: ' . $mail . "\r\n";
send_mail($to,$subject,$message,$headers);
}
} else {
echo json_encode(array('info' => 'error', 'msg' => __MESSAGE_EMPTY_FILDS__));
}
?>
I'm trying to make a conditional statement to stop an email alert when the fail.php is called. Right now I'm getting an email alert for both good and fail results.
I do not want to receive an email if the the result failed. Should I make two scripts or is there a way t make this work together?
Thanks
Here is the section I'm referring to along with the whole script.
if (mysql_affected_rows($result) > 0) {
mail($to, $subject, $msg, $headers);
$reg = $_REQUEST['reg'] ;
$first_name = $_REQUEST['first_name'];
header("location: reg_add_success.php?reg=" . urlencode($reg) . "&first_name=" . urlencode($first_name));
}
else {
header("location: reg_add_fail.php");
exit(); // as sugested by John Conde
}
<?
$to = 'newreg#41q.org';
$subject = 'New Homeless Connection';
$msg = "<html>
<head>
<title>New Homeless Connection</title>
</head>
<body>
<table cellspacing=\"0\" cellpadding=\"10\" border=\"1\" align=\"left\">
<tr>
<td align=\"left\" width=\"150px\">Registery No.:</td>
<td align=\"left\"> $reg</td>
</tr>
<tr>
<td align=\"left\">First Name:</td>
<td align=\"left\">$first_name </td>
</tr>
<tr>
<td align=\"left\">Connection Date:</td>
<td align=\"left\"$>$connect_date</td>
</tr>
<tr>
<td align=\"left\" colspan=\"2\">http://www.41q.org/admin/</td>
</tr>
</table>
<br>
<br>
</body>
</html>
";
// Make sure to escape quotes
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: Homeless' . "\r\n";
mail($to, $subject, $msg, $headers);
date_default_timezone_set('America/Los_Angeles');
$submit_date = date("m/d/y g:i A") ;
$order = "INSERT INTO reg_add (submit_date,
connect_date,
reg,
first_name,
)
VALUES
('$submit_date',
'$_POST[connect_date]',
'{$_POST[reg]}nv',
'$_POST[first_name]')";
$result = mysql_query($order);
if (mysql_affected_rows($result) > 0) {
mail($to, $subject, $msg, $headers);
$reg = $_REQUEST['reg'] ;
$first_name = $_REQUEST['first_name'];
header("location: reg_add_success.php?reg=" . urlencode($reg) . "&first_name=" . urlencode($first_name));
}
else {
header("location: reg_add_fail.php");
exit(); // as sugested by John Conde
}
?>
Remove the first instance of mail($to, $subject, $msg, $headers);.
Then, for good measure, check the number of rows affected, rather than true/false (although both should work).
if (mysql_affected_rows($result) > 0) {
}
If you check your code
// Make sure to escape quotes
$headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: Homeless' . "\r\n";
mail($to, $subject, $msg, $headers);
date_default_timezone_set('America/Los_Angeles');
This code is already sending the mail regard less of the result.
You just need to remove this line from top code
mail($to, $subject, $msg, $headers);
and your code will work fine.
Final code, kindly test ite
<?
$to = 'newreg#41q.org';
$subject = 'New Homeless Connection';
$msg = "<html>
<head>
<title>New Homeless Connection</title>
</head>
<body>
<table cellspacing=\"0\" cellpadding=\"10\" border=\"1\" align=\"left\">
<tr>
<td align=\"left\" width=\"150px\">Registery No.:</td>
<td align=\"left\"> $reg</td>
</tr>
<tr>
<td align=\"left\">First Name:</td>
<td align=\"left\">$first_name </td>
</tr>
<tr>
<td align=\"left\">Connection Date:</td>
<td align=\"left\"$>$connect_date</td>
</tr>
<tr>
<td align=\"left\" colspan=\"2\">http://www.41q.org/admin/</td>
</tr>
</table>
<br>
<br>
</body>
</html>
";
// Make sure to escape quotes
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: Homeless' . "\r\n";
date_default_timezone_set('America/Los_Angeles');
$submit_date = date("m/d/y g:i A") ;
$order = "INSERT INTO reg_add (submit_date,
connect_date,
reg,
first_name,
)
VALUES
('$submit_date',
'$_POST[connect_date]',
'{$_POST[reg]}nv',
'$_POST[first_name]')";
$result = mysql_query($order);
if (mysql_affected_rows($result) > 0) {
mail($to, $subject, $msg, $headers);
$reg = $_REQUEST['reg'] ;
$first_name = $_REQUEST['first_name'];
header("location: reg_add_success.php?reg=" . urlencode($reg) . "&first_name=" . urlencode($first_name));
}
else {
header("location: reg_add_fail.php");
exit(); // as sugested by John Conde
}
?>
I currently see some sql injections plus invalid query first_name, extra , at the end, constants used in posts array keys, a mix of request and post, large html block of code and no checks on validity of the values passed.
If you check for valid values then you can determine if the script should continue to the mail and update the database parts:
Heres a clean up of your code hope it helps:
<?php
$to = 'newreg#41q.org';
$subject = 'New Homeless Connection';
if($_SERVER['REQUEST_METHOD']=='POST'){
if(isset($_POST['first_name']) && strlen($_POST['first_name'])>1){
$first_name=$_POST['first_name'];
}
if(isset($_POST['reg']) && strlen($_POST['reg'])>1){
$reg=$_POST['reg'];
}
if(isset($_POST['connect_date']) && strlen($_POST['connect_date'])>1){
$connect_date=$_POST['connect_date'];
}
if(!isset($first_name) || !isset($reg) || !isset($connect_date)){
header("location: reg_add_fail.php");
exit();
}
}else{
//the page the post from
header("location: reg_form.php");
exit();
}
$msg=<<<EMAIL
<html>
<head>
<title>New Homeless Connection</title>
</head>
<body>
<table cellspacing="0" cellpadding="10" border="1" align="left">
<tr>
<td align="left" width="150px">Registery No.:</td>
<td align="left">$reg</td>
</tr>
<tr>
<td align="left">First Name:</td>
<td align="left">$first_name </td>
</tr>
<tr>
<td align="left">Connection Date:</td>
<td align="left">$connect_date</td>
</tr>
<tr>
<td align="left" colspan="2">http://www.41q.org/admin/</td>
</tr>
</table>
<br>
<br>
</body>
</html>
EMAIL;
// Make sure to escape quotes
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: Homeless' . "\r\n";
mail($to, $subject, $msg, $headers);
date_default_timezone_set('America/Los_Angeles');
$submit_date = date("m/d/y g:i A") ;
$order = "INSERT INTO reg_add (submit_date,connect_date, reg, first_name)
VALUES ('{$submit_date}',".mysql_real_escape_string($connect_date)."','".mysql_real_escape_string($reg)."nv','".mysql_real_escape_string($first_name)."')";
$result = mysql_query($order);
header("Location: ./reg_add_success.php?reg=".urlencode($reg)."&first_name=".urlencode($first_name));
die;
?>
I just discovered that I'm still receiving an email EVEN when there is an error (reg_add_fail.php). Is it possible to stop the script from emailing me IF the client is directed to reg_add_fail.php? Confused...
I simplified the script to condense.
Many thanks.
Erik
<?
$to = 'newreg#41q.org';
$subject = 'New Homeless Connection';
$msg = "<html>
<head>
<title>New Homeless Connection</title>
</head>
<body>
<table cellspacing=\"0\" cellpadding=\"10\" border=\"1\" align=\"left\">
<tr>
<td align=\"left\" width=\"150px\">Registery No.:</td>
<td align=\"left\"> $reg</td>
</tr>
<tr>
<td align=\"left\">First Name:</td>
<td align=\"left\">$first_name </td>
</tr>
<tr>
<td align=\"left\">Connection Date:</td>
<td align=\"left\"$>$connect_date</td>
</tr>
<tr>
<td align=\"left\" colspan=\"2\">http://www.41q.org/admin/</td>
</tr>
</table>
<br>
<br>
</body>
</html>
";
// Make sure to escape quotes
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: Homeless' . "\r\n";
mail($to, $subject, $msg, $headers);
date_default_timezone_set('America/Los_Angeles');
$submit_date = date("m/d/y g:i A") ;
$order = "INSERT INTO reg_add (submit_date,
connect_date,
reg,
first_name,
)
VALUES
('$submit_date',
'$_POST[connect_date]',
'{$_POST[reg]}nv',
'$_POST[first_name]')";
$result = mysql_query($order);
if ($result) {
mail($to, $subject, $msg, $headers);
$reg = $_REQUEST['reg'] ;
$first_name = $_REQUEST['first_name'];
header("location: reg_add_success.php?reg=" . urlencode($reg) . "&first_name=" . urlencode($first_name));
}
else {
header("location: reg_add_fail.php");
exit(); // as sugested by John Conde
}
?>
Put exit() after the redirect
header("location: reg_add_fail.php");
exit();
Just because you call header() doesn't mean the script stops executing immediately. Calling exit() will.
In your code, the PHP mail() function is being called outside the IF statement, so, you always get the email.
To send the email only when the query runs without errors, place the mail() inside the if statement!
PHP
if ($result) {
mail($to, $subject, $msg, $headers);
$reg = $_REQUEST['reg'] ;
$first_name = $_REQUEST['first_name'];
header("location: reg_add_success.php?reg=" . urlencode($reg) . "&first_name=" . urlencode($first_name));
}
else {
header("location: reg_add_fail.php");
exit(); // as sugested by John Conde
}
EDITED TO SHOW THE ENTIRE CODE:
<?php
// Email Recipient
$to = 'newreg#41q.org';
// Email Subject
$subject = 'New Homeless Connection';
// Email Message
$msg = '
<html>
<head>
<title>New Homeless Connection</title>
</head>
<body>
<table cellspacing="0" cellpadding="10" border="1" align="left">
<tr>
<td align="left" width="150px">Registery No.:</td>
<td align="left">'.$reg.'</td>
</tr>
<tr>
<td align="left">First Name:</td>
<td align="left">'.$first_name.'</td>
</tr>
<tr>
<td align="left">Connection Date:</td>
<td align="left">'.$connect_date.'</td>
</tr>
<tr>
<td align="left" colspan="2">http://www.41q.org/admin/</td>
</tr>
</table>
<br>
<br>
</body>
</html>';
// Email Headers
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: Homeless' . "\r\n";
date_default_timezone_set('America/Los_Angeles');
$submit_date = date("m/d/y g:i A") ;
// Prepare Database Query
$order = "
INSERT INTO reg_add (
submit_date,
connect_date,
reg,
first_name
)
VALUES (
'".$submit_date."',
'".$_POST['connect_date']."',
'".$_POST['reg']."nv',
'".$_POST['first_name']."'
)";
// Query Database
$result = mysql_query($order);
// Check If the result is valid
if ($result) {
// send email
mail($to, $subject, $msg, $headers);
// prepare and direct the user to the reg_add_success Page
$reg = $_REQUEST['reg'] ;
$first_name = $_REQUEST['first_name'];
header("location: reg_add_success.php?reg=" . urlencode($reg) . "&first_name=" . urlencode($first_name));
}
else {
// send the user to the reg_add_fail Page
header("location: reg_add_fail.php");
// exit from the script
exit();
}
?>