首先是網頁的基本架構
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>PHP範例 - 留言板(file IO)</title> </head> <body> </div> </body> </html>再來是form部份
<form action="" method="post"> <p> 姓名︰<input type="text" name="user" /><br /> <textarea name="comment" rows="4" cols="20"></textarea><br /> <input type="submit" value="送出" /> </p> </form>好~重點來了,現在我們在想要留言的地方寫上一個特別的註解,每次留言的時候就以這個註解為目標,替換成留言。那現在就在form的後面加上註解!
<!--write comment here~~-->到此為止,HTML的部份基本上已經都完成了。接下來我們在檔案的一開頭寫上PHP程式碼。
<?
if($_POST["user"]){
$text="";
$text.=$_POST["user"]."說~<br />";
$text.=$_POST["comment"]."<br /><br />";
$text.="<!"."--write comment here~~-->";
$f=file_get_contents("php_1.php");
$f=preg_replace("/\<!"."--write comment here~~--\>/",$text,$f);
file_put_contents("php_1.php",$f);
header('Location: php_1.php');
}
?>
前面的if是判斷有沒有收到POST資料,接下來就一段一段的把留言接上,最後再加上註解標記。可以觀察一下,如果把註解標記加在留言的後面,那顯示出來的留言排列方式就會由舊--->新;如果把註解標記加在留言的前面,那顯示出來的留言排列方式就是新--->舊。最後面的header是讓頁面刷新,避免重覆留言並刷新頁面。完整代碼︰
<?
if($_POST["user"]){
$text="";
$text.=$_POST["user"]."說~<br />";
$text.=$_POST["comment"]."<br /><br />";
$text.="<!"."--write comment here~~-->";
$f=file_get_contents("php_1.php");
$f=preg_replace("/\<!"."--write comment here~~--\>/",$text,$f);
file_put_contents("php_1.php",$f);
header('Location: php_1.php');
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP範例 - 留言板(file IO)</title>
</head>
<body>
<div>
<form action="" method="post">
<p>
姓名︰<input type="text" name="user" /><br />
<textarea name="comment" rows="4" cols="20"></textarea><br />
<input type="submit" value="送出" />
</p>
</form>
<p>
<!--write comment here~~-->
</p>
</div>
</body>
</html>
在我的範例網站也可以找到︰點我
hk
回覆刪除it is very useful!
回覆刪除what's <? use?
回覆刪除It is PHP short open tag, which is default off in PHP5. Just use "<?php" instead.
刪除hi
回覆刪除作者已經移除這則留言。
回覆刪除hihihihi
回覆刪除