用foreach制作的PHP变量 [英] PHP Variables made with foreach

查看:74
本文介绍了用foreach制作的PHP变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个变量来自$ POST _ ['array']中的数组,我希望进行某种循环,例如foreach,它使变量中的每个值都有一个变量名,并为其分配值

I have several variables coming from an array in $POST_['array'] i wish to make some kind of loop for example foreach that makes, for every value in the variable a variable name of it and assigns the value for it.

例如,如果我有

$POST_['name'];
$POST_['last'];
$POST_['age'];
$POST_['sex'];

我希望循环从$ _POST内的数组创建每个变量,其变量名称如下所示:

I want the loop to create each variable from the array inside the $_POST with the name of the variable like the following:

$name = 'John';
$last = 'Doe';
$age = '32';
$sex = 'male';

注意-数组来自一个序列化的jquery字符串,该字符串将所有变量和值以一种形式组合到一个大字符串中.

NOTE - The array is coming from a serialized jquery string that puts together all the variables and values in a form into one big string.

这可能吗?

推荐答案

您不需要循环,您需要提取:

You don't need a loop, you want extract:

extract($_POST); // But use caution, see below


如注释中所述,这会强制将$_POST数组中的所有参数放入当前符号空间.

As noted in the comments this forces all parameters in the $_POST array into the current symbol space.

<?php
extract($_GET);
var_dump($_SERVER); // Can be overwritten by the GET param
?>

上面的代码说明了该问题所示的问题—在 global 空间中,一些非常危险的事情可能会被覆盖.

The code above illustrates the problem as shown in this answer — some pretty dangerous things can be overwritten in the global space.

function myFunc() {
    // (Mostly) empty symbol space! (excluding super globals)
    extract($_POST);
}

在函数内部,作为第一行,没有造成伤害.

Inside a function, as the first line, no harm done.

重要说明:您可能会认为,因为$_SERVER

Important note: You might think since $_SERVER is a super global, that this exploit could happen inside a function as well. However, in my testing, on PHP Version 5.3.4, it is safe inside a function — neither $_SERVER, $_POST, $_GET, $_SESSION, or presumably other superglobals, could be overwritten.

您还可以使用提取不覆盖的extract_type选项.

在我看来,最好的选择是简单地为摘录中的所有变量加上前缀:

The best option to use, in my opinion, is simply to prefix all variables from extract:

// $_GET = test=1&name=Joe

extract($_GET, EXTR_PREFIX_ALL, "request_get");

echo $request_get_test; // 1
echo $request_get_name; // Joe

这样,您就不会遇到覆盖问题,但您也知道从阵列中获得了所有东西.

That way you don't have the overwrite problem, but you also know you got everything from the array.

如果您想手动(但仍是动态地)执行此操作,或者想要有条件地仅提取几个变量,则可以使用

If you wanted to do this manually (but still dynamically), or wanted to conditionally extract only a few of the variables, you can use variable variables:

foreach ($_POST as $key => $value) {
    if (isset($$key)) continue;

    $$key = $value;
}

(我使用的示例条件是防止覆盖).

这篇关于用foreach制作的PHP变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