1. 程式人生 > >PHP初級練習實戰之留言板

PHP初級練習實戰之留言板

btn ado errno sta png from borde 數字 cat

PHP初級練習實戰之留言板
初學者做的東西,有的地方寫的不好,哈哈哈!
一.知識重點
1.三目運算 $page= empty($_GET[‘p‘]) ? 1: $_GET[‘p‘];
2.數據庫的操作mysqli的方法
3.html css js
4.字符串的拼接
5.制作分頁頁碼
6.完整驗證碼的制作
7.類的運用
8.session傳遞驗證碼的方法

二 .代碼
代碼分為6個文件,liuyanbook.php為主頁
技術分享圖片

1.liuyanbook.php主界面

<?php
//日期
$weekday = ["日","一","二","三","四","五","六"];
date_default_timezone_set(‘Asia/Shanghai‘); 
$now = getdate(time());
$week=$now[‘wday‘];
$date = date("Y年m月d日  星期$weekday[$week]");
//echo $date;

//設置頁碼變量
//默認首頁p=1
$page= empty($_GET[‘p‘]) ? 1: $_GET[‘p‘];
//頁碼
$showPage = 3;
//計算偏移量
$pageoffset = ($showPage-1)/2;

//連接數據庫,取數據
$host = "127.0.0.1";
$dbuser = "root";
$password = "";
$dbname = "php10";
$db = new mysqli($host, $dbuser, $password, $dbname);

if ($db->connect_errno != 0) {
    echo "連接失敗:";
    echo $db->connect_error;
    exit;
}

//分頁
$db->query("set names utf8");
$limit =  ($page-1) * 5;
$sql = "select * from msg order by id desc limit {$limit},5";

$mysqli_result = $db->query($sql);
if ($mysqli_result == false) {
    echo "SQL錯誤!";
    exit;
}
//var_dump($mysqli_result);

//總頁數
$total_sql = "select count(*) from msg";
$total_result = $db->query($total_sql);
$total_array = mysqli_fetch_array($total_result,MYSQLI_ASSOC);
$total = $total_array["count(*)"];
//echo $total;

//計算頁數
$total_pages = ceil($total/5);
//echo $total_pages;
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>三態電子商務有限公司</title>
    <link rel="stylesheet" type="text/css" href="style.css"/>
    <script type="text/javascript"></script>
