JakeKempo
JakeKempo

Reputation: 590

retrieve keys values from post

I have a contact form posting a name, email address and message. I want to retrieve the values and send as an email.

Here is my code:

<?php

foreach($_POST as $key=>$value)
{
  $key = $value;
}

$subject = "Website Contact Form";
$sender = $email;
$bccemail = $adminemail;
$receiver = $adminemail;

if(isset($name) and isset($email) and isset($sender) and isset($receiver) and isset($subject) ) {

$ToEmail = $receiver;

$mailheader = "From: " .$sender."\r\n";
$mailheader .= "Bcc: " .$bccemail."\r\n";
$mailheader .= "Reply-To: ".$sender."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";

$message_body = "<br /><b>Name:</b> " . $name . "<br />";
$message_body .= "<b>Email: </b> " . $sender . "<br />";
$message_body .= $message . "<br />";

if(@mail($ToEmail, $subject, $message_body, $mailheader)) 
{
    echo "Success";
} else {
    echo "Error";
}

} else {
    echo "Big Error";
}
?>

From this I get echoed - "Big Error".

If I echo...

foreach($_POST as $key=>$value)
{
    echo "Key: $key<br />\n";
    echo "Value: $value<br />\n";
}

Then I get

Key: name Value: Jake Key: email Value: [email protected] Key: message Value: This is the message

So I know the form data is being posted.

If I put the variables into the php like so..

$name = "Jake";
$email = "[email protected]";
$message = "This is the message";

Then is works.

So I know it is something to do with retrieving the form data from the array.

Upvotes: 1

Views: 175

Answers (2)

Krish R
Krish R

Reputation: 22711

extract($_POST, EXTR_SKIP);

EXTR_SKIP - If there is a collision, don't overwrite the existing variable.

Do not use extract() on untrusted data, like user input (i.e. $_GET, $_FILES, etc.). If you do, for example if you want to run old code that relies on register_globals temporarily, make sure you use one of the non-overwriting flags values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.

Ref: https://www.php.net/extract

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50767

Looks like you're trying to do shorthand assignment for the quick and easy, which is fine, but you need to use extract() instead.

extract($_POST);

In this case, the key will be the variable name, so you can do

echo $name;
echo $email;
echo $message;

Otherwise, you just need to do assignment.

$name= isset($_POST['name'])?:false;
$email = isset($_POST['email'])?:false;
$message= isset($_POST['message'])?:false;

Using either of the above, you can then make your conditional shorter:

if($name && $email && $message):
    //successful
else:
    //failure
endif;

Upvotes: 4

Related Questions