isset($_POST) is correct usage or not? - php

The problem I'm facing is quite common I suppose but I didn't see a single thread in internet.
If I use isset($_POST),
Will it always return true?
Does the response depend on the version of PHP I use?
Is $_POST is a variable? (it's a super global 'variable' after all). Because in php.net documentation, it is mentioned
isset() only works with variables as passing anything else will result in a parse error.

Will it always return true?
Yes, even if the page was opened using GET method or nothing was POSTed.
Does the response depend on the version of PHP I use?
No it does not (not sure about very old versions of PHP).
Is $_POST is a variable?
Yes
isset() only works with variables as passing anything else will result in a parse error.
This is explicitly mentioned in the manual so that people do not try to do cheaky stuff. These won't work for example:
function getVarName() { return '_POST'; }
isset(getVarName());
isset('$_POST');
Now, why would you want to check if $_POST is set. Perhaps want to check if a certain variable (e.g. email) was posted, in that case you need to check:
isset($_POST["email"])

isset($_POST); will always return true. If you want to check if it contains something use empty($_POST);
Does the response depend on the version of PHP I use?
No
Is $_POST is a variable ?
Yes

Whether or not you posted any data $_POST will always be set as an array. What you are probably looking for is the empty() method to see if any data was actually posted, like:
if(!empty($_POST)) {
// POST data was set
}

I would recommend using one of the following:
if($_POST){
}
if(!empty($_POST)){
}
1, Will it always return true?
isset($_POST) will always return true. If $_POST is empty it will return false.
2, Does the response depend on the version of PHP I use?
I'm not sure about versions below 4.* but the response has always been the same.
3, Is $_POST is a variable?
Yes, it is considered a superglobal like: $GLOBALS, $_SESSION, $_POST, $_GET

Will it always return true?
Yes it would always be true
Does the response depend on the version of PHP I use?
No tested on PHP 4.3.0 - 5.4.10
Is $_POST is a variable?
Definitely Yes
Better way to validate $_POST is to use empty

Isset()
return true only if it contains some value (it can be Zero 0).
If it doesn't have any value then it returns false.
If you want to prevent from (0) use
if(isset($_POST) && $_POST)
This will be true if only it has non-zero value
$_POST is global array
Response doesn't depend upon the version of PHP

Related

Should I check isset($_GET[...]) when I expect it to always be set?

I was recently placed on a project with some PHP, and I don't know much about PHP. There are a couple instances in the site where upon clicking a button, the user is redirected to another page with some URL parameters. The next page then uses $_GET to get those parameters and move on.
Another issue in the code caused the page to reload the second page without the parameters, so using $_GET would return errors, but with the other issue fixed, I can't think of a reason why the parameters wouldn't be there.
While debugging, I came across advice to always check $_GET using isset(), but theoretically there should never be an instance when those parameters aren't there (otherwise something else is really wrong with the server or the code).
Is it still worth putting in the checks and working out a backup solution, even though there shouldn't be a need for it? I want to make sure I'm not ignoring some other potential issue that I may not be aware of.
It is always good practice+recommended to check your variables before applying any logic.
!empty() is recommended to use instead of isset() because it check both that variable is initialized and have some values too.
In case of array count($array)>0 can be used as a check.
Why to use !empty() check here:- !empty() Vs isset()
If you are expecting or requiring data to be sent via $_GET you should check if it's set. Especially since that data can be easily manipulated. Also like #Alive to Die said !empty() is better.
isset() checks if a variable has a value including ( False , 0 , or
empty string) , but not NULL. Returns TRUE if var exists; FALSE
otherwise. On the other hand the empty() function checks if the
variable has an empty value empty string , 0, NULL ,or False.

PHP: Is it bad practice to use an unset variable?

For example, if I want to use the code:
$foo = $_POST['foo']. $_GET['foo'];
to get a value whether passed by POST or GET, is this acceptable or bad practice?
Don't see anything in your answer which is to be unsetted, though you can use $_REQUEST['foo'], as that will consider $_POST as well as $_GET but again, your code will be dirty, say for example I tweaked the method value, for login form, users can easily attack your website...
So be wise, use $_GET[] and $_POST[] instead of using loose $_REQUEST[]
If for any means, you are using $_REQUEST thank make sure you use conditions to check whether the request is GET or POST using $_SERVER['REQUEST_METHOD']
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//Do something
}
I would go with:
$foo = isset($_REQUEST['foo']) ? $_REQUEST['foo'] : null;
More at: http://php.net/manual/pt_BR/reserved.variables.request.php
to get value whether passeb by POS or GET use this
$foo = $_REQUEST['foo'];
If you configure your development server PHP to throw all warnings, you will find out.
why are you using . operator, if i am not wrong this would concatenate the result, as the above suggested using $_REQUEST would be the better approach.
Yes, it's terrible. There are two problems:
It will raise a warning
Concatenation is not suited for this use case
If you want to get a key from either $_POST, or $_GET, and you don't care which one the key is present in, you can use the $_REQUEST superglobal with the following idiom:
$var = isset($_REQUEST['foo']) ? $_REQUEST['foo'] : null;
$_REQUEST is the union of $_GET and $_POST.

