<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return checkValid(this)" method="GET">
<input type="text" name="Symbol">
<input type="submit" name="submit" value="Search">
</form>
<?php
if($_SERVER["REQUEST_METHOD"] == "GET"){
echo "test";
$CSymbol = $_GET["Symbol"];}
?>
when the page was first load and did not press submit button, the php was executed and "test" was print on the screen, also with error:
Notice: Undefined index: Symbol in test.php on line 179
but if i change everything to POST, problem solved. Why is that, what's different btn GET and POST?
GET values are sent in the URL, POST in the HTTP Body. So "GETting" values can alsways be done but may be empty. POST has to be manually created. If you want to use GET in this case however. Guard it:
<?php
if($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET["Symbol"]){
echo "test";
$CSymbol = $_GET["Symbol"];}
?>
Reference Link
GET and POST are two different types of HTTP requests.
According to WikiPedia:
GET requests a representation of the specified resource. Note that GET should
not be used for operations that cause side-effects, such as using it for taking
actions in web applications. One reason for this is that GET may be used
arbitrarily by robots or crawlers, which should not need to consider the side
effects that a request should cause.
and
POST submits data to be processed (e.g., from an HTML form) to the identified
resource. The data is included in the body of the request. This may result in
the creation of a new resource or the updates of existing resources or both.
So essentially GET is used to retrieve remote data, and POST is used to insert/update remote data.
Authors of services which use the HTTP protocol SHOULD NOT use GET based forms
for the submission of sensitive data, because this will cause this data to be
encoded in the Request-URI. Many existing servers, proxies, and user agents will
log the request URI in some place where it might be visible to third parties.
Servers can use POST-based form submission instead
Finally, an important consideration when using GET for AJAX requests is that some browsers - IE in particular - will cache the results of a GET request. So if you, for example, poll using the same GET request you will always get back the same results, even if the data you are querying is being updated server-side. One way to alleviate this problem is to make the URL unique for each request by appending a timestamp.
For your above code..
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return checkValid(this)" method="GET">
<input type="text" name="Symbol">
<input type="submit" name="submit" value="Search">
</form>
<?php
if($_SERVER["REQUEST_METHOD"] == "GET" && !empty($_GET['Symbol'])){
echo "test";
$CSymbol = $_GET["Symbol"];}
?>
Every http request that is not a POST counts as a GET request, and so every page that loads up has an empty GET request, php will create a super global $_GET array with every non post request.
Hope this helps you understand what is going on.
Related
loaded page from javascript. tested for GET & POST. Only GET set as expected;
window.location.href = "medications_edit_revised.html?recordId="+id ;
Retrieved and used the data from the GET[]
Reloaded page from SUBMIT as shown below.
<form method="post" action="">
<table id="detailsDivTable">
<?php
$editClass->selectTheRecord();
?>
</table>
<fieldset name="Group1">
<legend>Group box</legend>
<input name="saveButton" type="submit" value="Save" />
<input name="deleteButton" type="submit" value="Delete" />
<input name="cancelButton" type="submit" value="Cancel" />
</fieldset>
</form>`
Tested GET[] & SET[]
if (isset($_GET['recordId']) ) {
$recordId = $_GET['recordId'];
require_once "medications_edit_revised.class.php";
$editClass = new editRevisedClass($DBH, $recordId);
}
if(isset($_POST['saveButton'])) {
Both tested TRUE. Is this normal behavior. I expected the GET[] would have been cleared when the form was POSTed
If yes is there a way to clear the GET before sending the SUBMIT
Thanks
When you set the URL like this:
window.location.href = "medications_edit_revised.html?recordId="+id ;
You have set URL params. Then when you do this:
Reloaded page from SUBMIT as shown below.
<form method="post" action="">
Because the action is empty it'll retain the URL parameters, because that's what empty and (eg) $_SERVER['PHP_SELF'] do - they send to the current URL, params and all.
You already know the URL so just set it as needed:
action="medications_edit_revised.html"
You seem to be confusing POST/GET requests and the PHP $_POST and $_GET superglobal variables.
PHP will populate $_GET with data in the query string of the URL the request was made to.
PHP will populate $_POST with data in the request body of a POST request if that data is encoded using a supported encoding.
It doesn't matter if the request was caused by JavaScript, a form submission, or something else.
Is this normal behavior.
Yes
If yes is there a way to clear the GET before sending the SUBMIT
Submit the form to a URL which does not have a query string.
The URL the form is submitted to will be specified by the action attribute.
If you don't have an action attribute, it will be submitted to the URL of the current page. If that URL has a query string, then so will be the URL that the form is submitted to (and thus $_GET will be populated).
If you want to avoid that, then specify the action explicitly.
Can you please past some of your code?
If you use GET to revice your variable, it gets it from the URL: example.com?name=jesper&lastname=kaae
The differences is:
GET requests a representation of the specified resource. Note that GET should not be used for operations that cause side-effects, such as using it for taking actions in web applications. One reason for this is that GET may be used arbitrarily by robots or crawlers, which should not need to consider the side effects that a request should cause.
And
POST submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both.
You can read more about them here
I've got the following HTML
<form action="/home" method="post">
<input type="hidden" name="_method" value="POST">
<input type="text" name="var">
<button type="submit">Submit</button>
</form>
on the server side, I trigger different actions based on the type of request I get. The _method hidden field governs that action. Can users not simply change the value to, say DELETE and cause mayhem? I tried it on my local Apache server, and it does in fact trigger the delete route, which could potentially be disastrous.
I also know that I'm not the only one using this practice, as I've seen it on official documentations for various frameworks, so what am I missing?
You can check the method name on the server side with:
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
// collect value of input field
}
else{
// Do nothing
}
?>
Note: Change "GET" as you see fit.
Note2: $_SERVER["REQUEST_METHOD"] is generated by the server. User can not edit it. So, you can check with this variable what kind of request you have (GET, POST, PUT,...).
Hope it helps you!
I understand that I am able to use the POST method for URL parameters to display data according to a specific variable, I know how to make use of the GET method - but I am told that the POST method can be used to hide the part of the URL that is like this.
/data.php?parameter=1234
What is the actual difference of the two methods in terms of URL parameters?
Below is some code that fetches data from a database according to the id of a specific link
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//This is the actual interaction with the database, according to the id.
$query = mysql_query("SELECT * FROM table WHERE id=" .$_GET['id'] . ";") or die("An error has occurred");
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Here each cell in the database is fetched and assigned a variable.
while($row = mysql_fetch_array($query))
{
$id = $row['id'];
$title = $row['title'];
$month = $row['month'];
$day = $row['day'];
$photo = $row['photo'];
$text = $row['text'];
}
?>
On a separate page I generate links to the data.php file according to the ID like so:
<?php echo $content['title']; ?>
Forgetting that there are potential SQL injections that can occur through the above code, how would I go about making use of the POST method in order to hide the URL parameters, or at least not display them like this:
http://example.com/data.php?id=1
In order to use POST, you will need to use a <form> tag, and depending on how you are pulling up these URLs, it could be easier to use javascript to help out. Here's a basic example:
<form method="post" action="data.php">
<input type="hidden" name="parameter" value="1234" />
<input type="submit" value="Go" />
</form>
The Go button would POST the form data, and now in data.php you will be able to retrieve the value from $_POST['parameter']. Note that when using POST, you will probably want to redirect (HTTP 302) back to a page so that when a user hits the back button, the browser doesn't prompt to resubmit the form.
Using javascript, you could set the parameter input to a different value before posting the form.
Use method "POST" for your form. I had the same issue, just adding POST to the form removed the parameters from the URL
<form id="abc" name="abc" action="someaction.php" method="post">
<input type="text" id="username" name="username"/>
<input type="password" id="password" name="password"/>
<input type="submit" id="submit" name="submit" value="submit"/>
</form>
To POST values, a browser would have to use a form with method="post", or javascript simulating a form. Various developer tools (fireug, etc) can convert GET forms to POST forms, but generally, a form is what is required.
In theory GET requests should not have any side effects, and "should" be consistent from request to request. That is, the server should return the same content. In todays world of just about everything being dynamic, this might be of little practical design significance.
Whether you use GET or POST, the parameters will appear in $_REQUEST. The critical difference is that using POST allows the variables NOT to appear in URL history. This decreases the visibility of data such as passwords which you do not want to show up in URL history. To use POST instead of GET, simply produce <form method="POST" ...> in the document.
Even better is to store sensitive values (like user ids) in cookies, so that they don't appear in $_REQUEST at all. Since the contents of cookies are provided in extra HTTP request headers, not in the content, they are generally not stored as part of the history.
In order to use POST instead of GET, you would need to use an HTML form tag in your html, like so:
<form method="POST" action="/data.php">
<input type="hidden" name="parameter" value="1234" />
<button type="submit">Submit</button>
</form>
When submitted, your URL will just be /data.php and parameter=1234 will be in your (hidden) post buffer.
Make sense?
To do a POST, you have to use a form, or some javascript/ajax trickery. An <a> will only ever cause a GET request.
Note that POST requests can still have query parameters in the URL. It's not "normal" to have them, but they are allowed. The main difference being that with a GET request (ignoring cookies), the URL is the ONLY way to send parameters/data to the server. With POST, you can use both the URL, and the body of the POST request, which is where POSTed form data is normally placed.
The user enters a number and clicks submit. The number now shows up on the page.
The user is then asked if they would like to double the number. They click yes.
The doubled number now appears on the page.
I am having trouble with part 3. Is this possible using just PHP?
UPDATE: Thanks for your answers. This is my first ever PHP script, so I wasn't sure. I am going to research doing it with AJAX just now. I'm very curious to know why it is possible to get to part 2 if you can't get to part 3. Can anyone explain this or provide a link?
<?php
$double = (isset($_REQUEST['do_double']) && $_REQUEST['do_double'] == '1') ? ($_REQUEST['number'] * 2) : '';
?>
<form method="get" action="?">
<input type="hidden" name="do_double" value="<?php echo isset($_REQUEST['number']) ?'1' : '0'; ?>" />
<input type="text" name="number" value="<?php echo isset($_REQUEST['number']) ? $_REQUEST['number'] : '';?>" />
<?php if ( ! isset($_REQUEST['number'])) { ?>
<input type="submit" value="submit" />
<?php } else { ?>
<input type="submit" value="Verdoppeln" />
<?php } ?>
</form>
<div id="number"><?php echo $double; ?></div>
I think you're talking about session variables. At the top of the script add the following script to start a session for the current user:
session_start();
This will allow you to store variables in session $_SESSION which persists between requests. Use isset to check if a value is set in session.
Take the form ID using something like document.formname.inputname (http://www.quirksmode.org/js/forms.html) and then multiple by two then use javascript to show it where ever you want.
Asynchronous is required I think. Try these 2 reads:
the difference between synchronous and async: http://javascript.about.com/od/ajax/a/ajaxasyn.htm and
possible examples: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
This is really more of a comment than an answer, but SO limits comment length so here 'tis:
The misconception that a web page is synonymous with a PHP script appears to be common among novice PHP programmers. Really, a web page is an HTML document (with associated resources) that is sent from a web server to a web browser as part of an HTTP response. A single server-side script can generate many different kinds of web pages, and when processing HTML forms (as you seem to be doing) it is common for a single server-side script to do exactly that. In "web 1.0" applications, clicking on "Submit" (for example) typically causes the browser to make a new HTTP request (called a "page turn"), and the web server keeps track of what the user is doing across page turns by storing "state" either in a "session" (with an associated key included in the HTTP header of each HTTP request - and the HTTP response generated by the web "login") or in one or more HTTP parameters. The point is that each new HTTP request may be for the same script/URL on the server, but the behavior (and the appearance of the web page) will be different because the server is somehow tracking the state of the "workflow" across page turns.
Now if you really must avoid page turns, you can use Javascript to change the appearance/state of the page displayed by the browser without making the user click on a "Submit" button. And the XMLHTTPRequest mechanism (aka AJAX), which allows content to be fetched from the web server "behind the scenes" and change the state of the client-side document without the user doing anything, is typically used to achieve this. But is only really necessary if you're doing something rather different (e.g. scrolling a map or updating a stock ticker) than what you describe in your question, which looks like a perfect example of a "web 1.0" application workflow.
I have a webpage. This webpage redirects the user to another webpage, more or less the following way:
<form method="post" action="anotherpage.php" id="myform">
<?php foreach($_GET as $key => $value){
echo "<input type='hidden' name='{$key}' value='{$value}' />";
} ?>
</form>
<script>
document.getElementById('myform').submit();
</script>
Well, you see, what I do is transferring the GET params into POST params. Do not tell me it is bad, I know that myself, and it is not exactly what I really do, what is important is that I collect data from an array and try submitting it to another page via POST. But if the user has JavaScript turned off, it won't work. What I need to know: Is there a way to transfer POST parameters by means of PHP so the redirection can be done the PHP way (header('Location: anotherpage.php');), too?
It is very important for me to pass the params via POST. I cannot use the $_SESSION variable because the webpage is on another domain, thus, the $_SESSION variables differ.
Anyway, I simply need a way to transfer POST variables with PHP ^^
Thanks in advance!
You CAN header redirect a POST request, and include the POST information. However, you need to explicitly return HTTP status code 307. Browsers treat 302 as a redirect with for GET, ignoring the original method. This is noted explicitly in the HTTP documentation:
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.8
Practically, this means in PHP you need to set the status code before the redirect location:
header('HTTP/1.1 307 Temporary Redirect');
header('Location: anotherpage.php');
However, note that according to the HTTP specification, the user agent MUST ask user if they are ok resubmitting the POST information to the new URL. In practical terms, Chrome doesn't ask, and neither does Safari, but Firefox will present the user with a popup box confirming the redirection. Depending on your operating constraints, maybe this is ok, although in a general usage case it certainly has the potential to cause confusion for end users.
No possibility to do this directly from server, as POST data should be sent by the browser.
But you can choose an alternative:
The prefilled form automatically submitted in your example could work, but as you wrote it's not really good practice and can leave users on a blank page
Receive GET arguments and POST them with curl (or any decent HTTP client) to the second site, then transfer the result to the browser. This is called a proxy and may be a good solution IMHO.
Do session sharing across domain, this can not be possible on all setups and can be complex.
Once setup is done, session sharing is almost transparent to PHP code. If you have more than one need for communication between the 2 domains it can be worth doing this.
Example with curl solution, code to run on domain 1:
//retrieve GET parameters as a string like arg1=0&arg1=56&argn=zz
$data = $_SERVER['QUERY_STRING'];
// Create a curl handle to domain 2
$ch = curl_init('http://www.domain2.com/target_script.php');
//configure a POST request with some options
curl_setopt($ch, CURLOPT_POST, true);
//put data to send
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//this option avoid retrieving HTTP response headers in answer
curl_setopt($ch, CURLOPT_HEADER, 0);
//we want to get result as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//if servers support is and you want result faster, allow compressed response
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
//execute request
$result = curl_exec($ch);
//show response form domain 2 to client if needed
echo $result;
That's it, your client's browser won't even see domain 2 server, it will get only result from it. know if you want to redirect client to domain, do it with classic HTTP header.
header('Location: http://www.domain2.com');
Of course, this is demo code with hardcoded values, and there are 2 point left to you:
Security: query string should be filtered or recreated to transmit only needed parameters, and you should assert the server on domain 2 returned a 200 HTTP code.
Application logic should need a little adjustment on this part: if domain 2 app expects to get post data in the same request as visitor is coming it won't do it. From domain 2 point of view, the client doing POST request will be server hosting domain 1 not the client browser, it's important if client IP matters or other client checks are done on domain 2.
If the POST request serves to display client specific content you also had to do some server-side tracking to combine previously posted data with the visitor being redirected.
You could hack something together like the following... (I'm not saying you should however!):
$res = "<form action='/path/to/new/page' method='POST' id='redirectHack'>
<input type='hidden' id='postVar1' name='postVar1' value='12345'>
<input type='hidden' id='postVar2' name='postVar2' value='67890'>
</form>
<script>
document.getElementById('redirectHack').submit()
</script>";
die($res);
Store your data in a session and then use GET.
No. You can't do header redirect with POST. You have 2 options,
You can use GET instead if the destination accepts either POST or GET.
We add a button in rare cases that the Javascript is turned off.
Here is an example,
<noscript>
<div>
<input type="submit" value="Continue"/>
</div>
</noscript>
This will show a continue button if Javascript is off so user can click to continue.
It is possible. In this situation I would use cURL:
$url = 'http://domain.com/get-post.php';
foreach($_GET as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
As a sample of what #Charles indicates, here is a working php PayPal buy form that:
Checks the input with javascript. If OK, it submits it, else displays an alert.
Checks the input with php. If OK, it creates the redirect headers and gets rid of the body HTML, else it shows the same form again.
Note that:
Inputs should be rechecked on the server, as a browser's inputs can be nefariously manipulated.
No HTML can be output before the header commands, as they will be ignored with a php warning.
Javascript can only check the inputs for valid values, but without AJAX, will not be able to check the server for whatever the user wants before submission. Therefore, this method is the complete non-javascript process.
No HTML is needed if the redirect target (like PayPal) is only processing the POST data. Targets for humans do, of course!
Unfortunately, 4 means that you cannot send just a subset or even a complete other set of values to the new url, AND have the target page processing the POST data open in the user's browser. You cannot do this by manipulating the $_POST array (it seems to be just a PHP copy of the actual data). Perhaps someone knows how to modify the real POST data set?
From 5, there is no opportunity to gather private information on the
original form, and just send only the payment information on the
form to PayPal or whomever, via the user's browser for their explicit payment approval. That means AJAX is needed to do that by
using two forms, one holding the private info with no button, and
the other form with the PayPal buy button that uses AJAX to submit
the other form, and depending upon the result, submit its own form.
You could use fields that PayPal doesn't use, but they are still
getting the info, and we don't know what they have trawling over
submitted form data.
Rather than using AJAX as in 6, it would be a lot simpler to have 3 versions of the form:
Initial to capture the private data.
If problem, re-show form with submitted data and indication of incorrect data or backend problem.
If OK, a PayPal form, submitted automatically by javascript at
the bottom of the page (form.submit()), or a request to submit manually by a button if no javascript.
<?php
// GET POST VARIABLES, ELSE SET DEFAULTS
$sAction=(isset($_POST['action'])?$_POST['action']:'');
$nAmount=(int)(isset($_POST['action'])?$_POST['amount']:0);
// TEST IF AMOUNT OK
$bOK=($nAmount>=10);
/*
TYPICAL CHECKS:
1. Fields have valid values, as a backup to the javascript.
2. Backend can fulfil the request.
Such as whether the requested stock item or appointment is still available,
and reserve it for 10-15 minutes while the payment goes through.
If all OK, you want the new URL page, such as PayPal to open immediately.
*/
// IF OK
if($bOK){
// CHANGE HEADER TO NEW URL
$sURL='https://www.paypal.com/cgi-bin/webscr';
header('HTTP/1.1 307 Temporary Redirect');
header('Location: '.$sURL);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Sample post redirection</title>
</head>
<body>
<?php
// IF NO ACTION OR NOT OK
if(($sAction=='')||!$bOK){
?>
<h1>Sample post redirection</h1>
<p>Throw money at me:</p>
<form name="pp" action="<?=$_SERVER['REQUEST_URI']?>" method="post" onsubmit="check_form(this)">
<!-- <input type="hidden" name="amount" value="<?=$nAmount?>" /> -->
<input type="hidden" name="business" value="paypal.email#yourdomain.com" />
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="lc" value="AU" />
<input type="hidden" name="item_name" value="Name of service" />
<input type="hidden" name="item_number" value="service_id" />
<input type="hidden" name="currency_code" value="AUD" />
<input type="hidden" name="button_subtype" value="services" />
<input type="hidden" name="no_note" value="0" />
<input type="hidden" name="shipping" value="0.00" />
<input type="hidden" name="on0" value="Private" />
<input type="hidden" name="os0" value="Xxxx xxxxx xxxxx" />
<p>Amount $<input id="amount" type="text" name="amount" value="<?=$nAmount?>" /> $10 or more.</p>
<p><button type="submit" name="action" value="buy">Buy</button></p>
</form>
<p>If all is OK, you will be redirected to the PayPal payment page.<br />
If your browser requires confirmation, click the <cite>OK</cite> button.</p>
<script>
// JS AT END OF PAGE TO PREVENT HTML RENDER BLOCKING
// JS FUNCTION FOR LOCAL CHECKING OF FIELD VALUES
function check_form(oForm){
// USE TO DETERMINE IF VALUES CORRECT
var oAmount=document.getElementById('amount');
var nAmount=oAmount.value;
var bOK=true;
var bOK=(nAmount>=10); // EXAMINE VALUES
// IF NOT OK
if(!bOK){
// INDICATE WHAT'S WRONG, ALERT ETC
alert('Stingy #$#&. Pay more!!');
// BLOCK FORM SUBMIT ON ALL BROWSERS
event.preventDefault();
event.stopPropagation();
return false;
}
}
</script>
<?php
}
?>
</body>
</html>
In a POST Redirect GET situation, ( see https://en.wikipedia.org/wiki/Post/Redirect/Get ) it is acceptable to use the session variable as the method of transporting the data.
<?php
session_start();
// return is the name of a checkbox in the post-redirect-get.php script.
if(isset($_POST['return'])) {
// We add some data based on some sort of computation and
// return it to the calling script
$_SESSION['action']="This string represents data in this example!";
header('location: post-redirect-get.php');
}