This is a simple web form handler in PHP that sends a completely filled web form to a email.
- I see lots of repeating code. What is the best way to reduce repetition?
- Is my way of checking for fields being empty good? The "empty()" method seems to also treat "0", "0.0" and similar values as empty.
- Am I doing something that is unneccesary?
Any other criticism is appreciated.
<?php
if ( $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
die( 'Please use a form to send a message!' );
}
if ( !isset( $_POST['name'] ) || trim( $_POST['name'] ) === '' ) {
die( 'Please enter your name!' );
}
if ( !isset( $_POST['phone'] ) || trim( $_POST['phone'] ) === '' ) {
die( 'Please enter your phone number!' );
}
if ( !isset( $_POST['city'] ) || trim( $_POST['city'] ) === '' ) {
die( 'Please enter your city!' );
}
$name = trim( $_POST['name'] );
$phone = trim( $_POST['phone'] );
$city = trim( $_POST['city'] );
$contents = '';
$contents .= "New order!\r\n";
$contents .= "\r\n";
$contents .= "Name: {$name}\r\n";
$contents .= "Phone number: {$phone}\r\n";
$contents .= "City: {$city}\r\n";
if ( mail( '<email removed>', 'New order!', htmlspecialchars($contents), 'From: <email removed>' ) ) {
die( 'Thanks! We will contact you very soon!' );
} else {
die( 'Unfortunately an error occurred. Please try again later.' );
}