Simple web form in PHP 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.

&lt;?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( '&lt;email removed&gt;', 'New order!', htmlspecialchars($contents), 'From: &lt;email removed&gt;' ) ) {
    die( 'Thanks! We will contact you very soon!' );
} else {
    die( 'Unfortunately an error occurred. Please try again later.' );
}
To add to Quill's answer, use heredoc whenever you want to use multiline strings.

$contents = &lt;&lt;&lt;CON
New order!

Name: {$name}
Phone number: {$phone}
City: {$city}
CON;

$content = htmlspecialchars($contents);


EDIT

Why &amp; how it improves your code,


Much cleaners and improves readability  
When you need double quotes inside the string you don't need to escape them
You don't have to worry about which characters to use when you need a line break.


A common use of this is when you write SQL queries, HTML or Email message bodies in your application. Basically multiline strings.