cainam29 Posted August 16, 2017 Share Posted August 16, 2017 Hi I'm new to PHP and I have a code that send an email but how I can prevent it from always sending everytime my page refreshes. function two_dim_array_to_html_table($arr, $colcomments){ $ret = "<table border='1' width='auto' cellpadding='1px' cellspacing='0px' align='center'>\n"; $ret .= "\t<tr>\n"; foreach($arr[0] as $key => $val){ $ret .= "\t\t<th>".$colcomments[$key]."</th>\n"; } $ret .= "\t</tr>\n"; foreach($arr as $row){ $ret .= "\t<tr>\n"; foreach($row as $column){ $ret .= "\t\t<td>".$column."</td>\n"; } $ret .= "\t</tr>\n"; } $ret .= "<table>\n"; return $ret; } if($result) { $Body = "<html>\n" . "<head>\n" . "</head>\n" . "<body>\n" . two_dim_array_to_html_table($result, $colcomments) . "</body>\n" . "</html>\n"; //Setting up Mail $mail = new PHPMailer(); if (EMAIL_USE_SMTP) { // Set mailer to use SMTP $mail->IsSMTP(); //useful for debugging, shows full SMTP errors //$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only // Enable SMTP authentication $mail->SMTPAuth = EMAIL_SMTP_AUTH; // Enable encryption, usually SSL/TLS if (defined(EMAIL_SMTP_ENCRYPTION)) { $mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION; } // Specify host server $mail->Host = EMAIL_SMTP_HOST; $mail->Username = EMAIL_SMTP_USERNAME; $mail->Password = EMAIL_SMTP_PASSWORD; $mail->Port = EMAIL_SMTP_PORT; } else { $mail->IsMail(); } $mail->From = EMAIL_FROM_ADDRESS; $mail->FromName = EMAIL_FROM_NAME; $mail->AddAddress('DENNIS.TOMBOC@TELUS.COM'); //$mail->AddAddress('dlTIP-ITOPMiddleware@telus.com'); $mail->Subject = 'Daily MW ITSM Tasks - "'.date('d-m-Y h:m:s').'"'; $mail->WordWrap = 100; $mail->IsHTML(true); $mail->Body = $Body; $mail->Send(); } I tried using this but it does not work, if(!$mail->Send()) { header("Location: http://www.example.com"); exit; } Quote Link to comment Share on other sites More sharing options...
Jacques1 Posted August 16, 2017 Share Posted August 16, 2017 Don't use GET requests to trigger e-mails. Use POST and then redirect to another page (see the Post/Redirect/Get Pattern). GET requests are purely for getting content (hence the name). They must not have any side effects. Quote Link to comment Share on other sites More sharing options...
cainam29 Posted August 16, 2017 Author Share Posted August 16, 2017 I'm not using GET anywhere in my code. Quote Link to comment Share on other sites More sharing options...
Sepodati Posted August 16, 2017 Share Posted August 16, 2017 You basically have this: if($result) { // show HTML // send email } How do you want it to be different? What controls the value of $result? Is there another condition that you should check for before sending the email? I think we're missing part of the picture here. -John Quote Link to comment Share on other sites More sharing options...
cainam29 Posted August 16, 2017 Author Share Posted August 16, 2017 I dont know which part is essential so I'm pasting the entire code <div id="mainContent"> <table width="1198" height="24" border="0"b align="center"> <tr> <td width="667" align="left">Hello <?php echo $_SESSION['myusername']; ?></td> </tr> </table> <?php foreach($message as $key => $val){ // show error, warning and info messages if(!empty($val)){ echo '<div style="margin:4px;background:'.$bgcol[$key].';border:2px solid grey;border-radius:8px;">'; foreach($val as $item){ echo '<div style="margin:8px;">'.$item.'</div>'; } echo '</div>'; } } ?> <div> <form action="assign.php" method="post"><?php if(is_array($result)){ echo ' <fieldset> <legend>Assign Ticket</legend> <div>Changes will affect updated rows only.</div> <p></p> <table width=auto cellpadding=1px cellspacing=0px border=1 align=center id=assign> <thead> <tr>'; // column comment from DB as column header foreach($result[0] as $key => $val){ echo '<th align=center>'.$colcomments[$key].'</th>'; } echo ' </tr> </thead> <tbody>'; foreach($result as $row => $info){ echo '<tr>'; foreach($info as $key => $val){ if($key=='id'){ echo '<td title="'.$colcomments[$key].'">'.$val.'.<input type="hidden" name="'.$key.'['.$info['id'].']" value="'.$val.'" id="rowid_'.$val.'" /></td>'; } else { echo '<td title="'.$colcomments[$key].'"><input type="text" name="'.$key.'['.$info['id'].']" value="'.$val.'" /></td>'; } } echo '</tr>'; } echo ' </tbody> </table> </fieldset>'; } function two_dim_array_to_html_table($arr, $colcomments){ $ret = "<table border='1' width='auto' cellpadding='1px' cellspacing='0px' align='center'>\n"; $ret .= "\t<tr>\n"; foreach($arr[0] as $key => $val){ $ret .= "\t\t<th>".$colcomments[$key]."</th>\n"; } $ret .= "\t</tr>\n"; foreach($arr as $row){ $ret .= "\t<tr>\n"; foreach($row as $column){ $ret .= "\t\t<td>".$column."</td>\n"; } $ret .= "\t</tr>\n"; } $ret .= "<table>\n"; return $ret; } if($result) { $Body = "<html>\n" . "<head>\n" . "</head>\n" . "<body>\n" . two_dim_array_to_html_table($result, $colcomments) . "</body>\n" . "</html>\n"; //Setting up Mail $mail = new PHPMailer(); if (EMAIL_USE_SMTP) { // Set mailer to use SMTP $mail->IsSMTP(); //useful for debugging, shows full SMTP errors //$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only // Enable SMTP authentication $mail->SMTPAuth = EMAIL_SMTP_AUTH; // Enable encryption, usually SSL/TLS if (defined(EMAIL_SMTP_ENCRYPTION)) { $mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION; } // Specify host server $mail->Host = EMAIL_SMTP_HOST; $mail->Username = EMAIL_SMTP_USERNAME; $mail->Password = EMAIL_SMTP_PASSWORD; $mail->Port = EMAIL_SMTP_PORT; } else { $mail->IsMail(); } $mail->From = EMAIL_FROM_ADDRESS; $mail->FromName = EMAIL_FROM_NAME; $mail->AddAddress('Tony.Bodreau@TELUS.COM'); $mail->Subject = 'Daily Tasks - "'.date('d-m-Y h:m:s').'"'; $mail->WordWrap = 100; $mail->IsHTML(true); $mail->Body = $Body; $mail->Send(); } ?> <fieldset> <legend>Select Date</legend> <div>Select Date from and Date to</div> <p></p> <input type="date" name="from" id="from" value="<?=$date['from']; ?>" /> <input type="date" name="to" id="to" value="<?=$date['to']; ?>" /> <div><input type="submit" value="Submit" /></div> </fieldset> </form> </div> </div> Quote Link to comment Share on other sites More sharing options...
requinix Posted August 16, 2017 Share Posted August 16, 2017 I'm not using GET anywhere in my code.Even if the original page with the is not loaded with a GET request (though I would guess it is), the POST/REDIRECT portion of what Jacques said is still highly relevant. Quote Link to comment Share on other sites More sharing options...
Jacques1 Posted August 16, 2017 Share Posted August 16, 2017 I'm not using GET anywhere in my code. I'm not talking about your forms. I'm talking about all method(s) which trigger mail submission, regardless of whether you've intended that or not. If merely refreshing the page immediately triggers a new mail, then you do use GET, because POST requests are protected against accidental resubmission. You would have gotten a warning like this: If you click on “Resend”, well, then you'll obviously send another mail. Long story short: The mail code must be explicitly restricted to POST requests by checking $_SERVER['REQUEST_METHOD']. Then use P/R/G to fix the remaining usability problems. <?php // this part of the code is only executed on POST requests if ($_SERVER['REQUEST_METHOD'] == 'POST') { // this is where the mail code goes // if everything was successful, do a redirect header('Location: http://example.com'); exit; } // the remaining code is executed on each request (this is where you render the page) Quote Link to comment Share on other sites More sharing options...
cainam29 Posted August 17, 2017 Author Share Posted August 17, 2017 (edited) Yeah, sorry my explanation is misleading...my real issue here is that as soon as you access the page and it loads for the first time, it is already sending an email. That part where you refresh the page, I am getting that Confirm box to either Resend or Cancel. So I have the option to cancel that but when the page loads for the first time and is sending email right away that is an issue. Edited August 17, 2017 by cainam29 Quote Link to comment Share on other sites More sharing options...
Jacques1 Posted August 17, 2017 Share Posted August 17, 2017 Yeah. Do you understand the solution now? Quote Link to comment Share on other sites More sharing options...
cainam29 Posted August 17, 2017 Author Share Posted August 17, 2017 I think I know where my real issue is by doing several tests, so when I access the page "assign.php" it will load the page where I can select "date from" and "date to" which then would load the fetch data after hitting submit button but an email is being sent as well as soon as the page loaded with the fetch data. That should not be sending an email and what i would exactly want to happen is the mail would just be triggered if the assign column is already filled up or the db is updated by the values in "assign" column. The entire code is posted above. I dont now how to fix this as when i tried to use "if(isset($_POST['submit']))" but phpmail gets triggered right away even if the purpose of clicking submit is just to get the data. I dont know how to fix this. Quote Link to comment Share on other sites More sharing options...
ginerjm Posted August 17, 2017 Share Posted August 17, 2017 Modify the code to check what has been submitted. Check for a button that says 'Send Mail' perhaps? And when the mail has been sent - don't send back the same page or be sure to clear out the input fields so that a refresh can't occur or at least it won't be sending back the same inputs a 2nd time. Think about the situation and program your way out of it. Quote Link to comment Share on other sites More sharing options...
requinix Posted August 20, 2017 Share Posted August 20, 2017 According to the code in the duplicate thread you just made, you're sending the email if a name=submit button was pressed. Is it just me or does that happen to be the same way you're loading the page the first time? By clicking a button? Quote Link to comment Share on other sites More sharing options...
cainam29 Posted August 20, 2017 Author Share Posted August 20, 2017 Yes you are correct, the first time the submit button is clicked to load the page and shows the data, it is sending an email as well which it should not be doing. it should just be sending an email when i click on the submit button the second time, that is after i edit the data and when i wanted to update the db and send an email (this is the part where i wanted it to send an email). Quote Link to comment Share on other sites More sharing options...
Sepodati Posted August 20, 2017 Share Posted August 20, 2017 There's no concept of a "second" button press in HTTP. $_POST["submit"] is the same in both cases. How do you expect to tell the difference? You need something that makes the forms different. Use PHP effort that, to create different forms based on where you're at in the process. A hidden form element or differently named submit buttons would be a start. Quote Link to comment Share on other sites More sharing options...
ginerjm Posted August 20, 2017 Share Posted August 20, 2017 As you said your script runs and first outputs the html for the form and immediately sends an email. This has to stop. So - fix your script to think for itself. Perhaps check if there is a POST method and if NOT, then only output the html. When you script next runs (from the submit button?) AGAIN check if the request method was a POST and THEN, process any input from the form and (if valid) send your email. And as I said before - once you have sent the email, modify your output so that a refresh won't have anything to process. Either clear out all the (expected) input values, or remove the submit button that triggers the email, or just output a different form saying that the email has been sent. Quote Link to comment Share on other sites More sharing options...
mac_gyver Posted August 20, 2017 Share Posted August 20, 2017 (edited) i have a question about the email you are sending. what does it have to do with updating the database data? if the mail is for daily task notification, it's not part of the update process and shouldn't even be part of this code. if you want to check for daily task information and send email(s) based on that information, you would trigger the email code via a scheduled task/cron job, query for the data you want, the produce and send the email(s). for your current code, you need to organize it so that you and anyone else that looks at it can see what it is even trying to do. this will help you to write logic that will do what you want. your search/filter form (start and end date) needs to use method='get', since it is controlling what data is gotten and displayed on the page. your data editing form is the only form that should use method='post'. (your last posted code in the other thread doesn't even have this form in it, so the code won't work anyways.) your code should be generally organized as follows - 1) common code needed for the whole page - start/restart session, 'require' or define in-line, code that your main code needs, initialize variables, ... 2) post method form processing code - 2.1) detect that a post method form has been submitted 2.2) if your code processes more than one form, such as for inserting, updating, and deleting, detect which form has been submitted, using a hidden 'action' field, with a different value for each of those processes 2.3) validate the input data 2.4) if there are no validation errors, use the submitted form data 3) get method code - code that retrieves/produces data needed to display the page 4) html document/template your code that's updating the data and sending an email related to that update would all be together as part of the code in item 2.4. you currently don't have the email code as part of that. Edited August 20, 2017 by mac_gyver Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
× 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.