c# 用户帐户临时文件夹_注册帐户,上传文件以供批准,以及查看和下载批准的文件

c# 用户帐户临时文件夹

在你开始前

在本系列的第一部分中,您将学习基本PHP语法,形式和功能,以及如何通过PHP应用程序连接和使用MySQL或任何其他数据库。

关于本教程

本教程将引导您使用PHP构建一个简单的工作流应用程序。 用户将注册一个帐户,上传文件以供批准,以及查看和下载批准的文件。 指定为管理员的用户可以查看和批准上载的文件,以使文件对所有用户可用。 本系列的第2部分第3部分探讨HTTP密码保护,XML,JSON和其他相关问题。

本教程包括以下内容:

  • 创建一个基本页面
  • 变量,循环和if-then语句
  • 功能
  • 连接到数据库
  • 使用包含文件
  • 工具类

谁应该学习本教程?

如果您是想学习如何使用PHP来构建基于Web的应用程序的程序员,请从三部分系列的教程的第1部分开始。 PHP是一种基于脚本的语言,易于学习,但仍使您能够构建具有强大功能的复杂应用程序。 本教程将引导您使用HTML表单创建基本PHP页面。 它还说明了如何访问数据库。

先决条件

本教程假定您没有PHP经验。 实际上,虽然熟悉HTML的概念对您很有用,但本教程不需要其他编程。 随意下载本教程中使用的源代码。

系统要求

您需要安装并可用的Web服务器,PHP和数据库。 如果您拥有托管帐户,则只要服务器已安装PHP V5并有权访问MySQL数据库,就可以使用它。 否则,下载并安装以下软件包:

XAMPP
无论您使用的是Windows®,Linux®还是Mac,获取本教程所有必需软件的最简单方法是安装XAMPP,其中包括Web服务器,PHP和MySQL数据库引擎。 如果选择这种方式,只需安装,然后运行控制面板以启动Apache和MySQL进程。 您还可以选择单独安装各个部件,但是请记住,然后必须将它们配置为可以一起工作-XAMPP已经解决了这一步骤。
网络服务器
如果选择不使用XAMPP,则Web服务器有多个选项。 如果您使用的是PHP 5.4(在撰写本文时,XAMPP仅使用PHP 5.3.8),则可以使用内置的Web服务器进行测试。 但是,对于生产而言,我将假设您使用的是Apache Web服务器2.x版。
PHP 5.x
如果您不使用XAMPP,则需要单独下载PHP5.x。 标准发行版包含本教程所需的一切。 随意下载二进制文件; 您将不需要本教程的源代码(或者永远不需要,除非您想破解PHP本身)。 本教程是在PHP 5.3.8上编写和测试的。
的MySQL
该项目的一部分涉及将数据保存到数据库,因此您也将需要其中之一。 同样,如果已安装XAMPP,则可以跳过此步骤,但是,如果选择这样做,则可以单独安装数据库。 在本教程中,我将重点介绍MySQL,因为它在PHP中非常常用,因此,如果选择这种方法,则可以下载并安装社区服务器。

基本PHP语法

让我们看一下用PHP创建页面的基础。 在下一节中,您将研究如何使用HTML表单向PHP提交信息,但是首先您需要了解如何执行一些基本任务。

基本PHP页面

首先,打开文本编辑器并创建最基本PHP页面(请参见清单1 )。

清单1.基本PHP页面
<html>
   <title>Workflow Registration</title>
   <body>
      <p>You entered:</p>
      <p><?php echo "Some Data"; ?></p>
   </body>
</html>

总体而言,您有一个简单HTML页面,其中单个PHP部分以粗体显示。 当服务器遇到<?php符号时,它知道评估后面的命令,而不是简单地将它们发送到浏览器。 它会一直遵循以下说明(您稍后会看到),直到该节结束为止,如?>符号所示。

在这种情况下,您只有一个命令echo ,它告诉服务器输出指示的文本。 这意味着,如果您保存页面并使用浏览器调用它(稍后将进行操作),浏览器将收到清单2所示的页面。

清单2.浏览器收到PHP页面
<html>
   <title>Workflow Registration</title>
   <body>
      <p>You entered:</p>
      <p>Some Data</p>
   </body>
</html>

要查看实际效果,请将文件另存为registration_action.php并将其移至服务器的文档根目录。 对于XAMPP,此目录为<XAMPP_HOME> / htdocs。 (对于Apache,这可能是/ var / www / html。)

要调用此页面,请打开浏览器并将其指向http://localhost/registration_action.php 。 您应该看到类似于图1的内容

图1. echo命令的输出
echo命令的输出

恭喜,您已经编写了第一个PHP页面。 您将使用该语言进行的所有其他操作都基于此。

变数

变量是数据的占位符。 您可以为其分配一个值,从此以后,每当PHP遇到您的变量时,它将使用该值代替。 例如,将页面更改为清单3。

清单3.在PHP页面中使用变量
<html>
   <title>Workflow Registration</title>
   <body>
      <p>You entered:</p>

         <?php
         $username = "nick";
         $password = "mypassword";

         echo "<p>Username = " . $username . "</p>";
         echo "<p>Password = " . $password . "</p>";
      ?>

   </body>
</html>

首先,请注意,每行必须以分号结尾。 另外,请注意,您使用句点( . ) 连接文本或将其放在一起。 您可以通过这种方式将任意数量的字符串或文本块组合在一起。

关于变量的更多说明:在PHP中,变量名称区分大小写,因此$UserName$username是不同的变量。

一致的命名约定(例如确定所有变量都为小写字母)可以大大防止难以捕获的错误。

