本期需要用到的前面几期所讲过的内容:
这里是 PHP 网站开发的第三个阶段,也就是前端 HTML 及 CSS 所制作的网页是如何跟 PHP 后台代码进行交互的。
向后台提交数据
前端网页代码:
留言本.wrap{width: 600px;margin: 0px auto;}
.add{overflow: hidden;}
.add .content{width: 598px;margin: 0;padding: 0;}
.add .user{float: left;}
.add .btn{float: right;}
.msg{margin: 20px 0px;background: #ccc;padding: 5px;}
.msg .info{overflow: hidden;}
.msg .user{float: left;color: red;}
.msg .time{float: right;color: blue;}
.msg .contet{width: 100%;padding: :5px;}
后端 PHP 文件代码:<?php
$content = $_POST['content'];
$user = $_POST['user'];
var_dump( $content,$user );
?>
效果:
点击 “发表留言” 后就可以看到效果〜
对留言内容进行检查
具体语法等请参考:《运算符》与《流程制》
后端 PHP 文件代码:<?php
$content = $_POST['content'];
$user = $_POST['user'];
//禁止使用的用户名
$n = [
'张三',
'李四',
'王五',
];
foreach ($n as $name) {
if ( $user == $name ) {
die("禁止使用的用户名");
}
}
//判断留言是否为空
if ( $content == '') {
die("留言内容不能为空");
}
if ( $user == '') {
die("留言人不能为空");
}
var_dump( $content,$user );
?>
效果:
可以看到当我们输入 “张三” ,也就是禁止使用的用户名,点击发表留言后会弹出 “禁止使用的用户名”:
对留言内容的处理进行封装
具体语法等请参考:《函数的基础语法》
这里只是把上面 “对留言内容进行检查” 里面的代码进行函数封装,从而实现一次封装多次调用的效果。
后端 PHP 文件代码:<?php
$content = $_POST['content'];
$user = $_POST['user'];
//定义函数,对数据进行检查
function post( $content ){
if ( $content == '') {
return false;
}
//禁止使用的用户名
$n = [ '张三', '李四', '王五'];
foreach( $n as $name ){
if ($content== $name ) {
return false;
}
}
return true;
}
//调用函数,检查留言内容
$is = post( $content );
if ( $is == false ) {
die('留言内容不能为空');
}
//调用函数,检查留言人
$is = post( $user );
if ( $is == 张三 ) {
die('用户名输入不正确');
}
var_dump( $content,$user );
?>
这里在浏览器里输出的效果跟上面 “对留言内容进行检查” 的效果是一样的。
对函数进一步进行封装
具体语法等请参考:《类与对象》
$content = $_POST['content'];
$user = $_POST['user'];
//定义类
class input{
//定义函数,对数据进行检查
function post( $content ){
if ( $content == '') {
return false; }
//禁止使用的用户名
$n = [ '张三', '李四', '王五' ];
foreach( $n as $name ){
if ( $content == $name ) {
return false;
}
}
return true;
}
}
//实例化类
$input = new input();
//调用函数。检查留言内容
$is =$input->post( $content );
if ( $is == false ) {
die('留言内容不能为空');
}
//调用函数,检查留言人
$is =$input->post( $user );
if ( $is == false ) {
die('用户名输入不正确');
}
var_dump( $content,$user );//输出
?>我们随便在浏览器的对话框输入一些内容:
点击发表留言后浏览器输出:
我们也可以把它拆成两个 PHP 文件:
代码 1:
//定义类
class input{
//定义函数,对数据进行检查
function post( $content ){
if ( $content == '') {
return false; }
//禁止使用的用户名
$n = [ '张三', '李四', '王五' ];
foreach( $n as $name ){
if ( $content == $name ) {
return false;
}
}
return true;
}
}
?>
我们把它保存为 input.php 文件,跟save.php文件放在同一目录。
代码 2:
include('input.php');//用include语法包含iput.php文件
$content = $_POST['content'];
$user = $_POST['user'];
//实例化类
$input = new input();
//调用函数。检查留言内容
$is =$input->post($content );
if ( $is == false ) {
die('留言内容不能为空');
}
//调用函数,检查留言人
$is= $input->post( $user );
if ( $is == false ) {
die('用户名输入不正确');
}
var_dump( $content,$user );//输出
?>
最终浏览器输出的内容跟之前输出的是一样的。This is not the end.It is not even the beginning of the end.But it is,perhaps,the end of the beginning.
更多分享