After reading:
When do you use POST and when do you use GET?
Mixing GET with POST - is it a bad practice?
I understand, that GET is used to retrieve a page without changing the server and POST is used for things (insert, update, delete), that change the server.
Now I have written a page which is called with a GET request with parameter StationNr set. The user can fill a form and makes a POST request to the same page with parameter Filter set. But I don't want to miss the parameter StationNr thus I thought I give it into a hidden input field. But then the parameter StationNr is either in the $_GET variable (first call) or in the $_POST variable (second call). I can do something like:
if (isset($_GET['StationNr']))
$snr = $_GET['StationNr'];
else if (isset($_POST['StationNr']))
$nr = $_POST['StationNr'];
But I don't like this. Also I don't want to use $_REQUEST['StationNr'] because of: When and why should $_REQUEST be used instead of $_GET / $_POST / $_COOKIE?
I think this is a common issue but I haven't faced it yet because I'm a beginner in writing php pages. How did you solve this problem?
Thanks!
Although you can use ?foo=bar to push GET values in a POST request, I'd suggest checking the request method instead:
if($_SERVER['REQUEST_METHOD'] == 'POST') { ... }
just use
<form method="post" action="script.php?get=variables">
<input name="your_inputs" />
</form>
Correct Syntax Would Be:
if (isset($_GET['StationNr'])) {
$snr = $_GET['StationNr'];
}else if (isset($_POST['StationNr']))
$nr = $_POST['StationNr'];
}
Related
I want to know how to use POST request in PHP. I used $_REQUEST['text'] for getting data from url like http://localhost/data.php?text=ABCDEFGH but If i pass very long text than ERROR : Request-URI Too Long.
if(isset($_REQUEST['text'])){
$parsetext=$_REQUEST['text']; //get data here data > ABCDEFGH
}else{
echo "not valid";
}
Please any one tell me how to support long TEXT using POST request. I know that $_REQUEST is for both request GET & POST.
Regarding the error, you can check these links (I assume you've already seen this):
How do I resolve a HTTP 414 “Request URI too long” error?
Request-URI Too Large
And for your question: I want to know how to use POST request in PHP.
Create a form.
(I assume that the textbox from this form will get the long data that you want to POST).
<form method="POST" action="http://localhost/data.php">
<input type="text" name="input_text" />
<button type="submit">Submit</button>
</form>
Receive the data from the from input using the defined method on your form. In this case the method is POST and the url/file that will receive the submitted data is http://localhost/data.php.
if (isset($_POST['input_text'])) {
// Where input_text is the name of your textbox.
$text = $_POST['input_text'];
echo $text;
}
ERROR : Request-URI Too Long.
$_REQUEST, as you say, handles $_POST and $_GET methods is correct.
Regarding your question, even though you use $_REQUEST to get the data, in the background it use the $_GET method to catch the query string you pass with the url.
$_GET method has limit on size and this is the main reason why you encounter that error. Whereas $_POST method don't have limit: Is there a maximum size for content of an HTTP POST?.
Conclusion: Better not use $_REQUEST, use $_GET or $_POST specifically :D
First of all, read this Question/Answer, this will probably clear some things for you on the differences between POST and GET and what method you should use for your project.
Then, you should forget about the $_REQUEST and use either $_GET or $_POST. This will prevent some security issues that you'll probably run into if you keep using $_REQUEST. More on that in the PHP Manual
Next up, you should definitely switch to POST, instead of GET if you're passing large sets of data. Otherwise you have to modify your apache config and that is not recommended if you plan on releasing you code to the public.
-EDIT START-
You can even use POST within AJAX, if everything is on the same server.
-EDIT END-
I am writing code for a simple WAMP server. It would receive a query string from another machine and simply display the parameters after parsing.
How would the server know that a query string has been received? And when received, how would it perform desired action on the query string?
Edit: The parameters are being passed as URL.
You're looking for the superglobal variable $_GET.
For example, at the URL http://example.com/foo.php?bar=BAM, the variable $_GET['bar'] has the value BAM.
You can check whether there are any query string variables by seeing if count($_GET) > 0.
To check whether a parameter is set, you can do something like this:
if (isset($_GET['bar'])) {
// do something cool
} else {
echo "Hey, you didn't give me a value for bar!";
}
Edit: If you are passing it in some other way, not in the URL, then please clarify your question. How you access the data will obviously depend on how you receive it.
Lets say you have two URLs:
www.example.com
www.example.com?param=Jonas
Now in first url you have no parameters, while second has parameter param that value is Jonas.
In PHP parameters usually are passed via POST or GET requests. They are stored to $_POST or $_GET (depending on request type). So to get something form GET request (every parameter in URL) you use:
if (!empty($_GET['param'])) {
echo $_GET['param']; // will echo 'Jonas'
}
I'm stuck with a php/mySQL thing..
I have a dynamically created form and I want to parse the $_POST variables it generates. To be specific,I have a query in SQL which generates the fields in my form. Then, I need to process these variables in the php file, where the action of the form goes.
However, I cannot parse the dynamically created $_POST variables. Below is my code:
$sql="just-a-query";
$result = mysql_query($sql);
while ($data = mysql_fetch_array($result)) {
${''.$data['parameterName']}=$_POST[$data['parameterName']];
}
For example, if I have 3 variables that got through the form the values:
house=1
tree=3
car=2
I would like to save them via php like this:
$house=$_POST['house'];
$tree=$_POST['tree'];
$car=$_POST['car'];
However I can't get through it. It returns Undefined index error. Any thoughts?
If you want to find if a variable is defined before using it, it's as simple as using isset():
if( isset($_POST[$data['parameterName']]) ) {
${''.$data['parameterName']}=$_POST[$data['parameterName']];
}
If on the other hand, it's supposed to be defined (you see the form element), but then it's not getting defined in the postback. First check to make sure that your form submission type is post, then check to make sure you are using the name attribute in the form elements.
thank you for your time. My problem was that I was parsing wrong parameters from the HTML.
Yes, I'm an idiot and yes, var_dump() helped me to figure my error.
Thanks again!
btw, my code was working perfectly. Ha!
I have set up the following:
Database class ($db)
Pagination class ($paginator)
I am attempting to write a basic system to let me administrate pages. I have a page "page_manager.php" in which I include both my database class (database.php) and my pagination class (paginate.php).
In my pagination class I have a function which echoes my SQL data. I've come up with a way to echo an HTML < select > element with the necessary IDs, which allows me to successfully echo the corresponding results (10 per page), based on the value of the < select > element. So, "1" will echo the first 10 results in the database, "2" will echo from 11-20, "3" will echo from 21-30, etc., etc..
I have added an onChange event to the < select > element which will copy its value (using "this.value") to a hidden form field. I then submit this form using document.getElementById().submit();
This will then add the $_GET variable to the URL, so the URL becomes ".../?pagenumber_form=X". However, when I try to grab this value back from the URL, the $_GET['pagenumber_form'] is empty.
Some code:
<span style='font-family: tahoma; font-size: 10pt;'>Page #</span>
<select id="page_number_selection"
onchange='javascript: document.getElementById("pagenumber_form").value = this.value;
document.getElementById("pagenumber").submit();'>
<?php
for($i = 1; $i <= $this->num_pages; $i++)
echo"<option id='" . $i . "'>" . $i . "</option>";
?>
</select>
<form name="pagenumber" id="pagenumber" action="" method="get">
<input type="text" name="pagenumber_form" id="pagenumber_form" />
</form>
So, I've tried using $_POST as well, but the same thing happens. I want to use $_GET, for a couple of reasons: it's easier to see what is happening with my values and the data I'm using doesn't need to be secure.
To recap: the $_GET variable is being added to the URL when I change the < select > element, and the corresponding value gets added to the URL as: ".../?pagenumber_form=X", but when I try to use the value in PHP, for example...
$page_number = $_GET['pagenumber_form'];
... I get a NULL value. :-(
Can anybody help me out please? Thank you.
EDIT:
I've just made a discovery. If I move my print_r($_GET) to my main index page, then the superglobals are returning as expected. My site structure is like this:
index.php
- JavaScript buttons use AJAX HTTP requests to include the "responseText" as the .innerHTML of my main < div >. The "responseText" is the contents of the page itself, in this case page_manager.php, which in turn includes pagination.php.
So in other words, my site is built from PHP includes, which doesn't seem to be compatible with HTTP superglobals.
Any idea how I can get around this problem? Thank you :-).
+------------------------------------------------------------------+
I can't answer my own posts, so:
The problem is not solved, but has been worked around.
I am certainly not very knowledgeable when it comes to PHP, but I am of the impression that using AJAX requests to include a PHP file in a document, which itself includes other PHP files, is not a good idea. The problem, I believe, was being caused because PHP is executed before the document is loaded in to the browser. Therefore, dynamically including a PHP file in a document will result in the improper working of said file due to the fact that PHP must be executed by the server before the page is rendered, and not after.
As such, I have stopped using AJAX for my site and am simply using good old PHP instead. I don't know enough to carry on using the AJAX requests, so that's an end to that problem.
Thanks to those who replied.
You need to re-pass the superglobals to the AJAX calls. So where you would make a request to pagination.php you need to make it to pagination.php?pagenumber_form=<?php echo $_GET['pagenumber_form']; ?>.
the corresponding value gets added to the URL as: ".../pagenumber_form=X
You might wanna try
.../?pagenumber_form=X
Included files can access superglobals just fine (which is what makes them super). What can't be done is to access variables from one request in another. It isn't that clear what your code is doing (since the question doesn't include a proper minimal test case–a complete, concise, representative sample), but it sounds like loading a single page involves multiple requests, and only the first of these is given the form data. Each AJAX request involves a separate HTTP request, and (because HTTP is supposed to be stateless) has different request data, so any request that isn't explicitly given the data won't have access to it. After a request is handled, all data the script has access to is discarded. This is why if you need data to exist across requests, you need some form of persistence, such as sessions (which you should be careful of, in order not to break the HTTP stateless model) or databases.
Some of the difficulty may lie in a confusion over exactly what happens server-side, what happens client-side, what happens between the two and in what order it all happens. Before you go further, read up on HTTP (a web search should reveal countless documents on the topic). You can use debuggers (e.g. Firebug, XDebug+a client, Wireshark, Live HTTP Headers) to peer at what's happening as it happens.
I am trying to use an if statement to check if the user has been directed to this page with from the correct location with correct data.
in php we would use
if ($_REQUEST)
{
......
}
but how can I do it in coldfusion?
According to this, $_REQUEST is:
An associative array that by default contains the contents of $_GET,
$_POST and $_COOKIE.
In which case, there is not an equivalent in Coldfusion. The $_GET would be equivalent to CF's URL scope. The $_POST would be equivalent to CF's FORM scope. The $_COOKIE would be equivalent with CF's COOKIE scope. You would need to check the appropriate scope depending on what you are looking for.
There are, however, frameworks for Coldfusion, such as Coldbox, that manage a "Request Collection" for you.
With more information this answer could be more complete.
You can check where the user came from using CGI.HTTP_REFERER. Example:
if (CGI.http_referer contains 'www.good-domain.com') { ... do something here ... }
You'll need to check the URL or FORM scopes to inspect the data to see if it is the "right data". You can inspect these values with something simple like this (which checks the form scope--used when data is posted in the body of a request):
requestIsGood = true;
requiredKeys = ['keyA','keyB','keyC'];
for (key in requiredKeys) {
if (!structKeyExists(FORM,key) {
requestIsGood = false;
break;
}
}
if (requestIsGood) { ... do something here ...}
Lastly, the difference between the URL and FORM scope in ColdFusion (CFML) is that values in the url's querystring will be populated to the URL scope. Values posted by the form will exist in the FORM scope.
The code examples should be accurate for Adobe ColdFusion 9+ http://adobe.com/go/coldfusion and the open source CFML engine Railo http://getrailo.org. It may work on another open source CFML engine OpenBD http://www.openbluedragon.org/ but I am not sure.
Hope this information helps you.