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! While you're at it, check out some resources Treehouse students have shared here.

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

PHP Build a Simple PHP Application Adding a Contact Form Checking the Request Method

Hello World
Hello World
12,904 Points

$_SERVER['REQUEST_METHOD'] VS isset($_POST['submit'])

Can anyone explain why did Randy use if($_SERVER['REQUEST_METHOD'] == POST) to check if the form has been submitted instead of using if(isset($_POST['submit']))? Isn't isset more direct and meaningful to the purpose of using the if statement here?

1 Answer

This is a good question. I think both will yield the same answer. The first method check if post is an element of the $_server array that is it checks if something has been posted to the server and the last method isset($_POST["submit"]) checks if a there is a element with the key "submit" in the post array. Make sure your submit buttons (ie. <input type="submit"> etc) have a "submit" value assigned to 'name' attribute. If they don't, the value won't appear in $_POST and so isset($_POST["submit"]) won't work either.


<input type="submit" name="submit" value="Next">

isset($_POST["submit"]) returns true.

<input type="submit" value="Next">

isset($_POST["submit"]) returns false

This answer explains why very well. The $_SERVER method is more robust, but not precise. The first method is good if you do not care what was posted to the server. The second method is great if there are multiple submissions and it matters what was picked.