Do not Access Superglobal $_POST Array Directly.
Use some filtering functions instead (e.g. filter_input(), conditions with is_*() functions, etc.).
----
(Alt-Enter shows hints)
I am getting this kind of warning in my NetBeans IDE when I am sending an AJAX request to my PHP file.
My request type is POST and when I go to PHP page I am getting the warning.
Can this warning harm my code in any way. How do I get rid of this?
Should I just ignore it or it very important to get rid of the warning?
The warning is appearing in the $_POST when I am getting the data that is passed from AJAX.
Example:
$fname = ($_POST['Fname']);
The line $_POST is having the yellow underline.
The warning text you posted gives you the examples - pass your $_POST param through a function like filter_input() or is_*().
try something like:
$fname = filter_input(INPUT_POST, 'Fname', FILTER_SANITIZE_SPECIAL_CHARS);
Reference - http://php.net/manual/en/function.filter-input.php
EDIT:
The list of available filters is linked on the function page.
You do not have to use FILTER_SANITIZE_SPECIAL_CHARS, I just gave it as example.
The point is that Netbeans telling you to validate / sanitize POST data. You can write your own functions for that. Check whether the value is of correct type, length etc.
Related
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);
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'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!
So I am using the following style of code if(array_key_exists('some_value', $_POST)){echo 'hi';}
For PHP 5.2.17 I am getting a warning from this style of code. This is the warning:
WARNING: argument 2 for array_key_exists() is not either an array or an object on line: 123
This seems strange to me because I believe that the $_POST array should always be defined. Is that not the case? I'm not sure what would cause the $_POST array to not be considered an array. I am not resetting $_POST to anything so it should exist as an array at all times. Does anyone have any idea what is wrong. Please let me know if more information is needed and thank you for the help.
Edit: I should note that this only happens on the production server. My local environment does not have this problem.
The Superglobals $_POST and $_GET are only populated if the script is POSTed to or GET from. In your example, the reason that you'd get that error is if there was not post action to the script. Before checking for a certain post value, you should check to make sure there was a post:
if(isset($_POST)) {
//The form was posted
}
In that fashion. From there, you can check for certain values using array_key_exist, or you can further check isset($_POST['myKey']).
Use if(isset($_POST['some_value'])) { echo 'hi'; } instead. Never had a problem with it.
Also check if you are not overriding or unsetting $_POST (or some framework you are using is doing it for you). I avoid to do so with superglobal variables since I think it is a bad practice and might give headaches like this one.
Can the PHP superglobal $_GET be used and work as intended outside of the form tags? For example, can I do $_GET('select box id') outside of the form tags and have it work as intended?
<?php
---Placeholder for DB login info---
switch($_GET['select box id'])
{
case "text shown for second option of select box":
$query = mysql_query("placeholder for actual query");
$row = mysql_fetch_row($query);
$textboxValue = $row[0];
break;
}
?>
Can the PHP superglobal $_GET be used and work as intended outside of the form tags?
Yes. The position of PHP code within HTML is entirely irrelevent except in determining where output will appear in a document.
$_GET['select box id']
Form controls use their names for submission keys, not ids.
mysql_query
Read the big red warning box on the documentation page for that function.
If this is for login info, you should not be using a get request anyway--you should be using post.
But at any rate, yes it should work. As long as the data is sent with the query, it should work.
That said, you may also want to do some research into some basic security aspects, such as validating and sanitizing inputs. Otherwise, you may wind up opening yourself up to some rather nasty attacks.
I would recommend the book Essential PHP Security from O'Reilly Press. I would also look into using something like MySql PDO for making database queries, as it tends to be more reliable and secure than simply using mysql_query.
Superglobal means available for use anywhere/everywhere.