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

Kirran Iveson
Kirran Iveson
2,191 Points

Why does the $_SERVER code go at the top of the document when it's supposed to run after the submit button is clicked?

From the start we've always had "cascading nature" and "flow" drilled into us, so I'm just curious why it doesn't actually matter in this case.

How does the $_SERVER code run when it comes before the form itself? It made sense when there was a page redirect, but now we've put it all on one page... Would anyone be able to explain?

1 Answer

When the submit button is clicked, the page is essentially reloaded and is re-executed from the top down. So, when you visit the page for the first time, it checks to see if the form was submitted. The check fails (because the form hasn't been submitted), so it loads the form, which is where you input your information. After you submit the form, the same page is loaded again. It checks again to see if the form has been submitted, and this time, the check returns true. So instead of presenting the form, it goes and does other things with the submitted data.

In actuality, it's just a little more involved than that, but that's close enough.

Kirran Iveson
Kirran Iveson
2,191 Points

Ah so the submit button, in simplest terms, acts as a reload for the code. While you did hint at more, I think for now I can live with that as an explanation :) Cheers Ryan!

Yeah, Kirran, the submit button processes the form using whichever page you specified in the

html
<form action = "example.php" ... etc>
``` part of the form. You basically link to whatever file contains the script for running the form. Code is processed top to bottom, and it stops whenever it reaches a place that causes it to stop there (i.e an error, a redirect, an if-else statement, etc).