PHP - checking isset on a $_SESSION[$_REQUEST[]] variable - php

Seems an easy one, but cannot work out why:
if(!isset($_SESSION[$_REQUEST["form_id"]]))
{
//do stuff
}
reutrns
Notice: Undefined index: form_id
empty returns same response.
This has been driving me mad for a while. :)

You're calling isset for $_SESSION but as the error states the issue is with $_REQUEST['form_id'] not being set.
if (!isset($_REQUEST['form_id']) || !isset($_SESSION[$_REQUEST['form_id']])) {

That's because it resolves $_REQUEST['form_id'] first and that causes the notice. You could do this instead:
if (!isset($_REQUEST['form_id']) || !isset($_SESSION[$_REQUEST["form_id"]]))
{
//do stuff
}

please check if key exists with
array_key_exists('form_id', $_REQUEST);
before checking value with
isset($_REQUEST['form_id']);

or check if your params are empty like
<?php
if (!empty($_REQUEST['form_id'])) {
// do anything
}
else
{
// I can't find the key in array
}
?>

Related

Notice: Undefined index with used isset and $_GET

this is my code
if(isset($_GET['delt']) || isset($_GET['editt'])){
$delt = intval($_GET['delt']);
$editt = intval($_GET['editt']);
}
when run the code I get the error
Notice: Undefined index: delt in
/opt/lampp/htdocs/tel-s/admin/top_a.php on line 116
I'm confused because i use isset and test used empty but do get the same problem
Your are testing only if one of params is set and later use both of them no matter if it's actually set.
Use && (and) instead of || (or):
if (isset($_GET['delta']) && isset($_GET['editt']))
OR
if (isset($_GET['delta'], $_GET['editt']))
Check both of variables for exists or change code
if( isset($_GET['delt']) ) {
$delt = intval($_GET['delt']);
}
if ( isset($_GET['editt']) ) {
$editt= intval($_GET['editt']);
}
It must have gotten $_GET['editt'] but couldn't get $_GET['delt'] and threw an error because it couldn't set anything to $delt. Consider #Justinas' answer.
did your url contains both "delt" and "editt" parameters ?
what is the out put of print_r($_GET) ?
isset function checks whether a variable is set or not ?
if you pass a string to intval() it will return 0

Checking if array is empty or not doesn't seems to work

Simple array and simple check if is array or object .. yet page crashing when there is no array data instead of showing No. This is the array
$url=get_curl_content_tx("https://example.com");
$arr = json_decode($url, true);
if (is_array($arr['outputs']) || is_object($arr['outputs'])) {
echo 'Yes';
}
else {
echo 'No';
}
if I receive fail i.e. no data from the url and $arr['outputs'] is empty I've got blank page with
Undefined index: outputs
instead of No. Doesn't if (is_array($arr['outputs']) || is_object($arr['outputs'])) check if is array or no?
If there is data in $arr['outputs'] everything is fine.
You need to use isset or array_key_exists to check the key exists in the $arr array before referring to it.
if (isset($arr['outputs']) && is_array($arr['outputs'])) {
You want to access a non-existent array, which gives you an error, no matter what function you are using right before. To solve this, check first if the array exists with isset():
if(isset($arr)) {
// Just gets executed if the array exists ans isn't nulll
} else {
// Array is null or non-existend
}
and add then your code in the if-else.

Is this the correct way of checking empty array?

I want to check if array is empty or not, i wrote few lines of code for it
if(array() == $myArray){
echo "Array";
}
or
if(array() === $myArray){
echo "Array";
}
I'm confused which one to use, as the second condition also checks type. But i think in the case of array we don't need to check their type.
Please anybody can suggest me which one to use.
you can check it by using empty() function like below
<?php
if(empty($myArray)) {
//condition
}
?>
if (! count($myArray)) {
// array is empty
}
Let php do its thing and check for booleans.
Use empty:
if (empty($myArray)) {
...
}
Try this :
<?php
$array = array();
if(empty($array))
{
echo "empty";
} else
{
echo "some thing!";
}
?>
It's always better to check first whether it is array or not and then it is empty or not. I always use like this because whenever I check only empty condition somewhere I don't get the expected result
if( is_array($myArray) and !empty($myArray) ){
.....
.....
}
<?php
if(empty($yourarry)){
}
OR
if(isset($yourarry)){
}
OR
if(count($yourarry)==0){
}
It depends:
Use count==0 if your array could also be an object implementing Countable
Use empty otherwise
array() == $myArray is unreadable, you should avoid it. You can see the difference between count and empty here.

PHP - proper check if $_POST['variable'] is posted

I want to check if $_POST['submit'] is posted.
My original code was:
if ($_POST['submit']) { }
But I have a PHP notice with this code - "Undefined index: submit in..."
So to remove the notice I have to write this:
if (isset($_POST['submit'])) { }
But this is pointless because $_POST array is global and it return always true.
Also if I want to check if $_POST['submit'] is not 0 without PHP notice I have to write this:
if (isset($_POST['submit']) && $_POST['submit'] != 0) { }
In this particular case I prefer:
if ($_POST['submit']) {}
But here I get the PHP notice.
So which way is the most proper/accepted?
Thank you
isset($_POST['submit']) checks if the submit key is set in the $_POST array. It doesn't just check whether the $_POST array exists and is therefore not "pointless". If you want to check whether the value is not falsey (== false), which includes 0, without triggering an error, that's what empty is for:
if (!empty($_POST['submit']))
which is the same thing as
if ($_POST['submit'])
but without triggering a notice should the value not exist.
See The Definitive Guide To PHP's isset And empty for an exhaustive explanation.
Try
if ($_SERVER['REQUEST_METHOD']=='POST')
{
//do
}
As of PHP version 7 there is a new method available called "Null Coalesce Operator". This method saves you time and space in your code.
$submit = $_POST['submit'] ?? '';
If submit key does not exist or is NULL the value of the $submit variable will be an empty string.
This method is not limited to $_POST. It will work for any variable. For example:
echo $my_message ?? 'No message found';
If message was not initialized or is NULL, the statement above will output No message found
There's even more that you can do with a null coalesce operator, documentation link below.
Documentation here
$_POST[] checks to see if a variable is submitted and not the form name.
if ( isset($_POST['name']) ) {
// work here
}
As per my understanding, It should be like below:
if (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST'){
# if method is post, code goes here.
}
and if you are sure that your method is POST for sure. and you have data post in $_POST you can use code like below:
if (isset($_POST['submit']) && $_POST['submit'] != '') {# I think, '' instead of 0
# if data is posted, code goes here.
}
I usually prefer $_POST.

What is the best way to know is $_GET['example']=="somevalue"?

if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR
if((!empty($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR just
if($_GET['example']=='somevalue'){ ... }
I am asking that why I have seen many example where people check first if $_GET['example'] is set and then if $_GET['example']=='somevalue' ( first and second example above ).
I don't understand why not just use the last solution ( if $_GET['example']=='somevalue' then $_GET['example'] is obviously set ).
This question refers to any other variable ( $_POST, $_SERVER, ecc ).
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
Is the right one, you want to know that the "variable" exists (or is set) in order to use it. Empty just checks wether it has data of any kind or not.
For example:
<?php
$foo= 0;
if (empty($foo)) { // True because $foo is empty
echo '$foo is either 0, empty, or not set at all';
}
if (isset($foo)) { // True because $foo is set
echo '$foo is set even though it is empty';
}
if (isset($var)) { // FALSE because $var was not declared before
...
}
?>
The differences between isset and empty are subtle but important. They are most relevant when used alone. If you are checking that a variable exists and is a truethy value (e.g. any string that is not all spaces or 0s) you can use either interchangeably.
When to use isset
Use isset when it's important to know if the variable has been defined and is not null:
if (isset($maybeExistsMaybeNull)) {
// variable defined and is not NULL
}
When to use !empty
Use !empty when it's important to know if the variable has be defined and is truthy
if (!empty($mightBeEmpty)) {
// variable defined, and isn't "", " ", 0, "0" etc.
}
!empty is a great shorthand for exists and is something.
When to use array_key_exists
Use array_key_exists when it's important to know if the key exists and the value is of no importance:
if (array_key_exists('something', $array)) {
// $array['something'] exists, could be literally anything including null
}
When not to use isset
If your code looks like this:
if (isset($something) && $something) {
// code is shorter with !empty
}
When not to use !empty
If your code looks like this:
if (!empty($something) && $something === "") {
// you meant isset. this is unreachable.
}
Then you're writing code that can't be executed
Code that throws errors is error prone
Avoid writing code that issues notices/warnings that you are ignoring. For example in the question:
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
The first use of example is an undeclared constant. Or is it undeclared - what if you've got define('example', "foo"); somewhere else in the code.
if($_GET['example']=='somevalue'){ ... }
If the url doesn't contain ?example=.. that's going to issue a notice too.
Writing code without displaying errors means you can very easily miss mistakes like the first.
In context: isset and !empty are equivalent
For the example given, these two language constructs act exactly the same.
There is no case where one will act differently than the other, neither will issue a notice if the variable is undefined, and no measurable difference in performance between the two.
As others have said for checking things like $_GET and $_POST you would ideally want to use:
if ( isset($_GET['example']) && $_GET['example'] =='somevalue' ) {
// process data
}
So you always want to firstly make sure that the variable has been set (and not set to null) or in other words exists. Then proceed to check if the variable contains the data that you were expecting. If you try to make reference to a variable which doesn't exist (by not checking isset()) php will give you a notice saying 'undefined variable...etc etc'.
If you wanted to find out if a variable is set but are not concerned too much by what then you could use:
if ( !empty($_GET['example']) ) {
// process data
}
But I would be careful about using empty() on strings in this regard as empty can behave strangely with string data like '0' or ' '.
So I would always do the first one, to a) make sure the variable exists and b) is what you were expecting it to be.
This is something that you'll probably do a lot of and it helps to put together a class/functions which handles this checking for you so you dont have to do it everytime.
function checkValue($key, $value) {
if(array_key_exists($key, $_REQUEST)){
if ($_REQUEST[$key] == $value) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I just use Request as a default instead of switching out (though it is preferable to switch in some cases between POST and GET for security (imo)).
Now you can just call this function anywhere
if (checkValue('Item', 'Tom') === true){} etc
the best is
if((isset($_GET[example]))&&('somevalue'==$_GET['example'])){ ... }
The difference between
'somevalue'==$_GET['example']
AND
$_GET['example']=='somevalue'
If you mistype the == and type = instead, the first notaion will raise an error to notify you.
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }

Categories