通用PHP表单处理器

时间:2018-02-19 22:33:37

标签: php forms post get request

我正在尝试创建一个优雅的表单处理器,它可以接收POST或GET并循环访问值并显示它们。我想尽可能简单/优雅,并且似乎无法消除GET / POST以支持REQUEST。此代码输出一个额外的值对,我显然不理解GET / POST与REQUEST的关系。当使用POST时,表单包含以前的GET信息(因此它们似乎重叠)并且我不确定如何轻松地不包括cookie(我认为它是什么)值。我知道REQUEST不是最好的方法,但是想知道是否有一种很酷的方式以这种方式使用它。接受其他建议。

<h1>
    Welcome to the Flexiform! AKA "The Formerator"
</h1>
<p>
This form should process any combination of inputs... this iteration doesn't handle identically-named inputs other than checkboxes. Would like to figure that out.
</p>

<?php

if ($_GET || $_POST) 
//if ($_REQUEST)   // why can't I use this?... it seems to process the incoming page as GET on firstload... 
{
    echo ("<h2>Way to '" . $_SERVER['REQUEST_METHOD'] . "' some! </h2>");

    foreach($_REQUEST as $submittedName => $submittedValue)     
    {   
        if (is_array($submittedValue)) // for checkboxes with more than one selected value
        {         
            $submittedValue = implode(', ', $submittedValue); 
        }                

        echo "For the <b>" . $submittedName . " input, you submitted: :</b> " . $submittedValue."</br>";
    }
}
else 
{
    echo ("<h2>Please submit one of the two forms to see some results.</h2>");
}

?>

<hr><hr>
<br>
GET SOME!
<form action= "" method = "get" >
    <input type = "text" name = "name" value = "GIcabad" />
    <input type = "text" name = "name2" value = "GIcabad2" />
    <input type = "text" name = "name3" value = "GIcabad3" />
    <input type = "text" name = "name" value = "GIcabadbb" />
    <input type = "text" name = "name2" value = "GIcabad2bb" />
    <input type = "text" name = "name3" value = "GIcabad3bb" />
    orange:<input type = "checkbox" name = "colors[]" value = "orange" checked />
    red:<input type = "checkbox" name = "colors[]" value = "red" />
    pink:<input type = "checkbox" name = "colors[]" value = "pink" checked />
    <input type = "submit" />       
</form>
<br>
POST SOME!
<form action = "" method= "post" >
    <input type = "text" name = "name" value = "PIcabad" />
    <input type = "text" name = "name2" value = "PIcabad2" />
    <input type = "text" name = "name3" value = "PIcabad3" />
    <input type = "submit" />
</form>

1 个答案:

答案 0 :(得分:0)

您可以在应用程序的主文件上循环一次,并将$_GET$_POST存储在单个变量中(它将像$_REQUEST但是没有{{1} })。然后就可以像这样使用它了

$_COOKIES

修改:表单和结果

<?php 

$input_values = array();
$gpcs = array_merge($_POST, $_GET);
foreach ($gpcs as $key => $value) {
    $input_values[$key] = $value;
}


// Then you can use anywhere in your application like this
echo isset($input_values['username'])? $input_values['username']:'';
echo isset($input_values['password'])? $input_values['password']:'';
echo isset($input_values['user_type'])? $input_values['user_type']:'';

?>