Jump to content

PHPMail always sending when page is refreshed


cainam29

Recommended Posts

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;
}

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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>
Link to comment
Share on other sites

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:

 

post-167590-0-67202700-1502896155.png

 

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)

post-167590-0-67202700-1502896155_thumb.png

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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).

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.