ds000001 2012-08-09 09:12
浏览 33
已采纳

PHP,禁用自动输入[]到数组

If you post a html form with inputs having names ending with [], php will automatically make these $_POST-values into an array.

For example, without brackets:

<input name="email" value="a" />

var_dump($_POST["email"])    
//string 'a' (length=1)

With brackets:

<input name="email[]" value="a" />
<input name="email[]" value="b" />

var_dump($_POST["email"])    
//array
//  0 => string 'a' (length=1)
//  1 => string 'b' (length=1)

My problem is that previously i didn't know about this so i've been coding my website with the assumption that $_POST-variables always are of type string. Naturally i perform standard input validation but only assuming that the variables already are strings.

So what if a hacker takes one of my normal inputs, like <input name="email" .../> and posts it with the brackets after. Then my code fetching $_POST["email"] would be an array!

I could imagine there are cases where this would be a security problem, for example startsWith-function could work on both strings and arrays. I haven't researched the full implications of it and i don't want to either, i just want to disable the function completely so i can trust all $_POST-variables to always be strings.

Is there any way to disable this function globally or is the only option to find-replace all and add a (string)-cast in front of every access of $_POST?

  • 写回答

1条回答 默认 最新

  • ds2321 2012-08-09 09:20
    关注

    You could just loop through the POST array, and fix them this way. But, since you said you don't ever plan to need this, why not just loop through the _POST array, check if anything is a non-string, and then just throw an exception? No need to give the hypothetical hacker a nice fallback or workaround :)

    foreach($_POST as $val) {
       if (!is_string($val)) {
          throw new InvalidArgumentException('POST arguments should be strings only');
       }
    }
    

    I find the best way to deal with such issues is to be strict, and throw exceptions for cases where a client (browser/evil guy) is clearly messing around with stuff ;)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试