PHP表单处理算法

PHP Form processing algorithm

作为部分解释,我的思维定式是强烈的程序化,因为我从 60 年代开始就以这种方式编程

我在 PHP 工作,并试图从交互式 404 错误表单开始处理表单。我想要的最小伪代码是:

do {

    OK = true;

    display_form;
        ask for optional name
        ask for optional email address
        ask for optional comments
    on – submit{
        sanitise input 
        validate input (which could be no input since all is optional)
        if one or more inputs invalid  set OK = false
    }
} while (OK == false)

assemble 使用 $_SERVER superglobals 以及输入通过电子邮件发送给网站管理员 使用邮件功能发送 有人 "helpfully" 在 while 之后和最后添加了 curlies——他们真的不属于那里——我的想法是我想对这两个语句执行 "drop through" 只有 在 DO 之后 -- WHILE 完成

邮件程序集可以在单独的文件中,也可以不在

虽然这是一个半特定的问题,但我的假设是,如果我能让它工作,那么让数据库更新工作会更容易。

在我看来,我的整个概念算法都是不正确的,直到我对它进行排序,我才无处可去。几天来我一直在研究这个问题 – Google 在这里指出了一些半相关的答案,所以我试一试。 W3C 示例清楚地显示响应代码 运行,即使输入有问题,这不是我想要的。

您需要在此处进行的主要转换可能是转换为请求-响应执行模型。您不能执行文字 do..while,因为您需要将响应发送回客户端。下一次迭代将由对 PHP 的新请求触发,该请求从头开始,并且不记得任何以前的状态。

所以,在伪代码中,它是这样工作的:

if is POST request:
  validate input, populate error variables

  if input is valid:
    send email with data
    redirect to different page or display "thanks"

form start
for $field in fields:
  output HTML for $field
    maybe highlight if error
    maybe set value to POSTed value to retain data
form end

因此,在访问第一个页面时,它不会是 POST 请求,而是直接进入表单部分。不会有任何错误或现有数据,因此将输出纯格式。提交表单时,相同的代码再次运行,现在进入 if is POST 分支。如果任何值无效,它将再次进入表单,该表单现在还可以输出任何错误消息和现有的提交值。只有当所有值都有效时,服务器才会发送电子邮件并通过重定向到另一个页面退出此 "loop",或者可能只是输出 "Thank you" 注释。

如果您将其正确地分离到 MVC 架构中,您将拥有这些组件:

  • M型号
    • 数据验证
    • 电子邮件发送
  • V观点
    • 输出形式HTML
  • C控制器

    • 一个用于处理 GET 请求,仅调用视图
    • 一个用于处理 POST 请求,主要是做:

      errors = model.validate(data)
      if no errors:
        model.send_email(data)
        redirect()
      else:
        view.display_form(data, errors)
      
    • 某种形式的路由器根据请求URL和方法

    • 调用正确的控制器

这些都可以是单独的函数,或 类,或方法,或只是文件。

下面是页面的最终代码。这是一个基本的 404 错误页面,可能对某些人有用。它应该回答我提供我正在使用的代码的请求

它包括三个我没有提供的文件:

top.php 和 footer.php 和 functions.php

top 生成 HTML head 语句,包括元代码,还包括顶级横幅和菜单,以及建立基本页面格式。

footer-- 在页脚包含之前使用 superglobal 服务器,页面可以提供页面的代码更新日期。以及我们组织的统一名称和注册号

functions.php 提供了一堆重复使用的函数。这段代码中使用了几个小的(相当明显的)函数:

spacer 输出代码以在 table.

中创建一个空单元格

spanCol 在 table 中创建一个跨列单元格,其中包含指定的文本和 指定标签打开和关闭

完整页面在 http://www.vfmc.org.au/notfound.php -- 请不要给我发送太多垃圾邮件。

胆量代码在这里 - 我不认为它很棒,但它的工作感谢这里的帮助:

<?php
$pageTitle = "File Not Found";
$authorName = "Don Gingrich";
$styleSheet = "./css/mainstyle.css";
include_once 'top.php';

require_once "functions.php";
$indicesServer = array(
    'PHP_SELF',
    'HTTP_REFERER',
    'SCRIPT_FILENAME',
    'SCRIPT_NAME',
    'REQUEST_URI',
    'ORIG_PATH_INFO'
);


if (isset($_SERVER['HTTP_REFERER'])) {
    $refering = $_SERVER['HTTP_REFERER'];
} else {
    $refering = NULL;
}
$requested = $_SERVER['REQUEST_URI'];
// $refering = $_SERVER['HTTP_REFERER'];
if ($refering == NULL || $refering == " ") {
    $refering = "referrer field was blank\n - may be due to mis-typing address\n";
}

/* basic "sanitise input" function */
function test_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

function send_webmaster_email($name, $email, $comment, $requested, $refering)
{
    global $sent;
    $subject = "File not Found: $requested";
    $txt = "Trying to access  $requested from $refering\n" . "Visitor comments follow:\n" . $comment;
    if ($name != "") {
        $txt .= "\n\tReporting person's name is: $name\n";
    }
    if ($email != "") {
        $txt .= "\n\tReporting person's email is: $email\n";
    }
    $to = "webmaster@vfmc.org.au";
    $additional_headers = "From: webmaster@vfmc.org.au\r\n";
    mail($to, $subject, $txt, $additional_headers);
    $sent = true;
}

