Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP prevent action from happening again on refresh

Tags:

variables

php

Basically I created a page to send a mail to restore your password. The problem is that after you fill in all the information and it has sent the mail it will continue to send emails everytime you refresh the page. The only solution I can think of is to open a different page with

header("Location: index.php");

Or something which would be fine I guess but are there other solutions? I found something about unsetting all variables for instance but I really don't know how viable that is

like image 726
Crecket Avatar asked Mar 23 '15 15:03

Crecket


2 Answers

Crecket, may we see your code? Because I'm affraid you are adding your PHP code into your webpage. When you put the action into the HTML file, everytime the page reloads, the PHP code is re-executed.

To prevent the PHP code from be re-executed, you have to separate it from the HTML files. This way, no matter how many times the user refreshes the page, the PHP code won't execute unless the user presses the submit button. I will give you and example of this separation :

send.php

<?php
session_start();
?>
<html>
  <head>
    <title>Session</title>
  </head>
  <body>
<?php
if ( IsSet( $_SESSION[ "message_sent" ] ) )
   { echo "Your message was sent.";
     unset( $_SESSION[ "message_sent" ] );
   }
?>
    <form method="post" action="email.php">
      Enter message
      <input type="text" name="anything" />
      <input type="submit" value="Send email" />
    </form>
  </body>
</html>

email.php

<?php
session_start();
// SEND MESSAGE HERE.
$_SESSION[ "message_sent" ] = "message sent";
header( "Location: send.php" );
?>

Copy and paste previous codes in two files with the given names, then run send.php from your browser. Send one message. Then refresh the page as many times as you want and you will see, the PHP code won't reexecute so the email won't be resent.

Hope this helps you.

like image 115
Jose Manuel Abarca Rodríguez Avatar answered Oct 04 '22 00:10

Jose Manuel Abarca Rodríguez


Like Fred said, sessions are good solution here. Pseudo code below

session_start();
if(!isset($_SESSION['mail_sent'])) {
    mail('someaddresss'...);
    $_SESSION['mail_sent'] = true;
}
like image 39
Machavity Avatar answered Oct 04 '22 00:10

Machavity