将已过滤的$ _POST变量转换为会话变量?

时间:2016-06-16 19:51:54

标签: php session post

我从表单$dbjunk = "Itemid:Quantity:Price:name, itemid2:quantity2:price2:name2"; $parsed = parseItems($dbjunk); foreach($parsed as $p){ list($itemID, $Quantity, $Price, $name) = array_values($p); var_dump($itemID, $Quantity, $Price, $name); } 数组中获取了一些变量,并且我已经在每个值$_POSTtrim()上运行了很多函数。我知道我必须在每个页面的开头添加filter_input(),然后使用它:session_start()

我只是不知道如何从post数组中添加我的值,仍然使用我的卫生功能:

$_SESSION["value"]

我可以这样做吗? $ip = $_SERVER['REMOTE_ADDR']; $name = trim( filter_input( INPUT_POST, "name", FILTER_SANITIZE_STRING ) ); $email = trim( filter_input( INPUT_POST, "email", FILTER_SANITIZE_EMAIL ) ); $state = trim( filter_input( INPUT_POST, "state", FILTER_SANITIZE_STRING ) ); $zip = trim( filter_input( INPUT_POST, "zip", FILTER_SANITIZE_STRING ) ); $product_delivery = trim( filter_input( INPUT_POST, "product_delivery", FILTER_SANITIZE_STRING ) ); $facility_delivery = trim( filter_input( INPUT_POST, "facility_delivery", FILTER_SANITIZE_STRING ) ); $cc_cost = trim( filter_input( INPUT_POST, "cc_cost", FILTER_SANITIZE_STRING ) ); $labor_cost = trim( filter_input( INPUT_POST, "labor_cost", FILTER_SANITIZE_STRING ) ); $util_cost = trim( filter_input( INPUT_POST, "util_cost", FILTER_SANITIZE_STRING ) ); $total_savings = ($product_delivery - $facility_delivery - $cc_cost - $labor_cost - $util_cost); $tons_per_year = trim( filter_input( INPUT_POST, "tons_per_year", FILTER_SANITIZE_STRING ) ); $savings_per_year = ($total_savings * $tons_per_year);

2 个答案:

答案 0 :(得分:3)

作为示例,您可以执行此操作而不是创建纯变量:

session_start();
$_SESSION['name'] = trim( filter_input( INPUT_POST, "name", FILTER_SANITIZE_STRING ) );

答案 1 :(得分:1)

您可以使用filter_input_array()

$defs = array('name'  => FILTER_SANITIZE_STRING,
              'email' => FILTER_SANITIZE_EMAIL);
              //etc...

$_SESSION['data'] = array_map('trim', filter_input_array(INPUT_POST, $defs));

我使用$_SESSION['data']来覆盖其他会话变量。然后只需访问$_SESSION['data']['name']等...

或者替代:

$vals     = array_map('trim', filter_input_array(INPUT_POST, $defs));
$_SESSION = array_merge($_SESSION, $vals);