Creating Logs from PHP mail function.

Discussion in 'PHP' started by Kyrus, Oct 31, 2008.

  1. #1
    Hello guys!

    Firstly, I just joined your community because I noticed how helpful you guys can be with one another.

    So with that said, let's get to business and what brings me here. We have an e-commerce system in our website, which is programmed to send an e-mail to us when the user clicks "Purchase" with the products purchased so we can proceed to send the package via mail. The user gets a confirmation page saying that all the data has been sent (or not, depending if he filled the required fields or not).

    To put it simple: cart.php -> purchase.php (which has the form to be filled) -> confirm.php (which displays the data sent and sends an e-mail to us or displays error)

    So far so good. We've implented this a while ago and we had no problems so far. The problem is, our webserver may be "slacking" when it comes to send those "Purchase" e-mails to us. We're not absolutely sure though and this brings us to my question:

    Is there anyway to control which users (IP Adresses, Time and Date + all the presumably data sent to us via e-mail) click "Purchase"?

    I'm thinking of a .txt file that the server could create in a secure fashion with all this data in a folder we could specify. That would be the best solution for us.

    But if you think of any other solution that may be viable don't hesitate, tell me! :)

    Here's out code:

    <?php require_once('Connections/X.php'); ?>
    <?php session_start(); ?>
    <html>
    <head>
    <title>Formulário</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <script language="Javascript1.2">
    <!--
    var message = "imprimir esta página";
    
    function printpage() {
    window.print();  
    }
    
    //document.write("<form><input type=button "
    //+"value=\""+message+"\" onClick=\"printpage()\"></form>");
    
    //-->
    
    function MM_callJS(jsStr) { //v2.0
      return eval(jsStr)
    }
    //-->
    </script>
    <link href="images/rawr.css" rel="stylesheet" type="text/css">
    <style type="text/css">
    <!--
    .style1 {
    	font-size: 10px;
    	font-family: Verdana, Arial, Helvetica, sans-serif;
    }
    -->
    </style></head>
    
    <body>
    <table width="500" border="0" cellspacing="8" cellpadding="0">
      <tr>
        <td colspan="2"><img src="images/bannerFundorawrEnvio.gif" width="500" height="90"></td>
      </tr>
      <tr>
        <td><a href="#" class="linkc style1" onClick="MM_callJS('printpage()')">Imprimir</a></td>
        <td valign="bottom" class="texto"><div align="right"><a href="index.php" class="linkc">&lt;&lt;Home</a></div></td>
      </tr>
      <tr>
        <td height="2" colspan="2" valign="bottom"></td>
      </tr>
      <tr>
        <td colspan="2">&nbsp;</td>
      </tr>
      <tr>
        <td colspan="2"><?php 
     include("db.php");
     include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
    
    $securimage = new Securimage();
    $error = false;
    
    $data = date("d-m-Y,G:i");
    $to = "mail@rawr.com"; //
    $nr = $_POST['nr']; 
    $name = $_POST['nome']; 
    $endereco = $_POST['end']; 
    $localidade = $_POST['loc']; 
    $cod_postal = $_POST['cod'];
    $pais = $_POST['pais'];
    $telefone = $_POST['tel']; 
    $fax = $_POST['fax'];
    $profissao = $_POST['prof'];
    $actividade = $_POST['act'];
    $email = $_POST['mail'];
    $nrcont = $_POST['nrcont'];
    $sub = "Encomenda";
    $msg = $_POST['msg'];
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
    $headers .= "Dados do Cliente referente a rawr online";
    if ($securimage->check($_POST['captcha_code']) == false) {
      die('Código de segurança incorrecto, por favor tente outra vez.');
    }
    
    
    //$EmailBody = "Nome: $name\nO Email: $email\nTelefone: $telefone\nEmpresa: $empresa\nMenssagem: $msg\n"; 
    /*
    //verifica se o utilizador inseriu um email e se este está num formato errado
    if(!empty($email) and !ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z­]{2,3})$", 
    $email)) { 
          echo "<div align='center'><font color='#006633' size=9 face='Verdana, Arial, Helvetica, sans-serif'><h5>O Email que foi inserido n&atilde;o tem um formato valido, por favor insira um email valido</h5></font></div>";
    	   echo "<div align='center'><font color='#FF0000' size=9 face='Verdana, Arial, Helvetica, sans-serif'><h5><a href='encomendar.php'>Clique aqui para corrigir</a></h5></font></div>";
    	//echo " <meta http-equiv=\"refresh\" content=\"5;URL=encomendar.php\"> ";
    	  //exit;
    } 
    //
    
    */
    //verifica se o utilizador colocou um código de cliente e se está errado imprime uma mensagem de erro
    if(!empty($nr)){
    
    $_SESSION['nr'] = htmlentities( $_POST['nr'] );
    $_SESSION['nome'] = htmlentities( $_POST['nome'] );
    $_SESSION['end'] = htmlentities( $_POST['end'] );
    
    $_SESSION['loc'] = htmlentities( $_POST['loc'] );
    $_SESSION['cod'] = htmlentities( $_POST['cod'] );
    $_SESSION['pais'] = htmlentities( $_POST['pais'] );
    
    $_SESSION['tel'] = htmlentities( $_POST['tel'] );
    $_SESSION['fax'] = htmlentities( $_POST['fax'] );
    $_SESSION['prof'] = htmlentities( $_POST['prof'] );
    
    $_SESSION['act'] = htmlentities( $_POST['act'] );
    $_SESSION['mail'] = htmlentities( $_POST['mail'] );
    $_SESSION['nrcont'] = htmlentities( $_POST['nrcont'] );
    $_SESSION['msg'] = htmlentities( $_POST['msg'] );
    
    $valid_cod = ereg("([a-zA-Z0-9]{8})",$nr);
    
    if(empty($name) || empty($telefone)){
    echo "<div align='center'><font color='#006633' size=9 face='Verdana, Arial, Helvetica, sans-serif'><h5>Não preencheu os respectivos campos obrigatórios de um cliente (nome e telefone).</h5></font></div>";
    echo "<div align='center'><font color='#FF0000' size=9 face='Verdana, Arial, Helvetica, sans-serif'><h5><a href='encomendar.php'>Clique aqui para corrigir</a></h5></font></div>";
    	//echo " <meta http-equiv=\"refresh\" content=\"5;URL=encomendar.php\"> ";
    	//  exit;
    }
    
    else if (!$valid_cod){
    echo "<div align='center'><font color='#006633' size=9 face='Verdana, Arial, Helvetica, sans-serif'><h5> O código de cliente não tem um formato valido.<br> Por favor insira-o correctamente!</h5></font></div>";
    echo "<div align='center'><font color='#FF0000' size=9 face='Verdana, Arial, Helvetica, sans-serif'><h5><a href='encomendar.php'>Clique aqui para corrigir</a></h5></font></div>";
    	//echo " <meta http-equiv=\"refresh\" content=\"5;URL=encomendar.php\"> ";
    	//  exit;
    }
    
    else { 
          
          echo "<div align='center'><font color='#006633' size=9 face='Verdana, Arial, Helvetica, sans-serif'><h5><strong><i>Obrigado ".$name." os seus dados foram enviados com sucesso</i></strong></h5></font></div>";
    
    	 // print"<input alt=imprimir align='right' border=0 name=submit src='images/print.jpg' type=image onClick='printpage()'><br>";
    	  
    $mesage=msn($nr,$name,$endereco,$localidade,$cod_postal,$pais,$telefone,$fax,$profissao,$actividade,$email,$nrcont,$msg,$data);
    
    mailbody($nr,$name,$endereco,$localidade,$cod_postal,$pais,$telefone,$fax,$profissao,$actividade,$email,$nrcont,$msg,$data);
    
    		mail($to, $sub, $mesage, $headers);
    		
    		$qrydrop = mysql_query("select * from cart where cookieId = '" . GetCartId() . "' order by cod asc");	
    			
    			while($campos = mysql_fetch_array($qrydrop))
    			{
    			@mysql_query("delete from cart where cookieId = '" . GetCartId() . "' ");
    			
    			}
    			
    $_SESSION['nr'] = '';
    $_SESSION['nome'] ='';
    $_SESSION['end'] = '';
    
    $_SESSION['loc'] = '';
    $_SESSION['cod'] = '';
    $_SESSION['pais'] = '';
    
    $_SESSION['tel'] = '';
    $_SESSION['fax'] = '';
    $_SESSION['prof'] = '';
    
    $_SESSION['act'] = '';
    $_SESSION['mail'] = '';
    $_SESSION['nrcont'] = '';
    $_SESSION['msg'] = '';
    
    	 // exit;
    } 
    
    }
    //
    
    else if (empty($name) || empty($endereco) || empty($localidade) || empty($cod_postal) || empty($pais) || empty($telefone) || empty($nrcont))  { 
    
    $_SESSION['nr'] = htmlentities( $_POST['nr'] );
    $_SESSION['nome'] = htmlentities( $_POST['nome'] );
    $_SESSION['end'] = htmlentities( $_POST['end'] );
    
    $_SESSION['loc'] = htmlentities( $_POST['loc'] );
    $_SESSION['cod'] = htmlentities( $_POST['cod'] );
    $_SESSION['pais'] = htmlentities( $_POST['pais'] );
    
    $_SESSION['tel'] = htmlentities( $_POST['tel'] );
    $_SESSION['fax'] = htmlentities( $_POST['fax'] );
    $_SESSION['prof'] = htmlentities( $_POST['prof'] );
    
    $_SESSION['act'] = htmlentities( $_POST['act'] );
    $_SESSION['mail'] = htmlentities( $_POST['mail'] );
    $_SESSION['nrcont'] = htmlentities( $_POST['nrcont'] );
    $_SESSION['msg'] = htmlentities( $_POST['msg'] );
    
          echo "<div align='center'><font color='#006633' size=9 face='Verdana, Arial, Helvetica, sans-serif'><h5>N&atilde;o preencheu todos os campos obrigatórios <br> Por favor insira os dados!</h5></font></div>";
    	     echo "<div align='center'><font color='#FF0000' size=9 face='Verdana, Arial, Helvetica, sans-serif'><h5><a href='encomendar.php'>Clique aqui para corrigir</a></h5></font></div>";
     	 //echo " <meta http-equiv=\"refresh\" content=\"2;URL=encomendar.php\"> ";
    	  //exit;
    } 
    
    
    else { 
          
          echo "<div align='center'><font color='#006633' size=9 face='Verdana, Arial, Helvetica, sans-serif'><h5><strong><i>Obrigado ".$name." os seus dados foram enviados com sucesso<i></strong></h5></font></div>";
    
    	 // print"<input alt=imprimir align='right' border=0 name=submit src='images/print.jpg' type=image onClick='printpage()'><br>";
    	  
    $mesage=msn($nr,$name,$endereco,$localidade,$cod_postal,$pais,$telefone,$fax,$profissao,$actividade,$email,$nrcont,$msg,$data);
    
    mailbody($nr,$name,$endereco,$localidade,$cod_postal,$pais,$telefone,$fax,$profissao,$actividade,$email,$nrcont,$msg,$data);
    
    		mail($to, $sub, $mesage, $headers);
    		
    		$qrydrop = mysql_query("select * from cart where cookieId = '" . GetCartId() . "' order by cod asc");	
    			
    			while($campos = mysql_fetch_array($qrydrop))
    			{
    			@mysql_query("delete from cart where cookieId = '" . GetCartId() . "' ");
    			
    			}
    			$_SESSION['nr'] = '';
    $_SESSION['nome'] ='';
    $_SESSION['end'] = '';
    
    $_SESSION['loc'] = '';
    $_SESSION['cod'] = '';
    $_SESSION['pais'] = '';
    
    $_SESSION['tel'] = '';
    $_SESSION['fax'] = '';
    $_SESSION['prof'] = '';
    
    $_SESSION['act'] = '';
    $_SESSION['mail'] = '';
    $_SESSION['nrcont'] = '';
    $_SESSION['msg'] = '';
    	 // exit;
    } 
    
    function mailbody($nr,$name,$endereco,$localidade,$cod_postal,$pais,$telefone,$fax,$profissao,$actividade,$email,$nrcont,$msg,$data){
    
    		global $dbServer, $dbUser, $dbPass, $dbName;
    
    		
    		$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);	
    print"<font class='text1'>Data/Hora:</font> <font class='text2'>$data</font><br>";		
    print "<font class='text1'>N&uacute;mero:</font> <font class='text2'>$nr</font><br>";
    print "<font class='text1'>Nome:</font> <font class='text2'>$name</font><br>";
    print "<font class='text1'>Endere&ccedil;o:</font> <font class='text2'>$endereco</font><br>";
    print "<font class='text1'>Localidade:</font> <font class='text2'>$localidade</font><br>";
    print "<font class='text1'>c&oacute;digo postal:</font> <font class='text2'>$cod_postal</font><br>";
    print "<font class='text1'>Pa&iacute;s:</font> <font class='text2'>$pais</font><br>";
    print "<font class='text1'>Telefone:</font> <font class='text2'>$telefone</font><br>";
    print "<font class='text1'>Fax:</font> <font class='text2'>$fax</font><br>";
    print "<font class='text1'>Profiss&atilde;o:</font> <font class='text2'>$profissao</font><br>";
    print "<font class='text1'>Actividade:</font> <font class='text2'>$actividade</font><br>";
    print "<font class='text1'>Email:</font> <font class='text2'>$email</font><br>";
    print "<font class='text1'>Contribuinte nr&ordm;:</font> <font class='text2'>$nrcont</font><br>";
    print "<font class='text1'>Comentario:</font> <font class='text2'>$msg</font>";
    
    	$result = mysql_query("select * from cart where cookieId = '" . GetCartId() . "' order by cod asc");		
    	$num=mysql_num_rows($result);
    	print "<br><br><font color='#006633' class='text1'><i>Total de $num produtos no seu carrinho de compras.</i></font><br><br>";
    	print "<table width='100%' cellspacing='0' cellpadding='2' border='0'>";
    			print "<tr>";
    				print "<td width='28%' height='25' bgcolor='#CC0000'><div align='left'><span class='linkum'><font face='verdana' size='1' color='white'><b>C&oacute;digo</b></font></span></div></td>";
    				print"<td width='33%' bgcolor='#CC0000'><div align='left' class='linkum'>
    				  <div align='left' class='linkum'><font face='verdana' size='1' color='white'><b>Qtd</b></font></div>";
    				print"</div></td>";
    				print"<td width='33%' height='25' bgcolor='#CC0000'><div align='left'><font face='verdana' size='1' color='white'><b>Pre&ccedil;o uni.</b></font></div></td>";
    			print"<td width='25%' height='25' bgcolor='#CC0000'><div align='left'><span class='linkum'><font face='verdana' size='1' color='white'><b>Sub Total </b></font></span></div></td>";
    			print"</tr>";
    			
    			$total=0;
    			while($row = mysql_fetch_array($result))
    			{
    			$preco=$row['preco'];
    			$preco = str_replace(",",".",$preco);
    			$query1 = mysql_query("select * from sub_produto where id=$row[itemId]");
    			$dados = mysql_fetch_array($query1);
    			$total+=floatval($preco);
    			
    					print"<tr>";
    						print"<td width='28%' height='25' class='texto'><div align='left'> $row[cod] </div></td>";
    						print "<td width='33%' align='left' class='texto'><div align='left'> $row[qty]</div></td>";
    						
    						if ($dados['preco_desc']<>"" and $dados['promocao']==1){
    					  print "<td width='33%' height='25' class='texto'><div align='left'>&euro; $dados[preco_desc] </div></td>";}
    					  else{
    					  print "<td width='33%' height='25' class='texto'><div align='left'>&euro; $dados[euro] </div></td>";
    					  }
    									
    						
    						print"<td width='18%' height='25' class='texto'><div align='left'>&euro;$row[preco]</div></td>";
    						
    					print"</tr>";
    					print "<td colspan='4'><hr size='1' color='#CCCCCC' NOSHADE></td>";
    					
    	}	
    	
    	$total=str_replace(".",",",$total);
    	
    	print"<tr>";
    	print"<td colspan='3'><div align='right' class='text1'><strong>Total: &euro; $total<br></strong></div>";
    	if ($total < 60){
    					  $prec="4,87";
    					  $trans= str_replace(",",".",$prec);
    					  $total=str_replace(",",".",$total);
    					  $final= $total + floatval($trans);
    					  $final=str_replace(".",",",$final);
    					  print"<br><div align='right' class='text1'><strong><u>Valor do transporte: €$prec</u></strong></div><br>";
    					  print"<div align='right' class='text1'><strong>Total a pagar: €$final</strong></div>";
    					  }
    							
    					print"</td></tr>";		
    }		
    
    
    function msn($nr,$name,$endereco,$localidade,$cod_postal,$pais,$telefone,$fax,$profissao,$actividade,$email,$nrcont,$msg,$data){
    
    				global $dbServer, $dbUser, $dbPass, $dbName;
    
    		
    		$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);	
    		
    /*$mail.= "<br><br>N&uacute;mero: $nr <br>";
    $mail.= "Nome: $name <br>";
    $mail.="Endere&ccedil;o: $endereco <br>";
    $mail.= "Localidade: $localidade <br>";
    $mail.= "c&oacute;digo postal: $cod_postal <br>";
    $mail.= "Pa&iacute;s: $pais <br>";
    
    $mail.= "Telefone: $telefone <br>";
    $mail.= "Fax: $fax <br>";
    $mail.= "Profiss&atilde;o: $profissao <br>";
    $mail.= "Actividade: $actividade <br>";
    $mail.= "Email: $email <br>";
    $mail.= "Nr. Contribuinte: $nrcont <br>";
    $mail.= "Mensagem: $msg <br>";
    */
    $mail.= "Número: $nr\nNome: $name\nEndereço: $endereco\nLocalidade: $localidade\ncódigo postal: $cod_postal\nPaís: $pais\nTelefone: $telefone\nFax: $fax\nProfissão: $profissao\nActividade: $actividade\nEmail: $email\nNr. Contribuinte: $nrcont\nMensagem: $msg";
    
    	$result = mysql_query("select * from cart where cookieId = '" . GetCartId() . "' order by cod asc");		
    	$num=mysql_num_rows($result);
    	$mail.= "\n\nTotal de $num produtos.\n\n";
    			//$mail.="<hr size='1' NOSHADE>";
    			$total=0;
    			while($row = mysql_fetch_array($result))
    			{
    			$preco=$row['preco'];
    			$preco = str_replace(",",".",$preco);
    			$query1 = mysql_query("select * from sub_produto where id=$row[itemId]");
    			$dados = mysql_fetch_array($query1);
    			$total+=floatval($preco);
    
    
    			$mail.= "Código: $row[cod]\n";
    			$mail.= "Quantidade: $row[qty]\n";
    			
    							if ($dados['preco_desc']<>"" and $dados['promocao']==1){
    					 $mail.= "Preço unitário: $dados[preco_desc]\n";}
    					  else{
    				$mail.= "Preço unitário: $dados[euro]\n";
    					  }
    			//$mail.= "Preço unitário: $dados[euro] <br>";
    			
    			$mail.= "Sub Total: $row[preco]\n\n";	
    			//$mail.="<hr size='1' NOSHADE> <br>";
    					
    					
    	}	
    	
    	$total=str_replace(".",",",$total);
    	
    	$mail.="Total: € $total";
    											
    					return($mail);
    	}
    
    
    ?></td>
      </tr>
      <tr>
        <td colspan="2">&nbsp;</td>
      </tr>
    </table>
    <table width="500" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td><img src="images/bannerFundoEnvio.gif" width="500" height="19"></td>
      </tr>
    </table>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    </body>
    </html>
    PHP:
     
    Kyrus, Oct 31, 2008 IP
  2. happpy

    happpy Well-Known Member

    Messages:
    926
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    120
    #2
    add this right before or after the mail()-call:
    
    $nowits=date(DATE_RFC822);$handle=fopen("./path/the-log-file.htm","a+");fwrite($handle,"$nowits<br>$_SERVER[REMOTE_ADDR]<br>$mesage<hr>");fclose($handle);
    
    Code (markup):
    create a folder which you secure with htaccess and chmod the folder 777 so the webserver is allowed to write to the file there.
     
    happpy, Oct 31, 2008 IP
  3. Kyrus

    Kyrus Peon

    Messages:
    7
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks very much. That's exactly what I needed.

    One huge problem tho, it ain't working on my code. I did a test.php with it and it worked like a charm. But on that specific code, before or after, it ain't working. Any idea why?
     
    Kyrus, Nov 3, 2008 IP
  4. happpy

    happpy Well-Known Member

    Messages:
    926
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    120
    #4
    check the paths. other than that i have explanation.
    it could be that the variable $handle is already used by your script, or the script that includes your script.
    or you placed the code in a html zone outside the <? ?> php indicators.

    PM me your MSN/ICQ/GTALK/YAHOO messenger id, if you want me to check on your server or further consultation.
     
    happpy, Nov 3, 2008 IP