How does a PHP page retrieve form data? - php

I am new to PHP and am taking the PHP course on W3Schools. In the form handling part of the course, I read that there are two methods of handling form data: POST and GET. I understand that depending on the method used, a superglobal variable is created which stores the data as key-value pairs. And at the destination page, the data is retrieved from this variable (using $_POST["key"] or $_GET["key"]).
But my question is: Where is the superglobal variable ($_POST or $_GET) stored? If it is on that same page on which the form exists, how can it be accessed by another destination page specified in the action attribute of the form tag?
Is it that the same set of these superglobal variables are accessible by all the pages on the server (contrary to my present belief that each page has its own set of those)?
The code below should make my question more clear:
File index.php
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
File welcome.php
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
W3Schools explains as follows:
When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables.
How do the variables $_POST["name"] and $_POST["email"] reach welcome.php?

Superglobals do not refer to the lifetime of a variable, but the scope in which the variable can be accessed.
Session variables can be accessed by other pages.
Also, regarding your comment "If that is the case, how can the second.php display the form data entered in first.php?"
first.php should save data to a database. second.php should read data from the database. If you are very new, I would suggest looking in to MySQL as a database. It plays very well with PHP.

When you send a request to a web server (i.e. apache, nginx), the request is parsed into pieces to be understood. Then, in PHP's case, the file requested is sent to the PHP interpreter with the data from the request.
In your example, you want a form to send a POST request to the page welcome.php. (If you're new to requests methods GET/POST/etc, then w3schools has a simple explanation on that: http://www.w3schools.com/tags/ref_httpmethods.asp) Your form has the method set to post, this can be get but it generally never is. If a user pressed a submit button within a tag, then the form sends to the request to the page set in action using the method set in method. Your form will send a POST request with the data name="..." and email="...".
When this request reaches PHP, all data sent to it will be stored in the method global variable. All post request place their data in $_POST, all get requests place their data in $_GET.
So when you submit your forms POST request, the page welcome.php will be requested by your browser (Firefox/Chrome) using the method POST and sending the data name and email in that request. On your server, PHP will open the file welcome.php and place the data into the $_POST array. Then, since $_POST is global, anywhere within welcome.php will have access to this variable.
If you manually go to the page welcome.php, you will be performing a GET request. Generally, only way to send a post request is through a form. So manually going to that page will have $_POST set to an empty array.
When I was learning PHP, I almost always had these lines at the top of the page so I knew what was going on:
<pre><?php print_r($_GET);?></pre>
<pre><?php print_r($_POST);?></pre>
This will print out the arrays in a pretty format, and the tags will make sure they're formatted correctly in the browser (since print_r uses newline characters, and browsers ignore those unless in pre tags).
You could also swap print_r with var_dump to get way more info about the variable.
This is a simple answer, there's way more to web technologies. And once you understand PHP enough I'd move into frameworks like CakePHP or CodeIgniter which takes away a lot of the little bits. It's important to understand the basics first though.

Regarding your edit:
<form action="welcome.php" method="post">
The method="post" bit means that when the user hits "Submit" (or whatever triggers action="welcome.php") the data will be collected from the form element and sent as POST data to the action target -- since it's a php file, you can then access this data through the superglobal, $_POST, as you've noted.
The name property in each of the inputs inside the form sets the key for each element of the POST data that is sent, and whatever the user entered in the input will be the corresponding value to that key.
For instance, if the user entered "foo" for the name, and "bar" for the email, your $_POST data in welcome.php should look something like:
Array
(
[name] => foo
[email] => bar
)

Related

How to output a new form in redirected php files?

I am trying to pass variables buy echoing new forms after using header("Location: location.php"). So when it is redirected, it outputs the form in the redirectred php file.
<?php
header("Location: location");
echo "<form><input type = 'submit' value ='try again' > </form>";
//expected output:the form outputs in the same files
?>
Using header("Location:page") immediately exits your script and redirects the user to that page. However, I have successfully accomplished something very similar (to what I think you want) by scripting a Website Registration API.
In total, I wrote 3 critical scripts, plus the original form page, in/out functions, and an assortment of data storage modules to create a seamless process. Your needs might not be as complicated as mine, but I found this to be much more involved than a simple 'validation check'.
Basic outline:
page original form is on: submit sends form data to script
script parses incoming data and determines action
each input variable is parsed
if form data is empty: user is sent to original (blank) form page
if form data flags bad input: the form is reprinted (errors in red)
if form data is legit: data is stored; script advances to user portal
login/logoff functions
Try to solve your problem by thinking about each step of the process and breaking it down into bite-size pieces. (first you have to see the input, then you have to check the input, etc.)
After the header("Location:url"); no other command will be executed
but you can used document.getElementById("myForm").submit();
<form id="form" action="/url"><input type = 'submit' value ='try again' > </form>";
//expected output:the form outputs in the same files
<script>
document.getElementById("form").submit();
</script>
or used curl

Different between actions

I want to know different between <form action="#" method="post"> and <form action="name of file" method="post">
I am always using # but don't know disadvantages.
Can you explain why I should use # or file name?
Thanks
form action = file name
It is used to send a request on the other page(i.e your file name) containing your form fields(inputs) with methods like GET and POST.
example my HTML page is having a form then and my PHP page is having all the backend code. Whatever I need to do with form inputs. I will give the file name of my PHP page in action. the action attribute of the form is used to send the form request to the destination we want to with methods like the POST and GET. If you do not want to send a request to another Page and want it to your default page. You can leave action ='' attribute of the form empty as I did.
An action of # indicates that the form stays on the same page, simply suffixing the URL with a #. A similar use occurs in anchors. Link for example, will stay on the same page.
Thus, the form is submitted to the same page, which then processes the data etc
The content of action allows you to know where you will put the code that will process the request.
If you put the name of a file it, then his file will process the request.
For example: you have your form on the index.php page and you want to put the PHP code of the form in a process.php file. You will put process.php in action (action="process.php").
If you do not put anything it is like sending the content of the request to the same file (index.php).

Is it because $_GET is global or the form submitting to itself or else?

I am trying to understand one simple thing in PHP form handling.I am new to it and I have a sample code:
<form name="frm" method="post" action="">
Item Name:<input type="text" name="itmName" id="itmName"/><br/><br/>
<input type="submit" name="sbmit" value="Add Record"/>
</form>
<?php
if(isset($_GET['m']))
{
echo '<script type="text/javascript">alert("'.$_GET['m'].'");</script>';
}
if(isset($_POST['sbmit']))
{
header("location:1.php?m=10");
}
?>
Irrespective of what data I send to the server, my focus is on the if(isset($_GET['m'])) part of the code. Everytime I submit the form, the 'if' is always evaluated to true and as a result the alert box appears.Is it because $_GET is holding the previous value set by header("location:1.php?m=10"); or is it because the form is submitting to itself or else?Googling didn't provide much help. I need better understanding over this.With Thanks
Since you are not specifying an action, it is going to get defaulted to the current pages url, in this case "1.php?m=10" (if that is what it was as you say). Even though the form is getting submitted via POST, the query string is still passed and still accessible.
To prevent it from being set, all you need to do is specific your form action
1°) when you submit your form, the post method send "itmName" and "sbmit" to the same page (because you didn't write anything in "action=").
2°) if the page received the post var 'sbmit', and i does, you ask to the server to redirect the page to the same page (i guess) with a get variable (m=10)
3°) you ordered your page to send an alert if it recieves something in the 'm' get variable.
So in only one shot, your sever does thoses 3 steps. That's why every time the alert is sent.
You are right, the form is client side.
When the submit button is cliked, the post datas are send to the server. Now in server side, the first thing the server see is "if(isset($_POST['sbmit']))" which orders a redirection but in php not in javascript, so we stay server side with the load of a new page that first need to be interpreted by the server because it contains a get variable.
This Get variable is detected by the server and automatically is turning "if(isset($_GET['m']))" on true. Now it writes the javascript tag that will be interpreted client side with the launch of the alert.

