1.实验学时
2学时
2.实验目的
1、掌握 PHP 函数自定义方法;
2、掌握 PHP 程序的数据输入方法;
3、掌握 PHP Web 中的重定向方法;
4、熟练应用php的选择、循环结构;
5、掌握面向对象编程语法
3.实验设备
PC计算机,配置Win10操作系统,Word2019,PHPStudy+eclipse for php
4.实验内容及步骤
(1)实验步骤
①新建 Project File—new—Local PHP Project
②新建php文件,test—new—PHP File
③输入代码并保存
④在浏览器验证代码的正确性并输出运行结果
(2)实验内容
[1]实现用户注册,用户登录功能(写成两个函数实现)
前端静态页面源代码:index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="login.php" method="post">
<table align="center">
<tr>
<td>学号:</td>
<td><input type="text" name="num"></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>性别:</td>
<td>
<input type="radio" name="sex" value="男" checked>男
<input type="radio" name="sex" value="女">女
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="zhuce" id="" value="注册">
<input type="submit" name="ok" id="" value="登录">
<input type="reset" name="" id="" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>
表单处理程序源代码:login.php。程序中包含两个方法,注册register()和登录login()
其中register()方法中输入的学号用正则表达式判断是否为8位,格式正确,显示注册信息,格式不对;输出“注册失败,学号格式不对!”
<?php
require_once 'student.class.php';
function login(){
if (isset($_POST['ok'])){
$xh = $_POST['num'];
$xm = $_POST['name'];
$xb = $_POST['sex'];
$stu=new student();
$stu->set($xh,$xm,$xb);
if ($stu->login()=='1'){
echo '登陆成功!';
}
else {
echo '登陆失败!';
}
}
}
function register(){
if (isset($_POST['zhuce'])){
$xh = $_POST['num'];
$xm = $_POST['name'];
$xb = $_POST['sex'];
$checkxh=preg_match('/^\d{8}$/',$xh);//检查学号是否是8位数字
$stu=new student();
$stu->set($xh,$xm,$xb);
if($checkxh){
$stu->show($xh, $xm, $xb);
echo '</br>';
}
else
echo "注册失败,学号格式不对!";
}
}
login();
register();
?>
面向对象编程的student.class.php
<?php
class student{
private $num;
private $name;
private $sex;
public function show($xh,$xm,$xb){
$this->num=$xh;
$this->name=$xm;
$this->sex=$xb;
echo '学号:'.$this->num.'</br>';
echo '姓名:'.$this->name.'</br>';
echo '性别:'.$this->sex.'</br>';
}
public function set($xh,$xm,$xb){
$this->num=$xh;
$this->name=$xm;
$this->sex=$xb;
}
public function login(){
if ($_POST['name']=='admin'){
return '1';
}
}
}
?>
运行结果测试:
- 前端页面
- 注册时,当输入的学号不为8位时
- 注册时,输入的学号为8位
- 登陆时,姓名为admin即输入信息正确时
- 登陆时,输入信息错误时
[2]页面输出8位随机字符串,随机显示内容范围为大小写字符加0-9的数字。
<?php
function randstring($n){
$a=range('a', 'z');
$b=range('A', 'Z');
$c=range('0', '9');
$d = array_merge($a,$b,$c);
$str='';
for ($i=1;$i<=$n;$i++){
$str.=$d[rand(0,count($d)-1)];
}
return $str;
}
$str=randstring(8);
echo $str;
?>