PHP基本注册表

时间:2013-05-16 22:29:05

标签: php session registration

你能帮我吗?我是PHP的初学者,仍然在学习该语言的基础知识。我目前正在学习如何创建会话。当我尝试书中的一个例子时,显然有一个错误。 HTML表单如下所示:

<form action="session_registration_form_script.php" method="post">
    <label for="name">Name:</label>
    <input type="text" name="name" />
    <label for="email">Email:</label>
    <input type="text" name="email" />
    <input type="submit" value="Register" />
</form>

和PHP脚本类似:

<?php

    // Initialize session data
    session_start();

    /*
     * If the user is already registered, display a 
     * message letting them know.
     */

     if(isset($_SERVER['username'])) {
         echo "You're already registered as $_SESSION[username]";
     }

     // Checks if the form was submitted
     else if($_SERVER['REQUEST_METHOD'] == 'POST') {

         /*
          * If both the username and email fields were filled
          * out, save the username in a session variable and 
          * output a thank you message to the browser. To 
          * eliminate leading and trailing whitespace, we use the 
          * trim() function
          */
          if(!empty(trim($_POST['username']))
          && !empty(trim($_POST['email']))) {

              // Store escaped $_POST values in variables 
              $uname = htmlentities($_POST['username']);
              $email = htmlentities($_POST['email']);

              $_SESSION['username'] = $uname;
              echo "Thanks for registering! <br />",
              "Username: $uname <br />",
              "Email: $email <br />";
          }

          /*
           * If the user did not fill out both fields, display 
           * a message letting them know that both fields are 
           * required for registration
           */

           else {
               echo "Please fill out both fields! <br />";
           }
     }

     // If the form was not submitted, dispalys the HTML form

     else {

?>

<?php } ?>

当我在浏览器上输出两个文件时,浏览器报告:致命错误:无法在“文件路径”的写入上下文中使用函数值和代码行

请通过修复此问题来帮忙,并随时添加您可能对我有用的任何内容。在此先感谢...

2 个答案:

答案 0 :(得分:2)

我可以在您的代码中看到许多问题。

 if(isset($_SERVER['username'])) {
     echo "You're already registered as $_SESSION[username]";
 }

应该是

 if(isset($_SESSION['username'])) {
     echo "You're already registered as ".$_SESSION['username'];
 }

此外,当您的表单字段被调用$_POST时,您正在寻找名为username的{​​{1}}变量。

至于您看到的实际错误,这是因为您一起使用nameempty的方式 - 您应该分别检查2。 E.g。

trim

答案 1 :(得分:0)

我认为在检查全局变量之前修剪变量是一个好主意,然后检查它们是否为空

        $uname = trim($_POST['username']);
        $email = trim($_POST['email']);
      if(!empty($uname)  && !empty($email)) {
    //if(!empty($_POST['username']) && !empty($_POST['email']))
    //{

          // Store escaped $_POST values in variables 
          $uname = htmlentities($_POST['username']);
          $email = htmlentities($_POST['email']);

          $_SESSION['username'] = $uname;
          echo "Thanks for registering! <br />",
          "Username: $uname <br />",
          "Email: $email <br />";
      }