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-
Related
I have a form with a small number (up to 10) of inputs. One of those inputs is a file upload input. The form layout is as follows:
<form method="post" ...>
<input type="hidden" name="input_no_1" value="value_no_1">
<input type="file" name="input_no_2">
<input type="hidden" name="input_no_3" value="value_no_3">
<button type="submit">send</button>
99.9% of the time this form works fine and I get all the data on the PHP side. However, every once in a while, the POST data gets truncated, and the $_POST variable contains only this:
input_no_1 => value_no_1
The file input and every other input that follows the file input are missing.
This error happens almost exclusively with user agents that contain "Mobile Safari". I suspect that mobile phone users could be using a less reliable network connection and as a result, their request gets aborted and PHP doesn't receive the entire uploaded data.
In my application, I need to know whether the data in the $_POST array is complete or not. I was expecting that if the HTTP server doesn't receive the entire request, I wouldn't even see it from the PHP side.
I am using apache/fpm. The upload_max_filesize and post_max_size are both set to 2G and are nowhere near the size of the uploaded files.
The question: what is the best way to handle incomplete POST data in PHP? Is there a way to prevent these requests from reaching my application, and if not, is there a way to know whether the posted data is complete? I prefer not to add any fields at the end of the form just to find out whether the request is complete or not :)
It sounds like this is a case of needing some server side form validation. Assuming the above fields are all required, something like the following might work for you:
if (!isset($_POST['input_no_1'], $_POST['input_no_2'], $_FILES['input_no_2'])) {
die('Form not filled completely');
} else {
//process form
}
I have a central PHP script I use for handling many requests from my page, using XMLHttpRequest() calls from JavaScript, using the GET method. My server PHP is currently 5.6, and yes, I'm avoiding synchronous calls.
It all works well, however there are cases where I'd prefer NOT to have the request remain in browser history, or even be displayed in the URL. So based on the MDN reference on this call, I thought I could simply switch to the POST method, keeping my existing requests (such as "http://myscript.php?cmd=dothis&data=somedata"). then all I'd have to do is add some code to my PHP script, so I could gather the passed data either way...
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if(isset($_GET['cmd'])) $cmd = $_GET['cmd'];
if(isset($_GET['data'])) $data = $_GET['data'];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_POST['cmd'])) $cmd = $_POST['cmd'];
if(isset($_POST['data'])) $data = $_POST['data'];
}
Well obviously i was dead wrong. What I found was...
Neither of the variables shown in this example are seen by the script within the $_POST array, when I switch to the POST method.
Switching from the $_POST array to the $_REQUEST array works fine (eg: "if(isset($_REQUEST['cmd'])) $cmd = $_REQUEST['cmd']);" ), BUT....
Just the act of issuing my XMLHttpRequest() calls with the POST method, results in errors like this in my log:
PHP Deprecated: Automatically populating $HTTP_RAW_POST_DATA is
deprecated and will be removed in a future version. To avoid this
warning set 'always_populate_raw_post_data' to '-1' in php.ini and use
the php://input stream instead. in Unknown on line 0
So obviously This is a dead end. Doing my best to research what is going on here, in the PHP manual reference to POST I read this right on top...
$_POST $HTTP_POST_VARS [deprecated]
So if I'm understanding this right, the reason I can only obtain the POST variables using the $_REQUEST array is because my requests are still formatted as if I were still using GET, which (apparently?) is a deprecated method. Therefore, "coaxing" it to work is just moving the problem to the future.
Incidentally, I can see by calling the phpinfo.php on my server that despite the ERROR I see in my logs, "always_populate_raw_post_data" is indeed already set to "-1". So all the "solutions" I've found recommending I "JUST" make this setting in my PHP.INI file do not help.
And even if it DID "hide" the error, doing so seems irrelevant to me. Am I wrong in saying that even if I simply gather my passed PHP vars from the $_REQUEST array when using the POST method, AND figure out a way to suppressing the "deprecated" warnings in my LOG, the whole scheme would still fall apart (and make my POST requests fail), the day I finally migrate to PHP 7.x.?
I apologize for asking here, but I have really tried to search every reference I could find for both doing XMLHttpRequests using POST method, AND the deprecated error messages I get in my logs. There is so much obsolete info out there, I can't find any clear discussion on how to PROPERLY alter or re-format my XMLHttpRequests so that I can use the POST method. In fact, I can't even positively determine whether doing so will be possible beyond PHP.5.6. Any help will be very much appreciated.
PHP made a mistake of naming $_GET and $_POST after the default place that a web browser will put data in an HTML form where the method attribute is set to GET or POST.
$_GET gets data from the query string, even if the request method was POST.
The request body is determined by the argument you pass to send. Data you put in the query string remains in the query string.
const url = 'http://myscript.php'
const form_data = new FormData();
form_data.append("cmd", "dothis");
form_data.append("data", "somedata");
cost xhr = new XMLHttpRequest;
xhr.open("POST", url);
xhr.addEventListener('load', function () { console.log(this.response); });
xhr.send(form_data);
Introduction
I've read the following:
Hypertext Transfer Protocol (HTTP) is the life of the web. It's used every time you transfer a document, or make an AJAX request. But HTTP is surprisingly a relative unknown among some web developers.
The HTTP verbs comprise a major portion of our “uniform interface” constraint and provide us the action counterpart to the noun-based resource. The primary or most-commonly-used HTTP verbs (or methods, as they are properly called) are POST, GET, PUT, and DELETE.
Huh?
Well, we came to the point I lost track of things.
PUT and DELETE, they say. I've only ever heard of POST and GET and never saw something like $_PUT or $_DELETE passing by in any PHP code I've ever viewed.
My question
What are these methods (PUT) and (DELETE) for and if it's possible to use them in PHP, how would I go about this.
Note: I know this is not really a problem but I always grab a learning opportunity if I see one and would very much like to learn to use these methods in PHP if this is possible.
What are these methods (PUT) and (DELETE) for...
There are a lot of words to spend to explain this, and I'm not skilled enough to do it, but as already posted, a quick recap of what the HTTP specification describes.
The protocol basically says this:
use GET when you need to access a resource and retrieve data, and you don't have to modify or alter the state of this data.
use POST when you need to send some data to the server. Ex. from a form to save these data somewhere.
use HEAD when you need to access a resource and retrieve just the Headers from the response, without any resource data.
use PUT when you need to replace the state of some data already existing on that system.
use DELETE when you need to delete a resource (relative to the URI you've sent) on that system.
use OPTIONS when you need to get the communication options from a resource, so for checking allowed methods for that resource. Ex. we use it for CORS request and permissions rules.
You can read about the remaining two methods on that document, sorry I've never used it.
Basically a protocol is a set of rules you should use from your application to adhere to it.
... and if it's possible to
use them in PHP, how would I go about this.
From your php application you can retrieve which method was used by looking into the super global array $_SERVER and check the value of the field REQUEST_METHOD.
So from your php application you're now able to recognize if this is a DELETE or a PUT request, ex. $_SERVER['REQUEST_METHOD'] === 'DELETE' or $_SERVER['REQUEST_METHOD'] === 'PUT'.
* Please be also aware that some applications dealing with browsers that don't support PUT or DELETE methods use the following trick, a hidden field from the html form with the verb specified in its value attribute, ex.:
<input name="_method" type="hidden" value="delete" />
Follow an example with a small description on a possible way to handle those 2 http requests
When you (your browser, your client) request a resource to an HTTP server you must use one of the method that the protocol (HTTP) accepts. So your request needs to pass:
A METHOD
An Uri of the resource
Request Headers, like User-Agent, Host, Content-Length, etc
(Optional body of the request)
Now, while you would be able to get data from POST and GET requests with the respective globals ($_GET, $_POST), in case of PUT and DELETE requests PHP doesn't provide these fast access globals; But you can use the value of $_SERVER['REQUEST_METHOD'] to check the method in the request and handle your logic consequently.
So a PUT request would look like:
PUT /something/index.php
(body) maybe=aparameter
and you can access those data in PHP by reading the php://input stream, ex. with something like:
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
$myEntireBody = file_get_contents('php://input'); //Be aware that the stream can only be read once
}
and a DELETE request would look like:
DELETE /something/index.php?maybe=aparameter
and again you can build your logic after have checked the method:
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
// do something
}
Please pay attention that a DELETE request has no Body and pay very attention to Response Status Code too (ex. if you received a PUT request and you've updated that resource without error you should return a 204 status -No content-).
Way to use PUT data from PHP:
$method = $_SERVER['REQUEST_METHOD'];
if ('PUT' === $method) {
parse_str(file_get_contents('php://input'), $_PUT);
var_dump($_PUT); //$_PUT contains put fields
}
PHP's $_GET and $_POST are poorly named. $_GET is used to access the values of query string parameters, and $_POST lets you access the request body.
Using query string parameters is not limited to GET requests, and other kinds of requests than just POST can come with a request body.
If you want to find out the verb used to request the page, use $_SERVER['REQUEST_METHOD'].
Most suitable place to use these (PUT and DELETE) methods is REST API. Where we use http methods to define the mode of operation for example you want to fetch any resources then you can use following:
GET http://api.example.com/employee/<any_id>
to add a new item:
POST http://api.example.com/employee/
to Update or Edit:
PUT http://api.example.com/employee/
to Delete an existing resource:
DELETE http://api.example.com/employee/1
etc.
Now on PHP side you just need to read what HTTP method used so that you can make an action according to that.
There are lots of libraries available which can do that for you.
What are these methods (PUT) and (DELETE)
There are described in the HTTP spec.
In a nutshell, and simplifying somewhat, PUT is for uploading a file to a URL and DELETE is for deleting a file from a URL.
never sawy something like $_PUT or $_DELETE passing by in any PHP code I've ever viewed
$_POST and $_GET are terribly named superglobals. $_POST is for data parsed from the request body. $_GET is for data parsed from the URL. There's nothing that strictly ties data in either of those places (especially the URL) to a particular request method.
DELETE requests only care about the URL's path, so there is no data to parse.
PUT requests usually care about the entire request body (not a parsed version of it) which you would access with file_get_contents('php://input');.
for and if it's possible to use them in PHP, how would I go about this.
You'd need to map the URL onto a PHP script (e.g. with URL rewriting), test the request method, work out what URL you were actually dealing with, and then write code to do the appropriate action.
$GLOBALS["_PUT"]=null;
if($_SERVER['REQUEST_METHOD'] == 'PUT') {
$form_data= json_encode(file_get_contents("php://input"));
$key_size=52;
$key=substr($form_data, 1, $key_size);
$acc_params=explode($key,$form_data);
array_shift($acc_params);
array_pop($acc_params);
foreach ($acc_params as $item){
$start_key=' name=\"';
$end_key='\"\r\n\r\n';
$start_key_pos=strpos($item,$start_key)+strlen($start_key);
$end_key_pos=strpos($item,$end_key);
$key=substr($item, $start_key_pos, ($end_key_pos-$start_key_pos));
$end_value='\r\n';
$value=substr($item, $end_key_pos+strlen($end_key), -strlen($end_value));
$_PUT[$key]=$value;
}
$GLOBALS["_PUT"]=$_PUT;
}
if (!function_exists("getParameter")){
function getParameter($parameter)
{
$value=null;
if(($_SERVER['REQUEST_METHOD'] == 'POST')&& (isset($_POST[$parameter]))){
$value=$_POST[$parameter];
}
else if(($_SERVER['REQUEST_METHOD'] == 'PUT')&& (isset($GLOBALS["_PUT"][$parameter])))
{
$value=$GLOBALS["_PUT"][$parameter];
}
else if(($_SERVER['REQUEST_METHOD'] == 'DELETE')&& (isset($_DELETE[$parameter]))){
$value=$_DELETE[$parameter];
}
else if(($_SERVER['REQUEST_METHOD'] == 'PATCH')&& (isset($_PATCH[$parameter]))){
$value=$_PATCH[$parameter];
}
else if(isset($_GET[$parameter])){
$value=$_GET[$parameter];
}
return $value;
}
}
I have already searched an answer here and with google, but I don't found something. Because I'm having trouble ask the right question to find something.
What is the best way for this problem:
My Page: edit_data.php
I have a form (method="post" action="save.php"). On submit I store the data in a MySQL table.
In save.php:
MySQL insert (return the new id of dataset)
if success I call edit_data.php?id=<new_id>
if error I call error.php?msg=<error message>
The problem is that I lose the data on error.
This is what I want:
- go back to edit_data.php
- show the error directly there
- and I want that all fields contains their original data
I cannot take $_GET, because the data are too big.
Does anyone have an easy solution for me?
Thank you
Is there any reason you can't use $_SESSION? That way, all your data will be saved for the duration of the session, or until you delete it.
Make sure that every PHP document contains session_start(); before any headers are output, this also goes for any blank space before your <?php tag.
To put all your $_POST data in a $_SESSION['POST'] you could do something like,
<?php
session_start();
foreach($_POST as $key=>$val) {
$_SESSION['POST'][$key] = $val;
} ?>
Then you can access your previous POST variables by accessing $_SESSION['POST']['KEYNAMEHERE']
PS: $_GET and $_POST are interchangeable here
If $_GET is to big, you can edit your php.ini file.
Please note that PHP setups with the suhosin patch installed will have
a default limit of 512 characters for get parameters. Although bad
practice, most browsers (including IE) supports URLs up to around 2000
characters, while Apache has a default of 8000.
To add support for long parameters with suhosin, add
suhosin.get.max_value_length = in php.ini
http://www.php.net/manual/en/reserved.variables.get.php#101469
Max size of URL parameters in _GET
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'];
}