isset or !empty for $_GET[var]

i recently had to do a "test" for a job, and i got feed back saying that this statement was incorrect:
$images = $flickr->get_images(5, !empty($_GET['pg']) ? $_GET['pg'] : 1);
The "supposed" error was generated via the ternary operator on the first time the page was loaded, as there was no "?pg=1" (or whatever) passed via the query string.
The feed back said i should have used isset instead. I have looked at various posts both here (question 1960509) and blogs, but cannot find any definitive answer.
Is this really an error? How can i replicate this issue? do i need to put on E_STRICT or something in my php.ini file? Or might this be due to an older version of php?
Note: please don't tell me about how i should validate things.. i know this... it was a test to just see if i could use the flickr api calls.
This is perfectly fine. empty is not an actual function, it's a language construct. It does not issue a warning if a variable is not set (in that case the variable is considered empty, thus the 'function' returns TRUE just as you want), and additionally it checks for empty or zero values.
You could see empty as a normal isset check with an additional loose comparison to FALSE:
empty($var) === (!isset($var) || $var == FALSE)
$images = $flickr->get_images(5, (isset($_GET['pg']&&($_GET['pg']))) ? $_GET['pg'] : 1);
without isset you'll get error so combine them
I'd use
$images = $flickr->get_images(5, array_key_exists('pg', $_GET) ? $_GET['pg'] : 1);
Combine with !empty($_GET['pg']) if needed (i.e. array_key_exists('pg', $_GET) && !empty($_GET['pg'])), but array_key_exists is the intended function for this job.
I think in a situation like this isset is the correct function to use as it is checking the existence of the array element rather than checking if the value of the element has been set. As Martin notes, the best thing to do here is combine them as this will only check the value if the element exists, meaning that the error will not occur on the first page load.
Also, I think this will only give a warning if E_NOTICE is on (or perhaps E_WARNING as well)
The reason you would get an error is because the empty function is designed to check the value of an existing variable, whearas isset() is designed to tell you whether a variable has been instantiated, however because empty() is a language construct technically it doesn't throw an error or create a warning so most people don't see the difference.
From the docs:
empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.
isset — Determine if a variable is set and is not NULL. So "isset" is the correct function to use for checking for value is set or not.
More details :http://php.net/manual/en/function.isset.php

PHP filter_has_var vs empty?

i know that empty is a bit faster then isset, but filter_has_var is a bit faster then isset (in php.net it written) so what is faster empty or filter_has_var ?
filter_has_var() might be useful if the superglobals have been purged for some reason, because it checks the original input data, not $_GET, $_POST, $_ETC.
For example:
$_GET["injected"] = 123;
var_dump( filter_has_var(INPUT_GET, "injected") ); // false
// or the other way round
While you can overwrite the variable, the filter extension accesses a separate copy. And INPUT_GET will not alias to the $_GET superglobal.
Apart from that another reason is to use it for unification. If you use filter_var extensively, than a ruleset would be more fond of using filter_has_var() over isset().
But don't use one or the other because of any silly performance reasons.
filter_has_var and empty are two totally different functions that do totally different things. You would not want to swap the use of these two functions.
empty is actually a language construct that checks if a variable is considered empty to PHP: for example null, array() or '' are considered empty.
filter_has_var simply checks one of the PHP superglobals: $_GET, $_POST, $_SERVER, $_ENV or $_COOKIE to ensure that a variable was passed with a request. This function will still return true if the var is empty.

What is the benefit of using filter_has_var() over isset()

I'm a little confused with the benefit of using filter_has_var($_POST['id']) over isset($_POST['id']).
Can Somebody please tell me if it's simply an alias function?
Not alot ;) According to the manual page for filter_has_var one user finds filter_has_var a little quicker. Also worth noting... filter_has_var isn't working on the live array ($_POST) but on the actual provided input... if you ever add/remove/update what's in that array you won't see those changes with a filter_has_var call (while isset will reflect the current state)
By the way the usage is filter_has_var(INPUT_POST,"id");
Update: Perhaps worth mentioning, filter_has_var was introduced in PHP 5.2.0 (somewhat new) while isset has been around for all of PHP4+5. Most servers keep up to date on this, but isset will always work (no one still runs PHP3 do they?)
First of all, it's not
filter_has_var($_POST['id'])
It's
filter_has_var(INPUT_POST, 'id')
Secondly, it doesn't actually query the $_POST superglobal. It analyzes the request parameter that came in with the request, so it's a better method to use in case $_POST gets dirtied in some way by the PHP script.
I think you mean filter_has_var(INPUT_POST, 'id') over isset($_POST['id']).
There is a small difference in that isset returns false if $_POST['id'] is NULL; you'd have to use key_exists('id', $_POST) to have similar behavior in that regard.
Besides that, the only difference is that filter_has_var doesn't consider modifications to the $_POST array (see this comment).
Function doesn't check live array
<?php
$_GET['a'] = 1;
echo filter_has_var(INPUT_GET, 'a') ? 'Exist' : 'Not exist';
will print Not exist

Categories