HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Simple web form in PHP

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
phpformsimpleweb

Problem

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.

', 'New order!', htmlspecialchars($contents), 'From: ' ) ) {
    die( 'Thanks! We will contact you very soon!' );
} else {
    die( 'Unfortunately an error occurred. Please try again later.' );
}

Solution

To add to Quill's answer, use heredoc whenever you want to use multiline strings.

$contents = <<<CON
New order!

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

$content = htmlspecialchars($contents);


EDIT

Why & 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.

Code Snippets

$contents = <<<CON
New order!

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

$content = htmlspecialchars($contents);

Context

StackExchange Code Review Q#106212, answer score: 3

Revisions (0)

No revisions yet.