Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
general improvements Move everything that is directly related for the submission inside the if ... 'POST' condition. if ($_SERVER['REQUEST_METHOD'] == 'POST') { $to = 'example@example.com'; ...
Answer
#1: Initial revision
## general improvements Move everything that is directly related for the submission inside the `if ... 'POST'` condition. ```php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $to = 'example@example.com'; $subject = 'הודעה חדשה מאת: ' . $name; include 'message.php'; $headers[] = 'MIME-Version: 1.0'; $headers[] = 'Content-type: text/html; charset=utf-8'; mail($to, $subject, $message, implode("\r\n", $headers)); header('Location: $contact_form_success_webpage'); exit; } ``` there is no benefit of running all this code without submission of the form. Setting the other variables is useful if you use them in the form to keep the values on failed validation, otherwise you could move them also inside the condition. ## validation You should make sure the required fields are actually enforced. ```php $errors = []; for ($required_field in ['topic', 'name', 'email']) { if (array_key_exists($required_field, $_POST)) { if (empty($_POST[$required_field])) { $errors[] = "$required_field cannot be empty"; } } } if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($errors) == 0) { // ... } ``` Then, beside your form you can output those error messages: ```php if (count($errors) > 0) { echo "<p><b>Error validating your field:</b><br>"; echo implode("<br>", $errors); echo "</p>"; } ```