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

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";

Related

How does a PHP page retrieve form data?

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
)

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.

Page refresh causes form submission [duplicate]

This question already has answers here:
Avoid resending forms on php pages
(6 answers)
Closed 9 years ago.
I have a webpage that contains a form that uses the POST method and references the same page it is on for submission. I am using a PHP include file that contains an if statement that runs when the submit value is set. For some reason though, after one submission, every time you refresh the page it submits the form with the previously submitted data (The browser warns of this before refreshing the page). What causes this, and what could I be doing wrong?
This is expected. You should have the form submit to a handler that has a unique URL, whether it be a query string or a different URI. One solution (of many) would be to change your form action:
<form action="?action=submit" method="post">
<input type="hidden" name="action" value="submit" />
...
and then in the PHP script handle the form, then change the context back to a URL without the hidden query string
if (!empty($_POST['action']) && $_POST['action'] == 'submit') {
// do stuff
header('Location: '.$_SERVER['SCRIPT_NAME']);
die();
}
Note the query string is not actually present in $_POST but we keep it there so browsers don't consider it to be a redirect loop.
i had the same issue with one of my pages.
the reason is that when the browser warns you that it will submit the form again, that means it is going yo be the same exact thing when you click on a submit button.
I did 2 things to avoid it but i am sure there many other ways.
1. Do not let the page echo the form again after succesfull submission of the form.
mine was like this
<?php
if(!isset($_POST['submit'])) {
include(form.php);// you can modify this according to your needs.
} else {
//display your message about what happened with the form.
}
?>
with that approach, your page will not the contaion a form to submit HOWEVER this will not prevent it from submitting on refresh.
2. if the form is submitted create a contoller input that carries a value indication that the form is already submitted. for example , place this into your form:
<?=(isset($_POST['submit']))?"" :"<input type-"hidden" name="submit_stat" value="true" />" ; ?>
and when you process your form when it is submitted check it with your php and make the script act on that variable like this:
<?php
if($_POST['submit_stat']==true) {
//do not process the form here.
//stop your script
}
?>
Another thing you can do is redirect your page to another page other than the page that handles the form. i believe this is the safest one.
Another Way to prevent this is to move the Post Data to Session, redirect, collect Post back from Session and delete Session Post Data.
if(!empty($_POST) && empty($_FILES)){
// move post to session
// redirect to same url (don't forget possible get query)
}else{
// collect post from session
// unset post from session
}
Build this as default and you should never have problems with post data.
Only exceptions are File uploads. In this case redirect *after* post processing manualy.

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>

Submitting a form through a modal box without leaving the page/modal

I am using the project 'ModalBox' from http://okonet.ru/projects/modalbox/index.html in order to generate my modal.
I am also using this overall script that persists e-mails submitted via form into a basic text file as a simple/quick solution. http://www.knowledgesutra.com/forums/topic/25586-php-simple-newsletter-script/
I have a dilemma though.
In order to keep the modal and display my 'mailing_thankyou.php' my form has to have 'onsubmit="return false"' but in order for my php script to work, I have to remove that return false, but then it changes to a new page in order to persist that information.
Does anyone have any ideas?
This is the main part in question:
myModal.html
<div id="signUp">
<form action="mailer/mailing.php" id="myForm" method="post" class="style16">
<input type="text" name="email" size="30" value="your email here!">
<input type="submit" value="Send link" name="submit" onclick="Modalbox.show('mailer/mailing_thankyou.php', {title: 'Form sending status', width: 500, params:Form.serialize('myForm') }); return false;">
or Cancel & close
<!-- ><input type="submit" value="GO!" name="submit"> -->
</form>
</div>
You may pull my files from my git repo:
https://github.com/jwmann/Modal-Sign-up
I'm not good at Mootools, so I will give you an example in jQuery - if you get the idea, I'm pretty sure you will find the right syntax for Mootools too.
The idea is to use AJAX call for form submission (and keep the onsubmit="return false;" so that browser window isn't reloaded):
var $form = $('#myForm');
$.post($form.attr('action'), $form.serialize(), function(response) {
$('div#signUp').html(response);
});
What this does is:
Stores jQuery wrapped form element into $form
Uses form's action attribute value as a request target address
Serializes and transfers all form elements' values
Executes callback function, which takes returned HTML code and replaces contents of <div id='signUp'>...</div> with this HTML.
Note: make sure that the script at forms action only returns html for the contents of the sign up box (meaning no <head>, <body>, etc. - only what should be in the box afterwards)
EDIT/AMENDMENT
This is what I've just found out on MooTools Docs page for Ajax/Request:
The equivalent of my jQuery snippet in MooTools would be
new Request.HTML({ // Creates an AJAX request
'url': $('myForm').get('action'), // Sets request address to the form's action
'update': $('signUp') // Indicates that results should be auto-loaded into element with id='signUp'
}).post($('myForm')); // Indicates that this form has to be serialized and transferred; also starts the request process
This requires that the form's action returns the result to display (a thank you message). One could achieve that by making redirect from the server-side after form data has been successfully processed, e.g. in PHP header('Location: mailer/mailing_thankyou.php'); exit;
After looking longer at your code I realized, that this is not entirely what you want (as I see you don't want the form replaced with the thank-you message - you want it to be shown in the modal). Hence the updated solution for your case:
new Request.HTML({ // Creates an AJAX request
'url': $('myForm').get('action'), // Sets request address to the form's action
'onSuccess': function() { // Defines what to do when request is successful (similarly you should take care of error cases with onFailure declaration
Modalbox.show('mailer/mailing_thankyou.php', {
title: 'Form sending status',
width: 500
// I have removed params from here, because they are handled in the .post() below
});
}
}).post($('myForm')); // Indicates that this form has to be serialized and transferred; also starts the request process
Pardon me if any of this doesn't work (as I said, I'm more of a jQuery guy - just trying to help here)
Have the form submit to a hidden iframe on the page. Give the iframe a name value and then set a target propery on the form. You can make the iframe 1x1 pixel and set the visibility to hidden (if you hide via display: none it might not work in all browsers.)
See this question for details:
How do you post to an iframe?
I removed the 'return false' from the input submit's 'onsubmit' (duhhh facepalm) because it was trying to serialize it in the first palce with prototype.js
Then I changed the php script so it would grab with $_GET instead of $_POST
no added functionality or hacks needed. Thank you for all the help though.

Categories