</head>
<body>
<div class="contentout">
    <div class="date"><?php echo $date;?></div>

    <div class="h">
        <h1>三態電子商務有限公司</h1>
        <h2>留言板</h2>
    </div>
    <div class="all">
        <div class="add">
        <form action="liuyan.php" method="post">
            <textarea name="content" class="content" cols="60" rows="8"></textarea><br>
            留言人:<input style="padding:6px 8px"; name="user" class="user" type="text"/>
            <p>驗證碼圖片:<img id="captcha_img" border="1" src="str.php?r=<?php echo rand();?>" width="100px" height="30"</p>
            <a href="javascript:void(0)" onclick="document.getElementById(‘captcha_img‘).src=‘str.php?r=‘+Math.random()">換一個?</a>
             請輸入圖片中的內容:<input style="padding:6px 8px"; type="text" name="authcode" value="" />
            <input class="btn" type="submit" value="提交留言"/>
        </div>
        </form>

        <!--留言內容-->
        <?php
        while($row = mysqli_fetch_array($mysqli_result,MYSQLI_ASSOC)) {
        ?>

            <div class="msg">
                <div class="info">
                    <span class="user"><?php echo $row["user"];?></span>
                    <span class="num"><?php echo "&nbsp;&nbsp;".$row["id"]."樓";?></span>
                    <span class="time"><?php echo date("Y-m-d H:i:s",$row["intime"]);?></span>  
                </div>
                <div class="content">
                    <?php echo $row["content"];?>   
                </div>
            </div>
        <?php
        }
        ?>

    </div>

    //頁碼部分
    <div class="page">
    <?php
        $page_banner = "";
        if ($page > 1) {
            $page_banner = "<a href=‘liuyanbook.php?p=1‘>首頁</a>";
            $page_banner.= "&nbsp;&nbsp;"."<a href=‘liuyanbook.php?p=".($page-1)."‘>上一頁</a>";
        }

        //初始化前面頁碼數據
        $start = 1;
        $end = $total_pages;
        if ($total_pages > $showPage) {
            if($page > $pageoffset + 1) {
                $page_banner.="...";
            }
            if ($page > $pageoffset) {
                $start = $page - $pageoffset;
                $end = $total_pages > $page + $pageoffset ? $page + $pageoffset : $total_pages;
            } else {
                $start = 1;
                $end = $total_pages > $showPage ? $showPage : $total_pages;
            }
            if ($page + $pageoffset > $total_pages) {
                $start = $start - ($page + $pageoffset - $total_pages);
            }
        }

        //顯示前面的頁碼
        for($i=$start;$i<$end;$i++) {
            $page_banner.= "&nbsp;&nbsp;"."<a href=‘".$_SERVER[‘PHP_SELF‘]."?p=".$i."‘>{$i}</a>";
        }

        //顯示尾部省略
        if ($total_pages > $showPage && $total_pages > $page + $pageoffset) {
            $page_banner.="...";
        }

        if ($page < $total_pages) {
            $page_banner.= "&nbsp;&nbsp;"."<a href=‘".$_SERVER[‘PHP_SELF‘]."?p=".($page+1)."‘>下一頁</a>";
            $page_banner.= "&nbsp;&nbsp;"."<a href=‘liuyanbook.php?p=".$total_pages."‘>尾頁</a>";
        }

        //頁碼部分字符拼接
        $page_banner.= "&nbsp;&nbsp;"."共".$total_pages."頁";
        $page_banner.= "&nbsp;&nbsp;"."共".$total."條留言";
        $page_banner.= "<form action=‘liuyanbook.php‘ method=‘get‘ style= display:inline>";
        $page_banner.= "&nbsp;&nbsp;"."跳轉到第<input type=‘text‘ size=‘1‘ name=‘p‘>頁";
        $page_banner.= "<input type=‘submit‘ value=‘確定‘>";
        $page_banner.= "</form>";
        echo  $page_banner;
    ?>
    </div>
</div>  
</body>
</html>

2.liuyan.php後端驗證,插入數據

<?php
include(‘class_input.php‘);
include(‘dbcontent.php‘);
//include(‘str.php‘);

$content = $_POST["content"];
$user = $_POST["user"];
$authcode = $_POST["authcode"];

//不能為空
/*if ($content == "") {
    die("留言內容不能為空!");
}
if ($user == "") {
    die("請輸入留言人的姓名!");

}*/

//對輸入的內容和留言人進行檢測,不能含有李星和王瑤兩個名字
$input = new input();

//檢測顯示的結果

$is = $input->post($content);
if ($is == false) {
    die("留言內容不能為空或者存在禁止關鍵字!");
}

$is = $input->post($user);
if ($is == false) {
    die("留言人不能為空或者存在禁止關鍵字!");
}

//檢測驗證碼
$codeinput = new codeinput();

$iscode = $codeinput->check($authcode);
if ($iscode == false) {
    die("請輸入正確的驗證碼!");
}

//var_dump($content,$user);

//將留言內容寫入數據庫
$time = time();
$sql = "insert into msg (content, user, intime) values (‘{$content}‘,‘{$user}‘,‘{$time}‘)";
//echo $sql;

$is = $db->query($sql);
//var_dump($is);
header("location:liuyanbook.php");//跳回主頁
?>

3.class_input.php兩個類,驗證關鍵字和驗證碼的類

<?php
class input {
    function post($word) {
        if ($word == "") {
            return false;
        }
    //定義禁止使用的用戶
    $name = ["李星","王瑤"];
    //循環禁止使用的關鍵字,user一一與它對比
    foreach ($name as $key => $value) {
        if ($word == $value) {
            return false;
        }
    }
            return true;
    }
}

class codeinput {
    function check($code) {
        if ($code == "") {
            return false;
        }

    //判斷輸入驗證碼是否正確

    if (isset($code)) {
    session_start();

    if (strtolower($code) == $_SESSION["authcode"]) {
        return true;
    } else {
        return false;
    }
    exit();
}   
    }
}

?>

4.dbcontent.php數據庫連接

