When is isset required?

Asked

Viewed 26,812 times

8

I would like to know when it really is essential to use the isset variables in PHP, especially in the case of forms.

What happens is that I am creating a large form, with some 200+ fields, which will perform calculations and other functions in PHP according to the fill out.

No field will be mandatory, and the system will make the "possible calculation" with the information provided. For now, how am I testing just on localhost, no problem using variables just like this for example:

$difsal = $_POST ["Tdifsalim"];  
$saldev = $_POST ["Tdate5"];

So even if the respective field (Tdifsalim for example) is not completed on the form, the script normal wheel, and gives the expected result (according to the fields that have been filled). But then I was in doubt if later, when to put in the server, I still have to include all these issets to avoid request errors.

So the question is: ask isset in all form variables is it really necessary? If it is, in the example above what is the simplest way to include the isset so that when the field is not filled in, the value of the variable is equal to null (not 0, because it can affect the calculations).

5 answers

8


It’s not supposed to work differently in different places. Of course there may be permissions or specific settings issues that can affect, but in general what involves only code logic and not libraries, is not to make a difference.

The isset is necessary if you need to know if the variable has been previously defined. If this doesn’t matter, if an implicit value is picked up gives an appropriate result, you don’t need to use it. Such "best practices" indicate for whenever possible to use the check and only stop using when there is a reason for it. Perhaps you have heard that one of the biggest concerns of software development, mainly for the web, is that all the data that will enter the application should be validated. All relevant possible validations should be made. The first validation should be whether the actual data exists.

You should do this item by item, you should test every index you want to use on $_POST or other information that comes externally.

The only thing that can be done to make it easier is to create a function that helps you validate, so you would pass a list of expected indexes and if anyone is not present, the function would file an error. The gain is not huge but simplifies the logic a little. How much this is advantageous depends on the case. You can do so:

function post_isset($indexes) {
    foreach($indexes as $index) if (!isset($_POST[$index])) return false;
    return true;
}
if (!post_isset(['nome', 'email'])) echo "deu erro";

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Of course this version is well simplified, this can be improved to indicate where the error occurred, can make it work with something other than $_POST, finally, there are several sophistications that can be developed.

In your example you want to take a null value and not a zero, well, this is what you take when the variable does not exist, it does not take a value default, or at least the deafult is null. But if you decide to take the direct variable, if the null meets you, it will still generate at least one notice, that is not ideal.

There are other ways like the Wallace Maxters answer that can get a similar result but the test needs to be done.

  • Thanks, that’s exactly what I wanted to know!

7

function isset

According to the PHP manual, the function isset serves to verify if a variable is existing or if it does not have the value equal to NULL. If she goes NULL or does not exist, the result of this function will return FALSE.

Filtragem de Dados

How PHP 5.2 implemented the filters, I wouldn’t use the isset, but would use the functions of this library to better filter the data.

$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$senha = filter_input(INPUT_POST, 'senha');

if ($email && $senha) {
   // faça alguma coisa
}

Take a look at the Manual for PHP

function filter_has_var

In the case of existence verification, it would be good to use the function filter_has_var. This function checks the existence of external variables according to their type (POST, GET, COOKIE).

An interesting difference between isset and filter_has_var was reported by a user on the PHP manual page (I tested and verified the results).

For the low examples the results are different:

$_GET['test'] = 1;

echo filter_has_var(INPUT_GET, 'test') ? 'Existe' : 'Não Existe'; // Não existe

echo isset($_GET['test']) ? 'Existe' : 'Não Existe'; // Existe

In the above case, the filter_has_var will verify the "real" existence of the variable passed by parameter in the url. The isset only checks whether the value exists within the global variable $_GET.

  • Thanks Wallace, it was very helpful, I will study these functions better.

5

The function isset - Tells whether the variable has been started. Only this.

The variable $_POST is a superglobal1 always soon it always exists (Set), but its content may be empty.

What you can use is the function Empty to check if your variable has value.

if (!empty($_POST["email"])) {
 echo "E-mail possui valor.";
}


1 Superglobal are native variables that are always available in all scopes

