简体   繁体   中英

Break an if/else statement if condition is not met

I have a form I use php to process, it works except when a condition is not met. Instead of using a captia I hide a normal field. The process is only suppose to run if the hidden field is = to nothing. otherwise it is suppose to break. It works if $hide (hidden field) = nothing but it throws an error when the field is filled out.

<?php
$to      = 'test@test.com';
$email   = $_POST['email'];

$name  = $_POST['name'];
$subject = $_POST['subject'];
$message = $_POST['comments'];
$hide = $_POST['message'];
$error=array();
if ($hide!=''){
    break;
}else{
    if($_POST['name']==''){
        $error[]="Your name is required";
    }
    if($_POST['email']==''){
        $error[]="Your email is required";
    }
    if($_POST['subject']==''){
        $error[]="Subject is required";
    }
    if($_POST['comments']==''){
        $error[]="Comments is required";
    }

    if(count($error)>0){
        echo "<div class='alert alert-danger'>";
        foreach($error as $data)
        {
            echo "<p>".$data."</p>";
        }
        echo "</div>";
        die();
    }

    $headers = 'From: Attorney Website'. '<'.$email.'>' . "\r\n" .
        'Reply-To: '. $email . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    if(mail($to, $subject, $message, $headers))
    {
        echo "<div class='alert alert-success'>You message has been succesfully received. We will reply you soon.</div>";
        die();
    } else {
        echo "<div class='alert alert-danger'>Opps! Something went wrong. Please try again.</div>";
        die();
    }
}
?>

You don't need to use break

Replace:

if ($hide!=''){
    break;
}
else {

with just

if ($hide) {
   // run email code

this will ensure $hide contains something before continuing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM