Что является настолько неправильным с извлечением ()?

Синтаксис для redirect предполагает *args и **kwargs. Итак, вы бы написали:

return redirect('mesChambres', id, nbChambre)
33
задан Community 23 May 2017 в 12:18
поделиться

12 ответов

I find that it is only bad practice in that it can lead to a number of variables which future maintainers (or yourself in a few weeks) have no idea where they're coming from. Consider this scenario:

extract($someArray); // could be $_POST or anything

/* snip a dozen or more lines */

echo $someVariable;

Where did $someVariable come from? How can anyone tell?

I don't see the problem in accessing the variables from within the array they started in, so you'd really need to present a good case for using extract() for me to think it's worth it. If you're really concerned about typing out some extra characters then just do this:

$a = $someLongNameOfTheVariableArrayIDidntWantToType;

$a['myVariable'];

I think the comments here on the security aspects of it are overblown somewhat. The function can take a second parameter that actually gives you fairly good control over the newly created variables, including not overwriting any existing variables (EXTR_SKIP), ONLY overwriting existing variables (so you can create a whitelist) (EXTR_IF_EXISTS), or adding prefixes to the variables (EXTR_PREFIX_ALL).

64
ответ дан 27 November 2019 в 17:22
поделиться

Риск такой же, как и для register_globals. Вы позволяете атакующему устанавливать переменные в вашем скрипте, просто изменяя запрос.

1
ответ дан 27 November 2019 в 17:22
поделиться

I guess the reason a lot of people don't recommend using it is that extracting $_GET and $_POST (even $_REQUEST) superglobals registers variables in the global namespace with the same name as each key within those arrays, which is basically emulating REGISTER_GLOBALS = 1.

4
ответ дан 27 November 2019 в 17:22
поделиться

Люди поднимают все вопросы об извлечении, потому что в нем есть потенциал может быть использован неправильно. Выполнение чего-то вроде extract ($ _ POST) в любом случае не является хорошей идеей, даже если вы знаете, что делаете. Тем не менее, его можно использовать, когда вы делаете такие вещи, как предоставление переменных в шаблон представления или что-то подобное. По сути, используйте его только тогда, когда вы совершенно уверены, что у вас есть для этого веская причина, и понимаете, как использовать параметр типа извлечения, если вам приходит идея передать ему что-то сумасшедшее, например $ _POST.

5
ответ дан 27 November 2019 в 17:22
поделиться

There is nothing wrong with it. Otherwise it wouldnt be implemented. Many (MVC) frameworks use it when you pass (assign) variables to Views. You just need to use it carefully. Sanitize those arrays before passing it to extract() and make sure it does not override your variables. Dont forget that this function also accepts a few more arguments! Using the second and third arguments you can control the behavior if collision occurs. You can override, skip or add prefix. http://www.php.net/extract

9
ответ дан 27 November 2019 в 17:22
поделиться

риск состоит в том, что: не доверяйте данным от пользователей, а извлечение в текущую таблицу символов означает, что ваши переменные могут быть перезаписаны тем, что предоставляет пользователь.

<?php
    $systemCall = 'ls -lh';
    $i = 0;

    extract($_GET);

    system($systemCall);

    do {
        print_r($data[$i];
        $i++;
    } while ($i != 3);

?>

(бессмысленный пример)

но теперь злонамеренный пользователь, который догадывается или знает код, вызывает:

yourscript.php?i=10&systemCall=rm%20-rf

вместо

yourscript.php?data[]=a&data[]=b&data[]=c

, теперь $ systemCall и $ i перезаписываются, в результате чего ваш скрипт сначала удаляет ваши данные, а затем зависает.

17
ответ дан 27 November 2019 в 17:22
поделиться

If you extract in a function, the variables will only be available in that scope. This is often used in views. Simple example:

//View.php
class View {
    function render($filename = null) {
        if ($filename !== null) {
            $this->filename = $filename;
        }
        unset($filename);
        extract($this->variables);
        ob_start();
        $this->returned = include($this->dir . $this->filename);
        return ob_get_clean();
    }
}

//test.php
$view = new View;
$view->filename = 'test.phtml';
$view->dir = './';
$view->variables = array('test' => 'tset');
echo $view->render('test.phtml');
var_dump($view->returned);

//test.phtml
<p><?php echo $test; ?></p>

With some alternative directories, checks to see if the file exists and defined variables and methods - you've pretty much replicated Zend_View.

You can also add $this->outVariables = get_defined_vars(); after the include to run code with specific variabels and get the result of these for use with old php code.

3
ответ дан 27 November 2019 в 17:22
поделиться

Я позволю руководству по PHP говорить за меня.

Справочная информация: extract ($ _ REQUEST) такой же, как настройка register_globals = On в php.ini

3
ответ дан 27 November 2019 в 17:22
поделиться

Давай. Люди винят инструмент, а не пользователя.

Это все равно что говорить против unlink () , потому что с его помощью вы можете удалять файлы. extract () - такая же функция, как и любая другая, используйте ее с умом и ответственно. Но не утверждайте, что это плохо само по себе, это просто невежество.

38
ответ дан 27 November 2019 в 17:22
поделиться

Never extract($_GET) in a global scope. Other than that, it has its uses, like calling a function that could (potentially) have lots of optional arguments.

This should look vaguely familiar to WordPress developers:

function widget (Array $args = NULL)
{
    extract($args);

    if($before_widget) echo $before_widget;

    // do the widget stuff

    if($after_widget) echo $after_widget;
}

widget(array(
    'before_widget' => '<div class="widget">',
    'after_widget' => '</div>'
));
1
ответ дан 27 November 2019 в 17:22
поделиться

Если не использовать осторожно, это может сбить с толку других, с которыми вы работаете. Учитывайте:

<?php

    $array = array('huh' => 'var_dump', 'whatThe' => 'It\'s tricky!', 'iDontGetIt' => 'This Extract Function');
    extract($array);
    $huh($whatThe, $iDontGetIt);


?>

Выводы:

string(12) "It's tricky!"
string(21) "This Extract Function"

Было бы полезно использовать для обфускации. Но я не могу перебороть вопрос "Откуда этот вар?" проблема, с которой я столкнулся.

6
ответ дан 27 November 2019 в 17:22
поделиться

Как кто-то заметил в другом потоке, здесь более безопасный способ использования extract , позволяя извлекать только указанные вами переменные, а не все, что содержит массив.

Это служит двойной цели - документированию того, какие переменные выходят из него, поэтому отследить переменную не будет так сложно.

1
ответ дан 27 November 2019 в 17:22
поделиться
Другие вопросы по тегам:

Похожие вопросы: