Another option to use @ in PHP?

Asked

Viewed 827 times

8

I don’t feel very comfortable having to use the @ before some variables and sessions when making conditions, to avoid error of Unexpected Index which happens when the variable or session was not previously initialized.

I was wondering if there is some way that I can set, in a top file of my application for example, a PHP pro setting automatically do this for all variables and sessions? Suddenly some other solution?

  • 2

    In practice I would be taking something that is not good and exchanging it for something worse. It is right to correct and avoid common and predictable mistakes. The error inhibitor @ is used for very specific cases as functions that return inexperienced errors that cannot be controlled by the error setting.

  • 3

    @gmsantos Why was my question edited and my greeting removed? I don’t recall reading anything that prohibits it, sorry if I’m wrong, but I found it unnecessary for you to interfere...

  • 2

    @Dirtyoldman this type of greeting is considered a noise. One of the slogans of SOPT is Ask questions, get answers, no distractions. More details on that goal response.

  • I’m sorry if I seemed intrusive, but I have a habit of do that kind of editing :)

4 answers

8


The @ is not a good practice, although it can be used, the recommended to do variable checks is the isset.

The isset other than array_key_exists (which can also be used as Ricardo’s example) supports multidimensional checks and you can also check more than one variable at the same time, for example:

  • Checking for multidimensional arrays:

    <?php
    $test = array('a' => 1);
    
    var_dump(isset($test['a']['b'])); //Retorna bool (false)
    var_dump(isset($test['a']));      //Retorna bool (true)
    
  • Checking more than one variable at the same time:

    <?php
    $a = 1;
    var_dump(isset($a)); //Retorna bool (true)
    var_dump(isset($a, $b)); //Retorna bool (false) por que $b não existe
    

    or

    <?php
    $a = array('test' => 1);
    $b = array('foo'  => 2);
    
    var_dump(isset($a['test'])); //Retorna bool (true)
    var_dump(isset($a['test'], $b['test'])); //Retorna bool (false) por que $b['test'] não existe
    

The isset also supports stdClass (or variables of a class)

Details about the isset:

  1. It’s not a function, it’s a builder
  2. If the variable is NULL or FALSE he will return false, as in the example:

    <?php
    $a = NULL;
    var_dump(isset($a)); //Retorna bool (false)
    

Empty vs isset

Should it not be possible to verify several variables at the same time, as in the example already cited with isset (isset($a, $b, $c, $d, $e)), you can use the empty, that besides checking if the "variable exists" it also checks if it is empty in case of strings for example. Situations that Empty will return TRUE:

  • "" (an empty string)
  • 0 (when it is an integer equal to zero)
  • "0" (zero as string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (When a variable is declared in a class, but has no value as it is NULL)

The problem of the question

How to delete all undeclared variable notifications without using @? In this case I would recommend to use the isset and create normal variables, such as:

$variavelA = empty($_SESSION['varA']) ? NULL : $_SESSION['varA'];
$variavelB = empty($_SESSION['varB']) ? NULL : $_SESSION['varD'];
$variavelC = empty($_SESSION['varC']) ? NULL : $_SESSION['varC'];
$variavelD = empty($_SESSION['varD']) ? NULL : $_SESSION['varD'];

If it seems laborious, you can use a loop with foreach or for, it is a little gambiarra admit, but there are different ways to do the process, this is just one and will depend on how your code is:

$keys_in_session = array('a', 'b', 'user', 'ultimaatividade');

foreach ($keys_in_session as $k => $v) {
    if (empty($_SESSION[$v])) {//Acaso a variável não exista na sessão ele cria ela como o valor `NULL` para que você possa usa-la sem ocasionar
        $_SESSION[$v] = NULL;
    }
}

Consideration of use

Despite the example with foreach, I personally recommend using only the isset and the empty combined with if or with ternary comparison operators:

echo 'Resposta: ', ( empty($_SESSION['message']) ? 'sem resposta' : $_SESSION['message'] );

Development Environment vs Production Environment

As already quoted in the other answer, the use of error_reporting is a good practice for the production and development environment.

  • Production environment is one that is understood at the moment that the software is already used to "produce something", in other words, when the site is already on the air.

  • Development environment is that of when you are developing the software in a place where it does not affect the server/ site or be on your machine for example.

I personally always use in development environment all error notifications "on":

<?php
//No topo do script
error_reporting(E_ALL|E_STRICT);

In production environment always turn off all errors:

<?php
//No topo do script
error_reporting(0);

But it is not possible to determine all failures that may occur and all situations, so how to know which errors occurred? For this we have 3 functions that we can use combined, error_get_last(), set_error_handler and register_shutdown_function, so you can record the errors in a file .txt for example and refer this file to check when the failure occurred, see an example in this other response:

/a/34818/3635

Note: It is not why you will turn off error messages that you should not use isset or empty, seek to use the E_ALL|E_STRICT to detect possible code failures and then fix them.

  • 1

    +1 This should be marked as the correct answer. He spoke about error_reporting in development and talked about isset to check variables. It is not good practice to use the @ to avoid the Notices.

6

With this solution you check whether the array key session (or any other) exists.

if (array_key_exists("login", $_SESSION)) {
    echo "O Usuario esta logado";
}

This solution will no longer display notices like the Unexpected Index (is what the question asks) but does not resolve the Unexpected Index.

To set up php.ini to not display the notification messages you should leave it as follows:

error_reporting  =  E_ALL & ~E_NOTICE

Another way is to paste this line into the file start .php:

ini_set("display_errors", "0");

Another way is to paste this line into the file start .php:

error_reporting(E_ALL ^ E_NOTICE); // ira reportar todos esceto os `notices`.
  • In this case, the error information will be deleted, which is not good practice in the development environment.

  • @Rodrigospeller But this is exactly what the author asked.

  • A code has been added that checks if the $_SESSION key exists before using it thus inhibiting the error.

1

Follow the file session_defs.php to be included in the code setup. In this file I created the function session_def, that sets the default value for the session variable if it has not yet been defined.

Filing cabinet session_defs.php

<?php
function session_def($name, $value) {
    // isset: Informa se já variável foi iniciada antes
    if (!isset($_SESSION[$name]))
        return $_SESSION[$name] = $value; // Se não foi iniciada,
                                          // inicia com o valor padrão
    return $_SESSION[$name];
}

// Cria a sessão ou resume a sessão atual.
// A partir deste ponto a variável $_SESSION é definida com os valores
// que já foram definidos anteriormente.
session_start();

// Define os valor padrão para as variáveis de sessão que não foram iniciadas
// com session_start.
session_def('item1', 12345);
session_def('item2', true);
session_def('item3', 'string');

?>

Use

<?php
require_once 'session_defs.php';
?><!doctype html>
<html>
<head>
    <meta charset="utf-8">
</head>

<body>
<pre>
<?php
var_dump($_SESSION); 
?>
</pre>

</body>
</html>
  • 1

    Your answer is good, but it does not explain the important point, the isset, consider editing it.

  • Edited. If you have any doubt about using the isset function, the PHP documentation is quite complete [ http://php.net/manual/en/function.isset.php ].

-3

Usually this Undefined index error is caused by problems with $_POST or $_GET.

You can execute the Extract(); command at the beginning of the code. So all variables already enter automatically, without calling $_POST or $_GET.

Just enter at the beginning of the code:

extract();

This article explains in detail the solution to the error:

https://www.homehost.com.br/blog/notice-undefined-index-php/

Browser other questions tagged

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