// define variables and set to empty values
$nameErr = $emailErr = "";
$name = $email = $comment = "";
$myError = false;
global $sent;
$sent = false;

/********************************************************
 * Processing code follows -- Only executed after POST
 *
 *******************************************************/

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $requested = $_POST['requested'];
    $refering = $_POST['refering'];
    $requested = test_input($requested);
    $refering = test_input($refering);
    $myError = false;
    if ($_POST["button"] == "Submit") {
        if (empty($_POST["name"])) {
            $name = "";
        } else {
            $name = test_input($_POST["name"]);
            // check if name only contains letters and whitespace
            if (!preg_match("/^[a-zA-Z -]*$/", $name)) {
                $myError = true;
                $nameErr = "Only letters, hyphen, and white space allowed";
            } 
        }

        if (empty($_POST["email"])) {
            $email = "";
        } else {
            $email = test_input($_POST["email"]);
            // check if e-mail address is well-formed
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $myError = true;
                $emailErr = "Invalid email format";
            } 
        }

        if (empty($_POST["comments"])) {
            $comment = "";
        } else {
            $comment = test_input($_POST["comments"]);
        }

        if ($myError == false) {
            send_webmaster_email($name, $email, $comment, $requested, $refering);
        } 
    }
}

echo "\n";
echo "<h2>File Not Found</h2>\n";
echo "<br>\n";
echo "<br>\n";
if ($sent == true ){
    echo "<h5>Email sent to Webmaster, Thank you</h5>\n";
    echo "<br>Use the menu to the left or the back button<br>\n";
    echo "to return to the VFMC site<br>\n";
} else {

    echo "   Unfortunately the file that you have asked for is unavailable.\n";
    echo "<br>\n";
    echo "<br>\n";
    echo "This may mean that the Webmaster has forgotten to load it or the link to it is broken in some way.<br>\n";
    echo "Or, if you typed a page in the browser address bar, you may have mis-typed, remember that everything<br>\n";
    echo "after the <b>www.vfmc.org.au/</b> is CaSeSensitive -- FiresideFiddlers, is spelled as written.<br>\n";
    echo "      <br>\n";
    echo "      <br>\n";
    echo "<h6>Please tell the webmaster by sending a message:</h6>\n";
    echo "      <br>\n";
    echo "      <br>\n";
    $myFile = htmlspecialchars($_SERVER['PHP_SELF']);
    echo "      <form action= \"$myFile\" method=\"post\">\n";
    echo "<input type=\"hidden\" name=\"refering\" value=\"$refering\" />\n";
    echo "<input type=\"hidden\" name=\"requested\" value=\"$requested\" />\n";    
    echo "      <table border=\"0\" cellpadding=\"8\" cellspacing=\"8\">\n";
    echo "      <colgroup>\n";
    echo "         <col width = auto>\n";
    echo "         <col width = auto>\n";
    echo "         <col width = auto>\n";
    echo "      </colgroup>\n";
    echo " <tr>\n";
    spanCol("3", "Your name and email address are optional,<br> but the  webmaster will be unable to respond <br>directly without them", "h5");
    echo "      <tr>\n";
    echo "         <td><label for=\"tswname\">Name</label>:</td>\n";
    echo "         <td><input type=\"text\" name=\"name\" id=\"tswname\" size=\"25\" /></td>\n";
    echo "         <td>\t";
    if ($nameErr == "") {
        echo "(Optional)\n";
    } else {
        echo "<span class=\"error\">*" . $nameErr . "</span>\n";
    }
    echo "</td></tr>\n";
    echo "      <tr>\n";
    echo "        <td>\n";
    echo "           <label for=\"tswemail\">Email address</label>:</td>\n";
    echo "        <td>\n";
    echo "           <input type=\"text\" id=\"tswemail\" name=\"email\" size=\"25\" />\n";
    echo "        </td>\n";
    echo "        <td>\n";
    if ($emailErr == "") {
        echo "(Optional)\n";
    } else {
        echo "<span class=\"error\">*" . $emailErr . "</span>\n";
    }
    echo "</td></tr>\n";
    echo "      <tr>\n";
    echo "      <td>\n";
    echo "      <label for=\"tswcomments\">Comments</label></td>\n";
    echo "      <td colspan=\"2\">\n";
    echo "      <textarea rows=\"15\" cols=\"45\" name=\"comments\" id=\"tswcomments\"></textarea>\n";
    echo "      </td>\n";
    echo "      </tr>\n";
    echo "      <tr>\n";
    echo "      <td align=\"center\" colspan=\"2\">\n";
    echo "      <input type=\"submit\" name=\"button\" value=\"Submit\" /><br>\n";
    echo "      </td>\n";
    echo "      </tr>\n";
    echo "      </table>\n";
    echo "      </form>\n";

}

echo "      <br>\n";
echo "      <br>\n";
echo "      <br>\n";
echo "      <br>\n";
echo "</td>\n";
echo "</tr>\n";

                $filename = $_SERVER['SCRIPT_NAME'];
                require_once "footer-code.php";             
?>

</tbody>
</table> <!--PWK-EDIT END FOOTER-->
</body>
</html>