Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Question about the Contact Page section in the BUILDING A SIMPLE PHP APPLICATION track.

Would it be correct to use:

if ($_POST != null) {execute contact-form process code}

in the place of

if ($_SERVER["REQUEST_METHOD"] == "POST") {execute contact form process code}

when checking whether a form has been submitted, with its action attribute set to the same page, and if not - why? I am not against using the $_SERVER variable method but I decided to experiment with the above code and it worked just fine. :)

Is there any flaw with using this procedure would cause an error?

2 Answers

This might be of interest to you.

What they're saying is when checking $_POST != null, you're checking the contents of the actual post data. What if someone submits the form with no data (which is possible), and you want some validation to run etc?

Total. Anarchy.

I haven't actually tested this, but to me, it seems most sensible to be as exact as possible with checks like this to avoid bugs and other such calamities.

You could always check for both to be super sure :-)

I actually wrote a reply before but I just realised it wasn't posted. You're absolutely right in that situation, it would be much more tasking to run validation when an empty form is neglected from ($_POST != null) { Run contact-process } - for example to display an "Incomplete fields" message. I had not thought ahead there, and was simply experimenting within the current context.

My logic centered on the fact that until a user has sent in form data, the page's $_POST variable is empty or null. Once the user sends in DATA, $_POST is no longer null and thus the contact-process code will be processed by the PHP file. This logic seemed to have worked, but it had not crossed my mind about testing it with empty form data. I did so and realised that for some reason the contact-process code had still run and redirected to the "Thank you" message, even though I had assumed that by sending empty form data, $_POST would remain null.

This made me suspect that there was still some data being sent with an empty form, and eventually realised that the form was still sending the $_POST array key values of "Name", "Email" and "Message" (from the input field name attributes) but with corresponding empty string values from an empty form.

Trial and error mate! Trial and error. PHP is so exciting!

Thanks for the reply