Question

Hi Could someone please tell me if the following is possible please?

I have a small php contact form which sends the information collected on the form to a designated email address

$emailaddress=whatever@whatever.com

What I am trying to achieve is that every time the form sends data, it switches so it would do the following...

Customer sends data via submit to $emailaddress1=whatever@whatever.com

The next customer sends data it submits to $emailaddress2=whoever@whoever.com The next customer sends data via submit to $emailaddress1=whatever@whatever.com again and so on.

Essentially every other send switches the email address to a different one to the last send.

Thanks in advance Tilly

Was it helpful?

Solution 3

Problem resolved thanks to Boerema plus a few little tweaks of my own.

Basically I just changed the delete part till after the form was processed, sine when the form is displayed it was deleting or creating without submission.

So...

In the form itself the code is...

$filename = '/full/path/to/tempfile/sent.txt'; 
if (file_exists($filename)) { //
$recipients = 'number1emailaddress@test.com';
} else {
$recipients = 'number2emailaddress@test.com';
}

Then after the form has processed

$filename = '/path/to/your/tempfile/sent/sent.txt';

if (file_exists($filename)) {
unlink($filename); //delete the file
} else {
fopen($filename, 'w') or die('Cannot open file:  '.$filename); //implicitly creates file
}

This way the file is only deleted/created on an actual submission, which works perfectly

Many thanks Boerema

OTHER TIPS

From the discussion in your comments, I would say the best answer is to use a simple file to indicate whether you want to send the email to address 1 or address 2. If you are ever only going to have two addresses, you could even simply use the EXISTENCE of the file as the indicator.

if (file_exists($filename)) {
    $toAddr = 'whatever@whatever.com';
    unlink($filename); //delete the file
} else {
    $toAddr = 'whoever@whoever.com';
    touch($filename); //create the file empty
}

If you have heavy usage, you may get an instance where two emails would go to one email at the same time, but it doesn't sound like that is a big issue.

If you need to have more than two addresses, then just write out to the file and read the value to determine where you want to send it instead of deleting and creating it.

You can try using a counter to know which email to send to.

$counter = 0;

if ( $_SERVER['REQUEST_METHOD'] == 'POST' ){

    $counter++;

    if ( $counter % 2 == 0 ){

        $email = 'email@address.com';

    } else {

        $email = 'email2@address.com';

    }

}

This will put a different email at even and odds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top