保存文件(并在需要时上传)并刷新浏览器。 您应该看到类似于图2的内容

图2.刷新后的浏览器
浏览器刷新

在继续之前,让我们看一看一种特殊的变量。

常数

您可以根据需要多次更改变量的值,但是有时您希望设置一个变量,但期望值不会更改。 这些项目不称为变量,它们是常量 。 例如,您可能想要定义一个代表每个页面标题的常量,如清单4所示。

清单4.定义一个常量
<?php
   define("PAGE_TITLE", "Workflow Registration");
?>
<html>
   <title><?php echo PAGE_TITLE ?></title>
   <body>
      <p>You entered:</p>
      ...

(现在看来有些琐碎,但是稍后您将看到如何在多个页面上使用此定义。)

请注意,您正在定义常量的名称及其值。 如果在定义后尝试更改其值,则会出现错误。

还要注意,当引用常量时(如title元素中一样),您不会使用美元符号,而只是使用常量的名称。 您可以根据自己的喜好命名常量,但是习惯上使用所有大写字母。

稍后,当您了解对象时,您会发现一种更紧凑的指定常量的方式。

更轻松的输出

到现在为止,您已经使用echo命令输出信息,但是当您仅要输出一条数据时,此命令可能有点麻烦。

幸运的是,PHP提供了一种更简单的方法。 通过使用输出运算符<?= ?>构造,可以指定要输出的信息,如清单5所示。

清单5.使用输出运算符
<?php
   define("PAGE_TITLE", "Workflow Registration");
?>
<html>
   <title><?= PAGE_TITLE ?></title>
   <body>
      <p>You entered:</p>
      ...

请注意,使用输出运算符时,请不要在信息后加上分号。

稍后,您将了解其他基本PHP结构,例如if-then语句,因为在构建应用程序时将需要它们。

PHP和表格

在本节中,您将研究数组以及使用表单数据的方式。 您还将了解如何控制PHP脚本的流程,例如循环和if-then语句。

在PHP中创建和使用表单

开发人员创建了PHP作为Web编程语言。 实际上,虽然可以从命令行运行PHP,但是很少有人在Web应用程序领域之外使用该语言。 结果是,作为PHP程序员,您最常见的任务之一就是使用Web表单。

您使用HTML创建Web表单,并且当用户提交表单时,浏览器会将一系列信息发送到服务器。

用HTML创建表单

首先为您的应用程序创建注册页面。 最终,用户将输入他们的信息,然后您将对其进行验证或检查其完整性,然后再将其保存在数据库中。 现在,只需创建基本表单即可。 创建一个名为registration.php的新文件,并在清单6中添加以下内容。

清单6.创建注册页面
<html>
   <head><title>Workflow System</title></head>
   <body>
      <h1>Register for an Account:</h1>

      <form action="registration_action.php" method="GET">

         Username: <input type="text" name="name" /><br />
         Email: <input type="text" name="email" /><br />
         Password: <input type="password" name="pword" /><br />
         <input type="submit" value="GO" />

      </form>

   </body>
</html>

在这里,您有一个简单的表单(包含在form元素中),其中包含两个文本输入:密码输入和提交按钮。 将文件保存在文档根目录中(带有registration_action.php)。 要打开它,将浏览器指向http://localhost/registration.php并在每个字段中键入。 您应该看到类似图3的内容

图3.注册一个帐户表单
注册帐户表格

请注意,密码框不会显示您键入的实际内容。 这种形式的表单元素意在掩盖可能从您的肩膀上方抬起头来的人的敏感信息。 但是,当你点击GO按钮,会发生什么?

提交表格

创建表单时,您将实际的form元素创建为: <form action="registration_action.php" method="GET">

该元素有两条信息。 第一个是action ,它告诉浏览器将信息发送到哪里 。 在这种情况下,它将转到您先前创建的页面registration_action.php。 第二种method ,告诉浏览器如何发送数据。

让我们看看它是如何工作的。 在一些数据填充(如果你还没有的话),然后点击GO按钮。 您应该看到类似于图4的结果。

图4.输出数据
输出数据

在这种情况下,请注意该信息似乎不正确-这不是您实际提交的信息-但这是因为您尚未调整该页面以查看正在提交的数据。 但是请看一下URL: http://localhost/registration_action.php?name=nickChase&email=nickchase%40noTooMi.com&pwor d=asupersecretpassword

请注意,对于每个具有名称的表单元素,URL中都有一个“名称/值”对,以“&”号分隔。 该URL看起来像这样,因为您使用了GET方法,该方法告诉浏览器以这种方式发送数据。 您还将看到Using POST ,其中涉及到发送数据的方式有所不同,但首先看一下实际上是从PHP页面中检索此数据的方法。

访问表格数据

现在,您已经提交了表单,您必须将数据放入实际的响应页面registration_action.php中。 对清单7进行清单7所示的更改。

清单7.将数据获取到响应页面
...
   <body>
      <p>You entered:</p>

      <?php
         $username = $_GET['name'];
         $password = $_GET['pword'];s

         echo "<p>Username = " . $username . "</p>";
         echo "<p>Password = " . $password . "</p>";
      ?>

   </body>
</html>

您正在做的是将命名值从$_GET数组中拉出。 稍后将有更多关于数组的信息,但是现在请注意,如果刷新浏览器,则会出现实际答案, 如图5所示。

图5.浏览器中的正确信息
在浏览器中更正信息

您可以按名称来提取任何一条提交的信息,但是由于这是一个数组,因此您还有其他选择。

数组