<?php
$host = "127.0.0.1";
$dbuser = "root";
$password = "";
$dbname = "php10";

$db = new mysqli($host, $dbuser, $password, $dbname);
if ($db->connect_errno != 0) {
    die("連接數據庫失敗!");
}
$db->query("set names UTF8");
?>

5.str.php生成驗證碼

<?php

session_start();

header("content-type: image/png");

    //生成白色底圖
    $image = imagecreatetruecolor(100, 30);
    $bgcolor = imagecolorallocate($image, 255, 255, 255);
    imagefill($image, 0, 0, $bgcolor);

    //在白色底圖上生成4個彩色隨機字符
    /*1.生成4個數字
    for($i=0;$i<4;$i++) {
        $fontsize = 6;
        $fontcolor = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));
        $fontcontent = rand(0, 9);

        $x = ($i*100/4) + rand(5, 10);
        $y = rand(5, 10);

        imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
    }*/

    //2.生成隨機字母數字
    $captch_code = "";//將生成的驗證碼存入該變量中

    for($i=0;$i<4;$i++) {
        $fontsize = 6;
        $fontcolor = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));

        //隨機截取字母數字
        $data = "abcdefghijkmnopqrstuvwxyz23456789";
        $fontcontent = substr($data,rand(0,strlen($data)),1);
        $captch_code.= $fontcontent;//追加到驗證碼存放

        $x = ($i*100/4) + rand(5, 10);
        $y = rand(5, 10);

        imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
    }

    $_SESSION["authcode"] = $captch_code;//保存到session中

    //在白色底圖上生成隨機點(幹擾元素)
    for($i=0;$i<200;$i++) {
        $pointcolor = imagecolorallocate($image, rand(50, 200), rand(50, 200), rand(50, 200));
        imagesetpixel($image, rand(1, 29), rand(1, 29), $pointcolor);
    }
    //在白色底圖上生成隨機線(幹擾元素)
    for($i=0;$i<3;$i++) {
        $linecolor = imagecolorallocate($image, rand(80, 220), rand(80, 220), rand(80, 220));
        imageline($image, rand(1, 99), rand(1, 29), rand(1, 99), rand(1, 29), $linecolor);
    }

    imagepng($image);

    imagedestroy($image);

?>

6.style.css界面樣式

.all {
    width: 800px;
    margin: 0px auto;
}

.contentout {
    width: 1000px;
    margin: 0 auto;

}

.date {
    text-align:right;
}
.h {
    text-align:center;
}
.add {overflow: hidden;}
.add .content {
    width: 98%;
    padding: 6px;
    margin: 0px;
    font-size:20px;
    }

.add .btn {
    float: right;
    width: 100px;
    height: 40px;
    font-size: 20px;
}

.msg {
    margin: 10px 0px;
    background: #ccc;
    padding: 10px;
    font-size: 18px;
} 
.msg .info{overflow: hidden;}
.msg .user {
    float: left;
    color: blue;
}

.msg .num { 
    font-style: italic; 
    font-size: 16px;
    color: red;
} 
.msg .time {
    float: right;
    color: #999;
}
.msg .content {
    width: 100%;
}
.page {
    text-align:center;
    font-size: 18px;
}`
`.all {
    width: 800px;
    margin: 0px auto;
}

.contentout {
    width: 1000px;
    margin: 0 auto;

}

.date {
    text-align:right;
}
.h {
    text-align:center;
}
.add {overflow: hidden;}
.add .content {
    width: 98%;
    padding: 6px;
    margin: 0px;
    font-size:20px;
    }

.add .btn {
    float: right;
    width: 100px;
    height: 40px;
    font-size: 20px;
}

.msg {
    margin: 10px 0px;
    background: #ccc;
    padding: 10px;
    font-size: 18px;
} 
.msg .info{overflow: hidden;}
.msg .user {
    float: left;
    color: blue;
}

.msg .num { 
    font-style: italic; 
    font-size: 16px;
    color: red;
} 
.msg .time {
    float: right;
    color: #999;
}
.msg .content {
    width: 100%;
}
.page {
    text-align:center;
    font-size: 18px;
}

三.數據庫
表格式
技術分享圖片

技術分享圖片

四.截圖界面

PHP初級練習實戰之留言板