Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.

Example:

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