unset($_GET['someVariable']) not working

My web page "mywebpage.php" is arrived at by way of a 'GET' from "someotherpage.php":
// In someotherpage.php -- go to mywebpage.php and display the form:
window.location = "mywebpage.php?someVariable=" + theVariable;
I handle this in "mywebpage.php" as follows:
THIS IS THE 'GET' HANDLER for the form IN "mywebpage.php":
if(isset($_GET['someVariable']))
{
// set up form variables to initial values, then display the form
}
When the form is SUBMIT'd, I re-enter the same "mywebpage.php" to handle the POST of the form:
THIS IS THE 'POST' HANDLER IN "mywebpage.php"
// okay the form was submitted, handle that here...
if(isset( $_POST['theformSubmitButton']))
{
// handle the form submit
}
The problem is when the user submits the form, the GET handler is still called so the form gets re-initialized.
The reason is, when the user POST's the form, the GET['someVariable'] is still there so the GET handler is re-entered, and then the POST handler code is processed, but by then the GET handler re-initialized the form which confuses the user since they just got done changing the form's values away from the initial settings.
In other words, when the form is submitted, the POST array is being correctly filled, but the GET array hangs around for the ride with its old variables still there, including 'someVariable'
So I added an 'unset' call in the GET handler:
this is the MODIFIED 'GET' HANDLER in "mywebpage.php"
if(isset($_GET['someVariable']))
{
// set up form variables then display the form
// now clear out the 'someVariable' in the GET array so that
// when the user POST's the form, we don't re-enter here
unset($_GET['someVariable']));
}
THIS FAILED TO WORK. When the form is posted, I'm still seeing that the GET handler above is called.
I need to make sure when the form is submitted, the GET handler is not re-called -- why doesn't the "unset()" code above work?
EDIT: Here is the form, not everything just the important parts (I left out a lot of inputs, several img tags, etc., nothing more):
<form enctype="multipart/form-data" action="#" style="display: inline-block"
method="post" name="myForm" id="myFormId">
<textarea name="InitialText" id="theText" rows="4" cols="68"
style="border: none; border-style: none"></textarea>
<br />
<label style="font-weight: bold; font-style: italic">For more info provide an email addres:</label>
<input type="text" id="emailField" name="emailFieldName" value="you#gmail.com" />
<input type="submit" id="theformSubmitButton" name="theformSubmitButton" value="Post Now">
</form>
GET Request and the $_GET variable are on two different layers.
When your user gets directed to mywebpage.php, there is data passed through get. That is ok this far, however that data is still inside your users current URL. You can see that by looking at the address bar. There will be a ?someParameter=someValue at the end of the address.
The unset function will only work on your server and only for the one time execution of your script. It will not remove the GET information from the URL in your users browser.
When you submit data through your HTML form, you redirect the user to the same url, which includes the GET data, which is not still there, but is being resubmitted again.
Try setting:
<form action="mywebpage.php" method="post">
This will set a custom target for your html form, which removes the GET information.
I'd avoid using $_POST or $_GET directly as often as possible. Reason: you're able to filter/modify the requests global. Simple Example:
$myPost = $_POST;
$myGET = $_GET;
unset($myGET["someVariable"]);
Generally: why're you using $_GETand $_POST at the same time? If you've to do it, you could handle it with if, if else and else.
That's because you unset the variable but
window.location = "mywebpage.php?someVariable=" + theVariable;
is the same.
My guess is that you need to change when the variable is not set to have something like this:
window.location = "mywebpage.php";

Convert $_GET variables to $_POST and redirect page

I'm sending info through a link read in an email via $_GET (i.e. link in email is in form http://website.com?dogs=cats"). But I want the site URL to not have the appendages visible. So I've tried:
Linking to a page which saves the $_GET in a hidden form fields, then automatically submits the form; problem is that the back button then leads back to this intermediary page
Same as above, opening intermediary page in new tab, then having the form load another new tab (_blank), and closes itself; works fine, except in IE these are windows, which are annoying
I'm considering saving the $_GET results in a cookie, then redirecting the page with a header(), then extracting data and expiring the cookie.
Is there an easier way that I'm overlooking?
How about starting a session and storing them to the $_SESSION variables?
Here is a sample implementation of how you can make a hidden arguments on links. This sets a custom handler on the links which will copy hidden argument into the form and send it through post request. It is not a substitute to the session, but it can have it's own uses.
<form id="form" method="post" action="">
<input id="dogs" type=hidden name="dogs">
</form>
Sample link
<script>
$(function(){
$('a').click(function(ev){
ev.preventDefault();
$('#dogs').val($(this).attr('data-dogs'));
$('#form').attr('action',$(this).attr('href')).submit();
}
});
</script>

Categories