How can the PHP script be modified to ensure that data is only written to the file and emails are sent if all form fields are correctly filled out?
To ensure that data is only written to the file and emails are sent if all form fields are correctly filled out, you can add a validation check before processing the form data. This check should verify that all required fields are not empty or contain valid data. If any field fails the validation, the script should display an error message and prevent further processing.
if(isset($_POST['submit'])){
// Validate form fields
$errors = array();
if(empty($_POST['name'])){
$errors[] = "Name is required";
}
if(empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$errors[] = "Valid email is required";
}
// If no errors, proceed with writing to file and sending email
if(empty($errors)){
// Write data to file
$file = 'data.txt';
$data = $_POST['name'] . ' - ' . $_POST['email'] . PHP_EOL;
file_put_contents($file, $data, FILE_APPEND);
// Send email
$to = 'recipient@example.com';
$subject = 'New Form Submission';
$message = 'Name: ' . $_POST['name'] . PHP_EOL;
$message .= 'Email: ' . $_POST['email'];
mail($to, $subject, $message);
echo 'Form submitted successfully!';
} else {
// Display errors
foreach($errors as $error){
echo $error . '<br>';
}
}
}
Related Questions
- What are the best practices for using var_dump() or print_r() to display form input in an array in PHP?
- Is it recommended to combine multiple form elements into a single form for easier handling in PHP?
- What are the potential pitfalls of using JavaScript to create input fields for date and time entries in PHP?