邮件功能不适用于条件

时间:2017-10-08 15:58:03

标签: php if-statement phpmailer

我的网站上有一个联系表单,使用php的邮件功能发送邮件。

这是我的代码:

	<?php
if(isset($_POST['your-email'])) {


$email_to = "felipepinoredes@gmail.com";
$email_subject = "Contacto Codelco";




$email_message = "Detalles del formulario de contacto:\n\n";
$email_message .= "Nombre: " . $_POST['your-name'] . "\n";
$email_message .= "E-mail: " . $_POST['your-email'] . "\n";
$email_message .= "Comentarios: " . $_POST['your-message'] . "\n\n";



$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);

echo "¡El formulario se ha enviado con éxito!";
}
?>

如果我就这样离开它,它就不会发送电子邮件,但是,如果我删除if并将其保留,就可以了:

$email_to = "felipepinoredes@gmail.com";
$email_subject = "Contacto Codelco";

// Aquí se deberían validar los datos ingresados por el usuario


$email_message = "Detalles del formulario de contacto:\n\n";
$email_message .= "Nombre: " . $_POST['your-name'] . "\n";
$email_message .= "E-mail: " . $_POST['your-email'] . "\n";
$email_message .= "Comentarios: " . $_POST['your-message'] . "\n\n";


// Ahora se envía el e-mail usando la función mail() de PHP
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);

echo "¡El formulario se ha enviado con éxito!";

但是我需要这个条件,我不希望每次加载页面时都自动发送空白邮件。

请帮助。

2 个答案:

答案 0 :(得分:1)

当一个变量通过POST发送到我们的脚本或GET总是被设置时,如果没有输入值,它将被设置为一个空字符串。因此,如果我们写下以下声明:

if(isset($_POST['your-email'])) {}

即使未输入任何值,也将始终评估为TRUE。因此,要验证我们的输入需要一些值,我们可以使用:

if(!empty($_POST['your-email'])) {}

if(isset($_POST['your-email']) && !empty($_POST['your-email'])) {} // Redundant

在问题的代码中if(isset($_POST['your-email'])) {}始终评估为true,即使$_POST['your-email']为空,也导致$email_message不完整。

答案 1 :(得分:0)

不确定它是否有帮助。但是如果首先是post方法,我会尝试请求。也许你正在使用get方法。

    <?php 
$hostname = "localhost";
$username = "root";
$password = "";
$database = "fransdemo";

$con = new mysqli($hostname, $username, $password) or die ("connection failed");
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

我还会在发送之前验证输入。因为你正在为你的代码打开后门。

if($_SERVER['REQUEST_METHOD'] === "POST"){
   if(isset($_POST['your-email'])) {
      ... your code ...
   }
}
相关问题