PHP使您能够创建数组或值列表,从而使您可以一次轻松地全部引用一组值。 例如,您可以创建一个值数组并将其输出到页面(请参见清单8 )。

清单8.创建一个值数组
$formnames = array("name", "email", "pword");
echo "0=".$formnames[0]."<br />";
echo "1=".$formnames[1]."<br />";
echo "2=".$formnames[2]."<br />";

array()函数返回一个值,该值是传递给它的值的数组。 (函数将在以后处理,但是现在,请了解您已调用它,并且它返回分配给变量的值。)

请注意,第一个值的索引为0,而不是1。还要注意,您还可以通过在数组变量名称后面的方括号中添加索引来指定所需的值。 该脚本产生清单9中所示的输出。

清单9.数组输出
0=name<br />
1=email<br />
2=pword<br />

此操作类似于您访问表单值的方式,这绝非偶然。 $_GET变量是一种特殊类型的数组,称为关联数组,这意味着每个值都具有一个key ,而不是数字索引。

提交表单时,实际上是在创建一个清单10所示的数组。

清单10.提交表单将创建一个数组
$_GET = array("name" => "roadnick",
 "email" => "ibmquestions@nicholaschase.com",
 pword" => "supersecretpassword");

这就是使您能够提取单个值的原因,例如$_GET["name"] 。 但是,您不必单独进行此操作。

通过数字获取阵列信息

关联数组在处理数据时非常方便,但是经常会出现一些情况,其中您实际上并不知道数组的结构。 例如,您可能正在构建一个通用数据库例程,该例程从查询中接收一个关联数组。

幸运的是,PHP提供了两个函数,使您的生活更加轻松(请参见清单11 )。

清单11. array_keys()array_values()函数
...
<body>
   <p>You entered:</p>

      <?php
      $form_names = array_keys($_GET);
      $form_values = array_values($_GET);

      echo "<p>" . $form_names[0] . " = " . $form_values[0] . "</p>";
      echo "<p>" . $form_names[1] . " = " . $form_values[1] . "</p>";
      echo "<p>" . $form_names[2] . " = " . $form_values[2] . "</p>"; 
   ?>

</body>
...

array_keys()array_values()函数每个都返回常规的数字信息数组,因此您可以使用这些数组通过数字索引提取数据, 如图6所示。

图6.使用数字索引提取数据的数组
使用数字索引提取数据

不过,必须有一种更方便的方法。 例如,如果您实际上不知道有多少个值怎么办? PHP提供了几种处理关联数组的方法,最方便的方法取决于您已经拥有的信息。 接下来,让我们看看另外两种完成同一任务的方式。

使用for-next循环

PHP中的一项非常常见的任务是遍历多个值。 您可以使用for-next循环轻松完成此操作。 for-next循环根据其定义遍历多个值。 让我们看一下清单12中的循环示例。

清单12. for-next循环
for ($i = 0; $i < 10; $i++) {
   echo $i . " ";
}

PHP最初为$i分配了0值,因为这是在循环开始时指定的值。 只要$i小于10,循环就会继续,并且每次循环执行时,PHP都会将$i的值加一。 此输出:

0 1 2 3 4 5 6 7 8 9

这意味着,如果您可以找出$_GET数组中有多少个值(可以做到),就可以轻松地遍历表单提供的所有值,如清单13所示。

清单13.遍历表单提供的所有值
...
<body>
   <p>You entered:</p>

   <?php
      $form_names = array_keys($_GET);
      $form_values = array_values($_GET);

         for ($i = 0; $i < sizeof($_GET); $i++) {
         echo "<p>".$form_names[$i]." = " . $form_values[$i] . "</p>";
      }     
   ?>

</body>
...

sizeof()函数为您提供$_GET数组中的值数量。 您可以使用该数据来告诉您何时停止循环, 如图7所示。

图7.使用sizeof函数停止循环
使用sizeof函数停止循环

使用$_GET作为关联数组,您实际上还有另一个选择: foreach循环。

使用foreach循环

关联数组在PHP中是如此普遍,以至于该语言还提供了一种获取数据的简便方法,而无需经历提取键和值的过程。 相反,您可以使用foreach循环,该循环可以直接操作数组。 考虑清单14中的代码。

清单14.使用foreach循环
...
   $form_values = array_values($_GET);

   foreach ($_GET as $value) {
      echo "<p>" . $value . "</p>";
   }
?>
...

PHP第一次执行循环时,它将获取$_GET数组中的第一个值,并将该值分配给$value ,然后输出。 然后,它返回到循环的顶部,并将下一个值分配给$value ,对$_GET每个值(因此,名称)执行此操作。 最终结果是清单15中所示的输出。

清单15. foreach循环的输出
<p>roadnick</p>
<p>ibmquestions@nicholaschase.com</p>
<p>supersecretpassword</p>

但是,更方便的是提取值和键的能力,如清单16所示。

清单16.提取值和键
...
   $form_values = array_values($_GET);

   foreach ($_GET as $key=>$value) {
      echo "<p>" . $key . " = " . $value . "</p>";
   }
?>
...

这将带您回到原始结果(请参见图8 )。

图8.原始结果
原始结果

多种形式的价值

在表单值的主题上,您需要处理偶尔出现的情况:当多个表单值具有单个名称时。 例如,由于用户看不到他们在键入什么密码,因此您可以通过将清单17中的代码添加到registration.php中,使他们键入两次以确认他们没有输入错误:

清单17.单个名称的多个表单值
...
Username: <input type="text" name="name" /><br />
Email: <input type="text" name="email" /><br />
Password: <input type="password" name="pword[]" /><br />
Password (again): <input type="password" name="pword[]" /><br />
<input type="submit" value="GO" />
...

请注意, pword字段的名称已稍有更改。 因为您将要检索多个值,所以需要将密码本身视为一个数组。 是的,这意味着您拥有另一个数组的数组值。 因此,如果您现在提交表单,它将创建一个URL: http://localhost/registration_action.php?name=nickChase&email=nickchase%40noTooMi.com &pword%5B%5D=asupersecretpassword&pword%5B%5D=asupersecretpassword

(值%5B%5D[]的url编码版本。)

提交表单与创建数组相同(请参见清单18 )。

清单18.提交表单将创建一个数组
$passwords = array("asupersecretpassword", "asupersecretpassword");
$_GET = array("name"=>"nickChase",
                "email"=>"nickChase@noTooMi.com",
                "pword"=>$passwords);

所有这些意味着,如果您想查看密码值,则需要将它们作为数字数组进行访问,如清单19所示。

清单19.作为数字数组访问密码值
...
foreach ($_GET as $key=>$value) {
   echo "<p>".$key." = " . $value . "</p>";
}

$passwords = $_GET["pword"];
echo "First password = ".$passwords[0];
echo "<br />";
echo "Second password = ".$passwords[1];
...

如果提交表单(或刷新页面),则可以看到不同之处, 如图9所示。

图9.提交表单
提交表格

注意,密码字段现在输出为Array ,但是您可以直接访问其值。

使用GET与使用POST

到目前为止,您一直在使用GET方法提交数据,如您所见,该方法将数据直接放在URL中。 现在,有时候这是适当的,有时不是。 例如,您可以使用此技术来模拟使用链接提交表单的方法,但是,如果您有大量数据(例如,来自用户可以在其中输入评论的textarea ),则该技术不是最佳的方法。完成您的目标。 一方面,Web服务器通常会限制它们在GET请求中接受的字符数。

另一件事,好的技术和标准的要求,说你永远不会使用GET对于具有操作的“副作用”,或者真正做什么事情。 例如,现在您仅查看数据,因此没有副作用影响操作。 但是,最终,您将要把数据添加到数据库中,根据定义,这是一个副作用。

许多Web程序员并不了解此特定限制,这可能会导致问题。 使用GET (尤其是将其用作URL)可能会导致系统多次执行操作,因为用户已为页面添加了书签,或者由于搜索引擎已为URL编制索引,而没有意识到它实际上是在更新数据库或执行某些其他操作。

因此,在这些情况下,您将不得不使用POST

使用POST

实际上,使用POST方法而不是GET方法非常简单。 首先,您需要更改registration.php页面,如清单20所示。

清单20.在注册页面上使用POST方法而不是GET
...
<h1>Register for an Account:</h1>
<form action="registration_action.php" method="POST">

   Username: <input type="text" name="name" /><br />
...

现在,当您提交表单时,URL是空的:

http://localhost/registration_action.php

要检索数据,您有两种选择。 第一种是使用$_POST数组而不是registration_action.php中的$_GET数组,如清单21所示。

清单21.使用$_POST数组检索数据
...
<body>
   <p>You entered:</p>

   <?php
      foreach ($_POST as $key=>$value) {
         echo "<p>".$key." = " . $value . "</p>";
      }

      $passwords = $_POST["pword"];
      echo "First password = ".$passwords[0];
      echo "<br />";
      echo "Second password = ".$passwords[1];
   ?>
</body>
...

您可以使用与$_GET数组完全相同的方式来使用$_POST数组。

这种方法的好处是,您可以精确控制脚本所要查看的内容。 不好的是,如果您想通过在URL中放入一些内容进行调试,则必须更改脚本。 解决此问题的一种常用方法是使用第三个数组$_REQUEST ,该数组包含在两个位置传递的数据(请参见清单22 )。

清单22.使用$_REQUEST数组进行调试
...
   <?php
      foreach ($_REQUEST as $key=>$value) {
         echo "<p>".$key." = " . $value . "</p>";
      }

      $passwords = $_REQUEST["pword"];
      echo "First password = ".$passwords[0];
...

错误检查:if-then语句

在继续之前,如果您不确定两次尝试是否匹配,则要求用户两次键入密码毫无意义。 为此,您将使用if-then语句,如清单23所示。

清单23.使用if-then语句
...
$passwords = $_POST["pword"];
echo "First password = ".$passwords[0];
echo "<br />";
echo "Second password = ".$passwords[1];

if ($passwords[0] == $passwords[1]) {
   echo "<p>Passwords match. Thank you.</p>";
} else {
   echo "<p>Passwords don't match. Please try again.</p>";
}
...

在if-then语句中,如果括号中的表达式(在此示例中, $passwords[0] == $passwords[1] )为true,则PHP将在第一组括号中执行该语句。 如果为假,则为假。 在这种情况下,您还包括了在语句为false时要采取的另一种措施。

请注意,您不是说$passwords[0] = $passwords[1]和一个等号,而是说$passwords[0] == $passwords[1]和一个双等号。 双等号是比较运算符。 它实际上检测到两者是否相等。 单等号是赋值运算符。 使用单个等号,当您执行该语句时,PHP会简单地将$passwords[1]的值分配给$passwords[0] ,这显然不是您想要的。

在这种情况下,如果密码不匹配,页面会向用户发出警告, 如图10所示。

图10.密码不匹配时发出的警告
密码不匹配

另外两个方便的运算符是and运算符( && )和or运算符( || )。 清单24显示了它们的作用。

清单24. and和the 或运算符
if (($today == "Monday") && ($status == "Not a holiday")) {
   echo "GO TO WORK!!!";
}

在这种情况下,仅当今天是星期一而不是假日时,该表达式才为真。 如果任何组件为true,则or运算符返回true。

功能

现在该深入了解一下,了解在PHP中实现函数如何可以帮助您节省时间。

创建一个功能

当您构建任何大小的应用程序时,通常都会在操作,计算或您反复使用的其他代码段中运行。

在这种情况下,采用代码并使用它创建一个函数会很有帮助。 例如,您可以进行密码验证并将其放入一个单独的函数中,如清单25所示。

清单25.创建一个函数
...
<body>
   <p>You entered:</p>

   <?php

      function checkPasswords($firstPass, $secondPass){

         if ($firstPass == $secondPass) {
            echo "<p>Passwords match. Thank you.</p>";
         } else {
            echo "<p>Passwords don't match. Please try again.</p>";
         }

      }

      foreach ($_POST as $key=>$value) {
         echo "<p>".$key." = " . $value . "</p>";
      }

      $passwords = $_POST["pword"];
      echo "First password = ".$passwords[0];
      echo "<br />";
      echo "Second password = ".$passwords[1];

   ?>
</body>

...

当服务器处理此页面时,它会到达function关键字,并且知道除非特别请求,否则不应执行该部分代码。 因此, foreach循环仍然是此页面上执行的第一件事, 如图11所示

图11.执行foreach循环
执行foreach循环

那么,您实际上如何使用该功能?

调用函数

要调用函数,请使用其名称,并在其后加上一对括号。 如果您希望有任何参数(在这种情况下),请放在括号中,如清单26所示。

清单26.调用一个函数
...
<body>
   <p>You entered:</p>

      <?php

      function checkPasswords($firstPass, $secondPass){
         if ($firstPass == $secondPass) {
            echo "<p>Passwords match. Thank you.</p>";
         } else {
            echo "<p>Passwords don't match. Please try again.</p>";
         }
      }

      foreach ($_POST as $key=>$value) {
         echo "<p>".$key." = " . $value . "</p>";
      }

      $passwords = $_POST["pword"];
      echo "First password = ".$passwords[0];
      echo "<br />";
      echo "Second password = ".$passwords[1];

      checkPasswords($passwords[0], $passwords[1]);

   ?>
</body>

...

当PHP执行此页面时,它从foreach循环开始,输出密码,然后执行checkPasswords()函数,将两次密码尝试作为参数传递(参见图12 )。 (您也可以传递数组,并从函数中提取单个值。)

图12.在foreach循环之后执行checkPasswords()函数
执行checkPasswords()

如果您使用其他某些语言编程,则可以将其更多地视为子例程,因为目标是执行代码块,而不是返回值。 您可以以任何一种方式使用函数,接下来将要介绍。

返回值

除了使用函数执行大量代码外,使用函数执行某种操作并返回值通常也很有帮助。 例如,您可以创建一个执行许多动作的验证函数,然后返回一个指示是否存在问题的值(请参见清单27 )。

清单27.返回一个值
...
<body>
   <p>You entered:</p>

   <?php
         function validate($allSubmitted){

         $message = "";

         $passwords = $allSubmitted["pword"];
         $firstPass = $passwords[0];
         $secondPass = $passwords[1];
         $username = $allSubmitted["name"];

         if ($firstPass != $secondPass) {
            $message = $message."Passwords don't match<br />";
         }
         if (strlen($username) < 5 || strlen($username) > 50){
            $message = $message."Username must be \
            between 5 and 50 characters<br />";
         }

         if ($message == ""){
            $message = "OK";
         }

         return $message;

      }


      function checkPasswords($firstPass, $secondPass){

...

该函数将$_POST数组作为参数,并提取其需要查看的信息。 您从一个空的$message字符串开始,如果密码不匹配,或者用户名长度(由strlen()或string length ,函数返回)错误,则将文本添加到$message字符串。 如果密码匹配且用户名长度正确,则会显示一个空字符串,为该字符串分配一个“ OK”值,以便您可以在页面正文中对其进行检查(下一个)。

验证数据

您已经创建了一个函数,该函数根据用户的输入是否适当返回一个值,因此现在可以测试该值(参见清单28 )。

清单28.验证数据
...
   echo "<br />";
   echo "Second password = ".$passwords[1];

      if (validate($_POST) == "OK") {
      echo "<p>Thank you for registering!</p>";
   } else {
      echo "<p>There was a problem with your registration:</p>";
      echo validate($_POST);
      echo "<p>Please try again.</p>";
   } 

?>
...

在if-then语句中,检查validate()函数返回的值。 如果它等于“ OK”,则提供一条简单的感谢消息; 否则,将显示消息本身, 如图13所示。

图13.显示警告消息
显示警告信息

首先请注意,此技术对于测试特定结果更加方便。 如果您尝试将所有这些条件放在if-then语句中,您能想象混乱吗? 另外,请注意,该函数在这里被调用了两次,效率不高。 在生产应用程序中,您可以将返回值分配给变量,然后进行检查,而不是不必要地重复操作。

现在,您已经知道数据是正确的,您可以将其输入数据库。

连接并使用数据库

您的许多PHP应用程序都将需要使用数据库,这是我在本节中介绍的内容。

选择数据库还是不选择数据库:使用PHP数据对象(PDO)

因为它是免费提供的,并且配置已包含在许多PHP的托管计划和发行版中,所以MySQL通常是绝大多数PHP应用程序的首选数据库。 很好,除了生成的代码特定于MySQL。

不幸的是,这意味着如果更进一步,您需要更改数据库(例如更改为Sqlite,IBM®DB2®或Oracle),则必须重写所有与数据库相关的代码。 幸运的是,随着PHP数据对象或PDO的出现,以及将其包含在5.3版以上PHP核心安装中,可以编写与特定数据库无关的与PHP数据库相关的代码。

它的工作方式是使用PDO编写数据库访问代码,然后包含特定于数据库的PDO驱动程序。 要更改数据库,您只需要包括适当的驱动程序并更改数据库“连接字符串”。

在这种情况下,您将使用PDO连接到MySQL数据库。 如果您使用的是XAMPP,则无需进行任何其他配置。 默认情况下启用MySQL驱动程序。 如果您不使用XAMPP,则需要确保在php.ini中未注释以下行: extension=php_pdo.dllextension=php_pdo_mysql.dll

这些dll应该已经存在于php.ini文件中指定为extension_dir

现在,您需要照顾数据库本身。

配置

在继续之前,您需要创建一个数据库,添加一个表并创建一个有权访问该数据库的新用户。

如果已经安装了XAMPP,则要进入MySQL控制台,请输入清单29中的命令。

清单29.进入MySQL控制台
cd <XAMPP_HOME>
mysql/bin/mysql -h localhost -u root

(如果单独安装了MySQL并为root用户创建了密码,则需要添加-p参数并在要求时输入密码。)

进入控制台后,输入清单30中的代码。

清单30.创建数据库
create database workflow;

use workflow;

create table users (id int auto_increment primary key, username varchar(50),
                    email varchar(255), password varchar(50));

show tables;

最终输出应类似于清单31

清单31.最终输出
>+--------------------+
| Tables_in_workflow |
+--------------------+
| users              |
+--------------------+
1 row in set (0.00 sec)

最后,添加一个新用户wfuser ,其密码为wfpass (请参见清单32 )。

清单32.添加新用户
GRANT ALL PRIVILEGES ON *.* TO 'wfuser'@'localhost'
IDENTIFIED BY 'wfpass' WITH GRANT OPTION;

现在,您可以继续实际使用数据库。

连接到数据库

创建几乎任何大小的Web应用程序而不必与某种数据库进行交互实际上是不可能的。 在示例应用程序中,您将使用MySQL数据库存储用户名和密码信息。 在本节中,您将向注册操作页面添加功能,以便它检查所提交的用户名是否唯一,如果有则将数据插入表中。 您还将查看显示数据库中已经存在的信息。 最后,您将创建应用程序的登录页面。

首先连接到您在“ 设置”中创建的工作流数据库(请参见清单33 )。

清单33.连接到工作流数据库
...
if (validate($_POST) == "OK") {

   $dbh = new PDO('mysql:host=localhost;dbname=workflow', 'wfuser', 'wfpass');

   echo "<p>Thank you for registering!</p>";

} else {
   echo "<p>There was a problem with your registration:</p>";
...

在这里,您正在创建一个新对象$dbh 。 在本系列的后续部分中,您将学习有关对象的更多信息,但是到目前为止,您可以将对象视为要使用的功能的集合。

该对象使用数据库的“连接字符串”( mysql:host=localhost;dbname=workflow )以及用户名和密码来连接到MySQL数据库。 (不同的数据库具有不同类型的连接字符串。)

假设一切顺利,此连接将保持打开状态,直到您销毁对象(很快就会看到)或页面完成处理为止。

准备插入用户数据。

插入记录

现在是时候将数据添加到您先前创建的users表中了。 要添加数据,您将创建一条SQL语句,将数据插入该表中,然后执行该语句。

该语句的形式如清单34所示。

清单34.将数据插入表中SQL语句
insert into users (username, email, password) values
                  ('roadnick', 'ibmquestions@nicholaschase.com', 'supersecretpassword')

现在,如果在创建表时特别注意,您可能想知道id列发生了什么。 您将第一列指定为AUTO_INCREMENT ,因此,如果您不进行此操作(如此处所做的那样),MySQL将自动使用下一个可用的整数填充它。

但是实际上插入数据不仅需要构建insert语句。 像清单35那样做是惯例。

清单35.插入数据的旧方法
$sql = "insert into users (username, email, password) values \
                  ('".$_POST["name"]."', '".$_POST["email"]."', '".$passwords[0]."')

但是,这种构造很容易受到称为“ SQL注入”的黑客技术的攻击,这可能导致数据被盗或删除。 幸运的是,使用PDO而不是直接访问数据库的优点之一是可以轻松使用“准备好的语句”,从而消除了这种风险。 运作方式如下:

您需要创建或准备该语句(请参见清单36 )。

清单36.创建语句
...
if (validate($_POST) == "OK") {

   $dbh = new PDO('mysql:host=localhost;dbname=workflow', 'wfuser', 'wfpass');

   $stmt = $dbh->prepare("insert into users (username, email, password) \
                                        values (:name, :email, :pword)");

   echo "<p>Thank you for registering!</p>";

} else {
   echo "<p>There was a problem with your registration:</p>";
...

注意->结构。 这就是引用对象的功能或属性的方式。 在这种情况下,您要告诉数据库准备带有三个参数的插入语句。

接下来,您需要将变量“绑定”到参数上(参见清单37 )。

清单37.将变量绑定到参数
...
   $stmt = $dbh->prepare("insert into users (username, email, password) \
                                        values (?, ?, ?)");

   $stmt->bindParam(1, $name);
   $stmt->bindParam(2,  $email);
   $stmt->bindParam(3, $pword);

   echo "<p>Thank you for registering!</p>";

} else {
...

此步骤告诉数据库获取变量中的任何值,并将其用于该特定参数。 然后,设置值并执行该语句,如清单38所示。

清单38.设置值并执行语句
...
   $stmt = $dbh->prepare("insert into users (username, email, password) \
                                        values (?, ?, ?)");

   $stmt->bindParam(1, $name);
   $stmt->bindParam(2,  $email);
   $stmt->bindParam(3, $pword);

   $name = $_POST["name"];
   $email = $_POST["email"];
   $pword = $passwords[0];

   $stmt->execute();

   echo "<p>Thank you for registering!</p>";

} else {
...

最终结果是数据库以适当的值执行查询,但是没有SQL注入攻击的风险。 (在后端采取了正确的步骤,例如转义特定字符)。

这样处理的另一个好处是您可以重新使用准备好的语句。 只需为$name$email$pword变量分配新值,然后重新执行该语句。

现在,您已将信息添加到数据库中,是时候考虑将其取回了。

选择记录

此时,您可以将数据添加到数据库,但是您如何知道用户名是唯一的呢? 目前您还没有,但是可以通过在执行实际插入之前检查users表来对此进行补救(请参见清单39 )。

清单39.确保用户名是唯一的
...
if (validate($_POST) == "OK") {
    $dbh = new PDO('mysql:host=localhost;dbname=workflow', 'wfuser', 'wfpass');

    $checkUserStmt = $dbh->prepare("select * from users where username = ?");
    $checkUserStmt->bindParam(1, $name);
    $name = $_POST["name"];
    $checkUserStmt->execute();

    if ($checkUserStmt->rowCount() == 0) {    

        $stmt = $dbh->prepare("insert into users (username, email, password)\
                                          values (?, ?, ?)");
...
        echo "<p>Thank you for registering!</p>";

    } else {

        echo "There is already a user with that name: <br />";

    } 

} else {
...

在这种情况下,您将像第一次创建一个准备好的语句,但是execute()函数似乎不太直观。 毕竟,您实际上并没有做任何事情,对吧? 错误。 您正在执行的操作是使用满足查询要求的数据填充该语句-任何具有用户输入用户名的数据库行。

要检查并查看数据库是否找到了任何记录,可以检查rowCount()函数,该函数返回查询找到的行数。 如果有,则意味着用户名不是唯一的。

实际上,该语句包含满足查询条件的任何行上的所有信息。 接下来,您将检索一组结果。

检索结果

当然,在现实世界中,如果有人输入了已经存在的用户名,则永远不会显示所有现有的用户名,但您将在此处进行操作,以便了解如何完成此操作。

之前,您了解了如何使用准备好的语句。 如果您没有使用任何不受信任的数据(例如用户名或用户提交的其他信息),那么您可以选择直接直接执行查询(请参见清单40 )。

清单40.直接执行查询
...
    } else {

        echo "<p>There is already a user with that name: </p>";

        $users = $dbh->query("SELECT * FROM users");
        $row = $users->fetch();
        echo $row["username"] . " -- " . $row["email"] . "<br />";

    }
...

第一步是通过执行查询来填充$users语句,该查询将选择users表中的所有行。

Next, you'll use the fetch() function to extract a single row. This function returns an associative array that includes the data for a single row. The keys are the same as the column names, so you can output the data for that row very easily by requesting the appropriate values from the $row array.

But this example is just a single row. How do you access all the data?

Seeing all the results: The while loop

To see all of the data, you want the page to keep fetching rows as long as there are rows to fetch. In order to do that, you can set up a while loop (see Listing 41 ).

Listing 41. Setting up a while loop
...
                          $users = $dbh->query("SELECT * FROM users");
        while ($row = $users->fetch()) {
            echo $row["username"] . " -- " . $row["email"] . "<br />";
        }       
                    ...

PHP starts by attempting to fetch a row. If it succeeds, the result is true and it goes on to display the information for that row. If it fails—in other words, if there are no more rows to fetch —the expression returns false and the while loop ends.

The result is a listing of all of the accounts that currently exist, as in Figure 14 .

Figure 14. Displaying multiple rows from a table
Displaying multiple rows from a table

Close the database connection

Before moving on, you need to make sure that the database connection you opened gets closed again. You do that by destroying the PDO object that connects to the database (see Listing 42 ).

Listing 42. Destroying the PDO object
...
            echo $row["username"] . " -- " . $row["email"] . "<br />";
        }
    }

     $dbh = null;

} else {
    echo "<p>There was a problem with your registration:</p>";
...

Now it's time to clean things up a bit.

Cleaning up: including files

So far, each script you've written has been self-contained, with all of the code in a single PHP file. In this section, you'll look at organizing your code into multiple files. You'll take sections of code that you use on multiple pages and place them into a separate file, which you'll then include in the original pages.

Why include files?

PHP provides two ways to include files. One is for including support files, such as interface elements, and the other is for crucial files, such as functions called within the page.

Including the definitions

Start by creating the files you'll eventually include. Whenever you create a website, one of the first things you need to do is create a header and footer file that contains the major interface elements. That way, you can build as many pages as you want without worrying about what the page looks like until the coding work is done. At that point, you can create the interface just once, in the include files, and the entire site will be instantly updated.

To start, create a file called top.txt and add the code in Listing 43 .

Listing 43. Creating a file called top.txt
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>Workflow Manager</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
  </head>
  <body>
    <div id="wrapper"><div id="bg"><div id="header"></div>
      <div id="page"><div id="container"><div id="banner"></div>
        <div id="nav1">
          <ul style='float: left'>
            <li><a href="#" shape="rect">Home</a></li>
            <li><a href="#" shape="rect">Upload</a></li>
            <li><a href="#" shape="rect">Files</a></li>
          </ul>
        </div>
        <div id="content">
          <div id="center">

In a separate file called bottom.txt, add the following shown in Listing 44 .

Listing 44. bottom.txt
</div>
        </div>
      </div>
    </div></div></div>
  </body>
</html>

Save both files in the same directory as registration.php. Copy the images directory and the style.css file from the PHPPart1SampleFiles.zip in Downloadable resources to that directory as well, as they're referenced by the HTML code in top.txt.

Including the files

Now go ahead and add these files to the registration page. Edit registration.php to look like Listing 45 .

Listing 45. Adding top.txt and bottom.txt to the registration page
<?php

   include("top.txt");

?>

<h1>Register for an Account:</h1>
<form action="registration_action.php" method="POST">
   
   Username: <input type="text" name="name" /><br />
   Email: <input type="text" name="email" /><br />
   Password: <input type="password" name="pword[]" /><br />
   Password (again): <input type="password" name="pword[]" /><br />
   <input type="submit" value="GO" />

</form>

<?php

   include("bottom.txt");

?>

Notice that you've removed the HTML that normally surrounds the content of the page and replaced it with a command to include the files you just created. Now it's time to see what that action does.

结果

If you now point your browser back to the registration page, you will see a much different look, as shown in Figure 15 .

Figure 15. New look of registration page
New registration page

If you do a "view source" on the page, you can see that all three files have now been merged in the output (see Listing 46 ).

Listing 46. Files have been merged in the output
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>Workflow Manager</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
  </head>
  <body>
    <div id="wrapper"><div id="bg"><div id="header"></div>
      <div id="page"><div id="container"><div id="banner"></div>
        <div id="nav1">
          <ul style='float: left'>
            <li><a href="#" shape="rect">Home</a></li>
            <li><a href="#" shape="rect">Upload</a></li>
            <li><a href="#" shape="rect">Files</a></li>
          </ul>
        </div>
        <div id="content">
          <div id="center">
<h1>Register for an Account:</h1>
<form action="registration_action.php" method="POST">

   Username: <input type="text" name="name" /><br />
   Email: <input type="text" name="email" /><br />
   Password: <input type="password" name="pword[]" /><br />
   Password (again): <input type="password" name="pword[]" /><br />
   <input type="submit" value="GO" />

</form>

          </div>
        </div>
      </div>
    </div></div></div>
  </body>
</html>

If you go ahead and make the same changes to registration_action.php and submit the form, you'll see that the changes take place immediately.

Now, this page isn't a work of art, and that's OK. Later, you can get a designer to make it look nice, and you'll have to make the changes only once—to the included files—rather than to every page on the site.

Requiring files

If PHP can't find interface files, it's a problem, but it isn't necessarily a catastrophe, especially if all you're worried about is the functionality of the application. As a result, if PHP can't find a file specified by the include() function, it displays a warning and continues processing the page.

In some cases, however, not being able to find an include file is a catastrophe. For example, you can pull the validate() script out into a separate file and include that file in the registration_action.php file. If PHP can't find it, that's a problem because you're calling that functions within the page. So, to avoid that, you can use the require() function, instead of include() (see Listing 47 ).

Listing 47. Using the require() function
<?php

   include("top.txt");
    require("scripts.txt");

?>

<p>You entered:</p>

<?php
   foreach ($_POST as $key=>$value) {
      echo "<p>".$key." = " . $value . "</p>";
   }

   $passwords = $_POST["pword"];
   echo "First password = ".$passwords[0];
   echo "<br />";
   echo "Second password = ".$passwords[1];

   if (validate($_POST) == "OK") {
      echo "<p>Thank you for registering!</p>";
...

If PHP can't find a page that's required, it sends a fatal error and stops processing.

Avoiding duplicates

There's nothing to stop you from including a file in a file that is itself included in another file. In fact, with all of these include files floating around, it can get confusing, and you may inadvertently include the same file more than once. This duplication can result in interface elements appearing multiple times, or errors due to the redefinition of functions or constants. To avoid that, PHP provides special versions of the include() and require() functions. For example, you can be sure that the registration_action.php file will load the files only once (see Listing 48 ).

Listing 48. Ensuring that the registration_action.php file will load the files only once
<?php
   include_once("top.txt");
   require_once("scripts.txt");
?>

<p>You entered:</p>

<?php
...

When PHP encounters the include_once() or require_once() function, it checks to see if the file has already been included in the page before including it again.

结论

In this tutorial, you began the process of building a web-based application using PHP. You looked at the basic syntax of a PHP script, using it to build a page that accepts input from an HTML form. In processing the form, you reviewed basic structures, such as variables, if-then statements, and loops. You also examined numeric and associative arrays, and how to access their data. You then moved on to looking at and moving data into and out of a MySQL database by creating a SQL statement and executing it, then working with the arrays that represent each row of data. Finally, you looked at using include files.

The purpose of this series of tutorials is to teach you how to use PHP through building a workflow application. Here in Part 1, you began the process by enabling users to sign up for a new account, which you then stored in a database. Subsequent parts of this series explore HTTP password protection and other important issues that will help you on your path to becoming a PHP developer.


翻译自: https://www.ibm.com/developerworks/opensource/tutorials/os-phptut1/os-phptut1.html

c# 用户帐户临时文件夹

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值