通过复选框将数组发送到$ _POST

时间:2012-09-15 18:50:33

标签: php post global-variables

我在朋友服务器上测试我的php代码时遇到问题。(它在我的本地服务器上工作正常)。

有一个包含checkbox输入的表单,如

提交表格时

  1. 在我的服务器中:print_r($ _ POST)打印:
    Array ( [names] => Array ( [0] => john [1] => sam ) )
  2. 在他的服务器中:print_r($ _ POST)打印:
    Array ( [names] => Array )
  3. Array是一个不是数组的字符串!

    他的php版本是5.2.17

    <form method="post">
    john <input type="checkbox" name="names[]" value="john"/>
    sam <input type="checkbox" name="names[]" value="sam"/>
    moh <input type="checkbox" name="names[]" value="moh"/>
    <input type="submit"/>
    </form>
    <?php 
    print_r($_POST);
    ?>
    

2 个答案:

答案 0 :(得分:3)

从第一篇文章的评论中得到答案:

你这样做是错误的:$_POST = array_map('stripslashes',$_POST);

这正是导致此问题的原因,在stripslashes的每个元素上使用$_POST是worng,stripslashes对字符串起作用,字符串中的数组等于“Array”,这样函数正在将数组转换为"Array",你应该编写一个自定义函数并检查元素是否不是数组使用stripslashes或者是否再次使用array_map,如下所示:

<?php

function stripslashes_custom($value){
    if(is_array($value)){
        return array_map('stripslashes_custom', $value);
    }else{
        return stripslashes($value);
    }
}

$_POST = array_map('stripslashes_custom', $_POST);

?>

条带化函数的数组输入结果不同的原因可能是由于不同的php版本......

答案 1 :(得分:0)

如您所知,您无法使用magic_quotes_gpc更改ini_set()。如果php.ini中的magic_quotes_gpcOff,则会跳过下面的代码,因为不需要条带化。否则对于magic_quotes_gpc = On,此函数将以递归方式执行,以剥离数组中的所有字符串,而不是使用array_map()

我已经使用PHP 5.2.17(模式On)和5.3.10(模式Off)进行了测试。

所以我们在这里使用简单的代码:

<?php

function stripslashesIterator($POST){
    if ($POST){
        if (is_array($POST)){
            foreach($POST as $key=>$value){
                $POST[$key]=stripslashesIterator($POST[$key]);
            }
        }else{
            return stripslashes($POST);
        }
        return $POST;
    }
}

//Init $_POST, $_GET or $_COOKIE
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() === 1){
    $_POST=stripslashesIterator($_POST);
}

?>
相关问题