When is it necessary to use ISSET?

6

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

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

No field will be required, and the system will make the "calculation possible" with the information provided. For now, as I am just testing on localhost , it is not a problem to use the variables just like this:

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

So even if the respective field (% w / o% eg) is not filled in the form, script runs normal, and gives the expected result (according to the fields that were filled ). But then I wondered if afterwards, when I put it on the server, I still have to include all those Tdifsalim to avoid request errors.

So the question is: does issets in all form variables even necessary? If it is, in the example above the simplest way to include 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 ).

    
asked by anonymous 14.04.2015 / 17:26

5 answers

6

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

isset is required if you need to know if the variable was previously defined. If this does not matter, if an implied value is fetched, you do not have to use it. Such "good practices" indicate for as long as possible to use the verification and only to stop using when there is a reason for this. You may have heard that one of the biggest concerns of software development, especially for the web, is that all data that will go into the application must be validated. You should make all possible validations that are relevant. The first validation should be if the data actually exists.

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

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

function post_isset($indexes) {
    foreach($indexes as $index) {
        if (!isset($_POST[$index])) {
            return false;
        }
    }
    return true;
}

if (!post_isset(['nome', 'email'])) {
    echo "deu erro";
}

See running on ideone .

Of course this version is very simplified, this can be improved to indicate where the error occurred, can make it work with something besides $_POST , in short, there are several sophistications that can be developed.

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

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

    
14.04.2015 / 17:41
6

function isset

According to the PHP manual, the isset function is used to check if a variable exists or if it does not have the value equal to NULL . If it is NULL or does not exist, the result of that function returns FALSE .

Data Filtering

As PHP 5.2 implemented filters , I would not use isset , but would use the functions of that 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 PHP Manual

function filter_has_var

In case of existence check, it would be nice to use the filter_has_var function. 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 examples below, 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, filter_has_var will check the "actual" existence of the variable passed by parameter in the url. The isset only checks to see if the value exists within the global variable $_GET .

    
14.04.2015 / 17:40
4

The function isset - Informs if the variable has started. Just that.

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

What you can use is empty to check if your variable has value.

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


Superglobals are native variables that are always available in all scopes

Sources: PHP: isset , PHP: empty , PHP: $ _POST , PHP: Superglobals , Stackoverflow .

    
14.04.2015 / 17:36
1

Always use when a variable comes from the user, but it is always good to always verify that 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 it is due to the 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 entries:

$saldev = isset( $_POST["Tdate5"] ) ? $_POST["Tdate5"] : false;
    
14.04.2015 / 18:16
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.

    
14.04.2015 / 18:35