Sources: PHP: isset, PHP: Empty, PHP: $_POST, PHP: Superglobal, Stackoverflow.

  • isset also checks if the value is NULL. It may exist, but it may be null.

  • 1

    Thanks Laerte, I will study better the Mpty and the functions that Wallace indicated. The people here have helped me a lot, I am very grateful to all.

  • Dispose! I learn a lot here too. :)

2

Always use when a variable comes from the user, but it’s also good to always check even if the data comes from the application itself.

When you do

$saldev = $_POST ["Tdate5"];

It is causing an error when the index does not exist however when the error message does not appear on the screen is due to setting hiding it and this is a bad practice. Set environment to show errors when in development environment (localhost)

error_reporting(E_ALL)

Always check the entrances:

$saldev = isset( $_POST["Tdate5"] ) ? $_POST["Tdate5"] : false;
  • Ah, but this will be a hassle! : ) haha So from what I understand it is right to validate even in some way, because although it is working, it is not a good practice. I’m seeing here among the options that were put, and I think that the bigow looks simpler (its shape is the one I was going to do), but thanks for the answer. + 10 Edit: to configure the localhost just include this line in apache2.conf? Thanks for that tmb!

  • 1

    This "hassle" can be reduced by using libraries or frameworks. But if you want to create your own method, simply create a class or a simple function that abstracts and check the $_REQUEST data. Then you define the essential validation rules with option to customize.

  • "the right is to validate even somehow, because although it is working" In fact it is not "working" safely. An error is being generated but is being ignored. The way you’re doing it, when you’re running in a restricted settings environment, you’re sure to run into problems. Here come those famous questions "works localhost and does not work on server" rsrsr..

  • 1

    @gustavox Understand that you are generalizing two different concepts: Data entry and data validation. Data entry should always be checked. php does not accept undetermined data. Even if your field has nothing completed it is mandatory that there is at least one value false or null set to the variable. Ensuring that data has been received does not guarantee that it is valid, although valid does not guarantee that it has been received. Finally, particularly I like this way of getting the data, if you have a netbeans in hand, it gets agile yet.

1

Ah some time implement this function :

        /**
         * campoNecessario
         *
         * Realiza uma verificacao no(s) campo(s) passado(s), que retorna "true",
         * caso esteja "empty", o "empty" tambem considera valor "0" como "empty",
         * por isto se quiser permitir valores zerados defina o segundo parâmetro
         * como "true".
         * Realiza um verificacao caso o campo nao esteja exatamente igual a ER,
         * lembrando que "preg_match" retorna 1 caso ER = //
         *
         * @name        campoNecessario
         * @param       $campos
         * @param       $campoZerado
         * @param       $expressaoRegular
         * @return      boolean
         * @author      Guilherme Lautert
         * @since       00/00/0000 00:00:00
         * @modified    26/02/2015 13:35:10
         */
        public function campoNecessario($campos, $campoZerado = FALSE, $expressaoRegular = 'A'){
            switch ($expressaoRegular){
                case 'A':  // all
                    $expressaoRegular = '//';
                break;
                case 'N': // numeros
                    $expressaoRegular = '/^[0-9]+$/i';
                break;
                case 'L': // letras
                    $expressaoRegular = '/^[a-zA-Z]+$/i';
                break;
                case 'NL': // letras e numeros
                    $expressaoRegular = '/^[a-zA-Z0-9]+$/i';
                break;
                default:
                    $expressaoRegular;
                break;
            }

            if(is_array($campos)){
                foreach ($campos as $key => $campo){
                    if(is_array($campo)){
                        return $this->campoNecessario($campo, $campoZerado, $expressaoRegular);
                    }else{
                        if($campoZerado){
                            if(empty($campo) && ($campo !== "0")){
                                return TRUE;
                            }
                        }else{
                            if(empty($campo) || $campo == "0,00" || $campo == "0.00"){
                                return TRUE;
                            }
                        }
                        if(!preg_match($expressaoRegular, $campo)){
                            return TRUE;
                        }
                    }
                }
            }else{
                if($campoZerado){
                    if(empty($campos) && ($campos !== "0")){
                        return TRUE;
                    }
                }else{
                    if(empty($campos) || $campos == "0,00" || $campos == "0.00"){
                        return TRUE;
                    }
                }
                if(!preg_match($expressaoRegular, $campos)){
                    return TRUE;
                }
            }
            return FALSE;
        }

I hope it helps.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.