Помощ - Търсене - Потребители - Събития
Пълна версия: Как да си направим една проста форум система
GGbit.info > Hi-Tech > Web разработка > Полезни статии
advokata
В този урок ще обясня как да си направим сами форум, които ще съдържа следните неща:
- регистриране на потребители
- вход/изход
- Администраторски контролен панел
- Търсене на форум
- Лични съобщения

База данни:

Като за начало ще ни трябва база данни - ето я и нея:
CREATE TABLE forum_content (
id int(10) NOT NULL auto_increment,
title text,
autor text,
forum text,
content text,
signature text,
PRIMARY KEY (id)
) TYPE=MyISAM;

CREATE TABLE forum_forums (
id int(10) NOT NULL auto_increment,
forum text,
permission text,
PRIMARY KEY (id)
) TYPE=MyISAM;

CREATE TABLE forum_pm (
id int(10) NOT NULL auto_increment,
user text,
content text,
owner text,
title text,
PRIMARY KEY (id)
) TYPE=MyISAM;

CREATE TABLE forum_reply (
id int(10) NOT NULL auto_increment,
autor text,
content text,
signature text,
reply_id text,
permission text,
PRIMARY KEY (id)
) TYPE=MyISAM;

CREATE TABLE forum_users (
id int(10) NOT NULL auto_increment,
user text,
pass text,
email text,
signature text,
PRIMARY KEY (id)
) TYPE=MyISAM;


Сега да създадем файла, които ще ни свързва с базата данни:
<?php
$dbh=mysql_connect ("localhost", "username", "pass") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("db");
?>


Сега и формата за регистриране:
<?php
$a = rand(0,9);
$b = rand(0,9);
$c = rand(0,9);
$d = rand(0,9);
$e = rand(0,9);
$f = rand(0,9);
$g = rand(0,9);
$h = rand(0,9);
/* Generates a random number for the security code */
$random = "$a"."$b"."$c"."$d"."$e"."$f"."$g"."$h";
/* Echoes the form */
echo "
<form action=?id=register method=post><table border=0>
  <tr>
    <td>Username:</td>
    <td><input name=user type=text id=user class=form></td>
  </tr>
  <tr>
    <td>Password:</td>
    <td><input name=pass type=password id=pass class=form></td>
  </tr>
  <tr>
    <td>Email</td>
    <td><input name=email type=text id=email class=form></td>
  </tr>
  <tr>
    <td>Forum Signature</td>
    <td><textarea name=signature cols=20 wrap=VIRTUAL id=signature class=form></textarea></td>
  </tr>
  <tr>
    <td> </td>
    <td><input name=code1 type=text id=code1 value=$random class=form></td>
  </tr>
  <tr>
    <td>Security Code </td>
    <td><input name=code2 type=text id=code2 class=form></td>
  </tr>
  <tr>
    <td> </td>
    <td><input type=submit name=Submit value=Register class=form></td>
  </tr>
</table>
</form>
";
/* If its submitted...*/
if($_POST['Submit']){
/* Includes the config file */
include("config.php");
/* Get the info from the forms */
$user = $_POST['user'];
$pass = $_POST['pass'];
$pass_md5 = md5($pass);
$email = $_POST['email'];
$signature = $_POST['signature'];
$code1 = $_POST['code1'];
$code2 = $_POST['code2'];
if(empty($user)){
echo "Please, insert an username.";
die();
};
if(empty($pass)){
echo "Please, insert a password.";
die();
};
if(empty($email)){
echo "Please, insert an email";
die();
};
if(empty($signature)){
$signature = "~".$user;
};
if($code1 !== $code2){
echo "Security code doesn't match";
die();
};
/* Check if the username already exist */
$query3 = "SELECT * FROM `forum_users`";
$result3 = mysql_query($query3);
while($r3=mysql_fetch_array($result3)){
$username = "$r3[user]";
if($user == $username){
echo "Sorry, that username is already in use.";
die();
}
};

/* Insert the info if everithing is ok */
$query = "INSERT INTO `forum_users` ( `id` , `user` , `pass` , `email`, `signature`)
VALUES (
'NULL', '$user', '$pass_md5', '$email', '$signature'
);";
$ok = mysql_query($query);
if($ok){
echo "Welcome $user!, Thanks for registering...";
}else{
echo "Oops, error";
}
};
?>


Да не забравиме и вход/изход:

- Вход
<form action="?id=login" method="post">
<table border="0">
  <tr>
    <td>Username</td>
    <td><input name="user" type="text" id="user" class=form></td>
  </tr>
  <tr>
    <td>Password</td>
    <td><input name="pass" type="password" id="pass" class=form></td>
  </tr>
  <tr>
    <td> </td>
    <td><input type="submit" name="Submit" value="Login" class=form></td>
  </tr>
</table>
</form>
<?php
if($_POST['Submit']){
$user = $_POST['user'];
$pass = $_POST['pass'];
$pass_md5 = md5($pass);
include("config.php");

if(empty($user)){
echo "Please, insert an username.<br>
<a href=?id=login>Go Back</a>.";
die();
};

if(empty($pass)){
echo "Please, insert a password.<br>
<a href=?id=login>Go Back</a>.";
die();
};

$ok = mysql_query("SELECT * FROM `forum_users` WHERE user='$user' and pass='$pass_md5'")
or die ("Wrong Password and Username combination, please, <a href=login.php>go back</a> and try again, or register <a href=register.php>here</a> for free if you dont have an account");
$worked = mysql_fetch_array($ok);  
if($worked){
$r = mysql_fetch_array(mysql_query("SELECT * FROM `forum_users` WHERE user='$user'and pass='$pass_md5'"));
$signature = "$r[signature]";
setcookie ("forum",$user,time()+1957240);
setcookie ("forum_sig",$signature,time()+1957240);
header( 'refresh: 3; url=?id=' );
echo "Welcome $user!, Enjoy the website!.<br>";
echo "You will be redirected in 3 seconds...";
}else{
echo "Wrong username and password, please, <a href=?id=login>try again</a>";
}
};
?>


<?php
$name = $_COOKIE['forum'];
$signature = $_COOKIE['forum_sig'];
setcookie ("fullrag",$name,time()-1957240);
setcookie ("fullrag_sig",$signature,time()-1957240);
header( 'refresh: 3; url=?id=' );
echo "You are now logged out<br>
You will be redirected in 3 seconds...";
?>


Ето го и нашия форум:
<script>
function sendText(e, text)
{
e.value += text
}
</script>
<?php
/* Includes the configuration file */
include("config.php");
/* Set the variables that will be received */
$forum = $_GET['forum'];
$see = $_GET['see'];
$read = $_GET['read'];
$f_id = $_GET['f_id'];
$newtopic = $_GET['newtopic'];
$reply_id = $_GET['reply_id'];
$reply = $_GET['reply'];
/* Now if the url containts &see=true this will activate */
if($see == "true"){
$forum = $_GET['forum'];//optional
/* Pagination... */
function per_page($link, $offset) {
  global $numofpages, $page;
  $numofpages = round($numofpages);

  $pagesstart = round($page-$offset);
  $pagesend = round($page+$offset);

  if ($page != "1" && round($numofpages) != "0") {
    echo str_replace("%page", round($page-1), '<a href="'.$link.'"><font face="Trebuchet MS">«</font></a>  ');
  }

  for($i = 1; $i <= $numofpages; $i++) {
    if ($pagesstart <= $i && $pagesend >= $i) {
      if ($i == $page) {
        echo "<b>[$i]</b> ";
      }
      else {
        echo str_replace("%page", "$i", '<a href="'.$link.'">'.$i.'</a>  ');
      }
    }
  }
  if (round($numofpages) == "0") {
    echo "[$i]";
  }

  if ($page != round($numofpages) && round($numofpages) != "0") {
    echo str_replace("%page", round($page+1), '<a href="'.$link.'"><font face="Trebuchet MS">»</font></a>');
  }
}


/* Set How many results to display per page */
$pp = "10";

/* Select the table that you want to view, you can add things like WHERE something='something' */
$table = "forum_content";

$total = mysql_result(mysql_query("SELECT COUNT(id) FROM $table WHERE `forum`= '$forum' ORDER BY `id` DESC"),0);
$numofpages = $total / $pp;  
if (!isset($_GET['page'])) {
  $page = 1;
}
else {
  $page = $_GET['page'];
}
$limitvalue = $page * $pp - ($pp);

/* Display the rows */
$query = "SELECT * FROM $table WHERE `forum`= '$forum' ORDER BY `id` DESC LIMIT $limitvalue, $pp";
$result = mysql_query($query);
while($r=mysql_fetch_array($result))
{
  echo "<span class=box4><a href=?id=forum&forum=$r[forum]&see=read&f_id=$r[id]>$r[title]</a> - Autor: $r[autor]</span>";
}
echo "<br><a href=?id=forum&forum=$forum&newtopic=true><img src=images/newtopic.gif width=93 height=25 border=0></a><br><br>";

/* Display the pages down the bottom */
echo 'Pages: '.round($numofpages).'<br>';

per_page("?id=forum&forum=$forum&see=true&page=%page", "5");
/* If the url contains &see=read */
}else if($see == "read"){
/* Sets the query */
$query = "SELECT * FROM `forum_content` WHERE `forum`= '$forum' and `id`= '$f_id'";
$result = mysql_query($query);
while($r=mysql_fetch_array($result)){
/* Echoes the content */
echo "<span class=box1><b>$r[title]</b></span><span class=box2>Posted by $r[autor]</span><span class=box1>$r[content]</span><span class=box3>$r[signature]<br></span><br>";
};
/* Another query */
$query2 = "SELECT * FROM `forum_reply` WHERE `forum`= '$forum' and `reply_id`= '$f_id' ORDER BY `id` ASC";
$result2 = mysql_query($query2);
while($r2=mysql_fetch_array($result2)){
echo "<span class=box2>Reply by $r2[autor]</span><span class=box1>$r2[content]</span><span class=box3>$r2[signature]<br></span><br>";
}
/* This will add the images of Add Reply and New Topic */
echo "<table border=0>
  <tr>
    <td><a href=?id=forum&forum=$forum&reply=true&f_id=$f_id><img src=images/reply.gif width=93 height=25 border=0></a></td>
    <td><a href=?id=forum&forum=$forum&newtopic=true><img src=images/newtopic.gif width=93 height=25 border=0></a></td>
  </tr>
</table>
";
}else if($newtopic == "true"){//starts a new topic
$user = $_COOKIE['forum'];// If the user is logged in
if(empty($user)){
$r = mysql_fetch_array(mysql_query("SELECT * FROM `forum_forums` WHERE `forum`= '$forum'"));
$permission = "$r[permission]";//check the permission, if the forum allow guests to post
if(empty($permission)){
echo "You are not allowed to post here, please register";
die();
}else if($permission == "0"){
echo "You are not allowed to post here, please register";
die();
}else if($permission == "1"){
$forum = $_GET['forum'];//If the user is logged in it wont display the username box
echo "<form action=?id=forum&forum=$forum&newtopic=submitted method=post name=form>
  <table border=0>
    <tr>
      <td> </td>
      <td align=\"center\"><input type=\"button\" onClick=\"sendText(document.form.content, '[b][/b]')\" value=\"b\" name=\"smile\" class=form>
        <input type=\"button\" onClick=\"sendText(document.form.content, '[i][/i]')\" value=\"i\" name=\"smile\" class=form>
        <input type=\"button\" onClick=\"sendText(document.form.content, '[u][/u]')\" value=\"u\" name=\"smile\" class=form>
        <input type=\"button\" onClick=\"sendText(document.form.content, '[url][/url]')\" value=\"url\" name=\"smile\" class=form></td>
    </tr>
    <tr>
      <td>Username</td>
      <td><input name=user type=text id=user class=form></td>
    </tr>
    <tr>
      <td>Title</td>
      <td><input name=title type=text id=title class=form></td>
    </tr>
    <tr>
      <td>Content</td>
      <td><textarea name=content cols=35 rows=10 id=content class=form></textarea></td>
    </tr>
    <tr>
      <td> </td>
      <td><input type=submit name=Submit value=Post class=form></td>
    </tr>
  </table>
</form>";
}
}else{
$forum = $_GET['forum'];
echo "<form action=?id=forum&forum=$forum&newtopic=submitted method=post name=\"form\">
  <table border=0>
    <tr>
      <td> </td>
      <td align=\"center\"><input type=\"button\" onClick=\"sendText(document.form.content, '[b][/b]')\" value=\"b\" name=\"smile\" class=form>
        <input type=\"button\" onClick=\"sendText(document.form.content, '[i][/i]')\" value=\"i\" name=\"smile\" class=form>
        <input type=\"button\" onClick=\"sendText(document.form.content, '[u][/u]')\" value=\"u\" name=\"smile\" class=form>
        <input type=\"button\" onClick=\"sendText(document.form.content, '[url][/url]')\" value=\"url\" name=\"smile\" class=form></td>
    </tr>
    <tr>
      <td>Title</td>
      <td><input name=title type=text id=title class=form></td>
    </tr>
    <tr>
      <td>Content</td>
      <td><textarea name=content cols=35 rows=10 id=content class=form></textarea></td>
    </tr>
    <tr>
      <td> </td>
      <td><input type=submit name=Submit value=Post class=form></td>
    </tr>
  </table>
</form>";
}
}else if($newtopic == "submitted"){
$title = $_POST['title'];
$forum = $_GET['forum'];
$content = $_POST['content'];
/* BB code stuff */
$content = str_replace("
","<br>","$content");
$content = str_replace("[b]","<b>","$content");
$content = str_replace("[/b]","</b>","$content");
$content = str_replace("[i]","<i>","$content");
$content = str_replace("[/i]","</i>","$content");
$content = str_replace("[u]","<u>","$content");
$content = str_replace("[/u]","</u>","$content");
$content = str_replace("[url]","<a href=","$content");
$content = str_replace("[/url]"," target=_blank>[Link]</a>","$content");
$user = $_POST['user'];
/* If the user box is empty */
if(empty($user)){
$user = $_COOKIE['forum'];
}
/* If the signature box is empty... */
$signature = $_COOKIE['forum_sig'];
if(empty($signature)){
$signature = "None.";
}
$ok = mysql_query("INSERT INTO `forum_content` ( `id` , `title` , `autor` , `forum`, `content`, `signature`)
VALUES (
'NULL', '$title', '$user', '$forum', '$content', '$signature'
);");
if($ok){
header( 'refresh: 3; url=?id=forum&forum=$forum' );
echo "The post $title has been sucesfully added, thanks $user<br>You will be redirected in 3 seconds...";
}else{
echo "Oops, error.";
}
}else if($reply == "true"){
$reply_id = $_GET['f_id'];
$user = $_COOKIE['forum'];
if(empty($user)){
$r = mysql_fetch_array(mysql_query("SELECT * FROM `forum_forums` WHERE `forum`= '$forum'"));
$permission = "$r[permission]";
if(empty($permission)){
echo "You are not allowed to reply, please register";
die();
}else if($permission == "0"){
echo "You are not allowed to reply, please register";
die();
}else if($permission == "1"){
$forum = $_GET['forum'];
echo "<form action=?id=forum&forum=$forum&reply=submitted&f_id=$reply_id method=post name=form>
  <table border=0>
    <tr>
      <td> </td>
      <td align=\"center\"><input type=\"button\" onClick=\"sendText(document.form.content, '[b][/b]')\" value=\"b\" name=\"smile\" class=form>
        <input type=\"button\" onClick=\"sendText(document.form.content, '[i][/i]')\" value=\"i\" name=\"smile\" class=form>
        <input type=\"button\" onClick=\"sendText(document.form.content, '[u][/u]')\" value=\"u\" name=\"smile\" class=form>
        <input type=\"button\" onClick=\"sendText(document.form.content, '[url][/url]')\" value=\"url\" name=\"smile\" class=form></td>
    </tr>
    <tr>
      <td>Username</td>
      <td><input name=user type=text id=user class=\"form\"></td>
    </tr>
    <tr>
      <td>Content</td>
      <td><textarea name=content cols=35 rows=10 id=content class=\"form\"></textarea></td>
    </tr>
    <tr>
      <td> </td>
      <td><input type=submit name=Submit value=Post class=form></td>
    </tr>
  </table>
</form>";
}
}else{
$forum = $_GET['forum'];
echo "<form action=?id=forum&forum=$forum&reply=submitted&f_id=$reply_id method=post name=form>
  <table border=0>
    <tr>
    
      <td> </td>
      <td align=\"center\"><input type=\"button\" onClick=\"sendText(document.form.content, '[b][/b]')\" value=\"b\" name=\"smile\" class=form>
      <input type=\"button\" onClick=\"sendText(document.form.content, '[i][/i]')\" value=\"i\" name=\"smile\" class=form>
      <input type=\"button\" onClick=\"sendText(document.form.content, '[u][/u]')\" value=\"u\" name=\"smile\" class=form>
      <input type=\"button\" onClick=\"sendText(document.form.content, '[url][/url]')\" value=\"url\" name=\"smile\" class=form></td>
    </tr>
    <tr>
      <td>Content</td>
      <td><textarea name=content cols=35 rows=10 id=content class=\"form\"></textarea></td>
    </tr>
    <tr>
      <td> </td>
      <td><input type=submit name=Submit value=Reply class=form></td>
    </tr>
  </table>
</form>";
}
}else if($reply == "submitted"){
$reply_id = $_GET['f_id'];
$forum = $_GET['forum'];
$content = $_POST['content'];
/* BB code Stuff */
$content = str_replace("
","<br>","$content");
$content = str_replace("[b]","<b>","$content");
$content = str_replace("[/b]","</b>","$content");
$content = str_replace("[i]","<i>","$content");
$content = str_replace("[/i]","</i>","$content");
$content = str_replace("[u]","<u>","$content");
$content = str_replace("[/u]","</u>","$content");
$content = str_replace("[url]","<a href=","$content");
$content = str_replace("[/url]"," target=_blank>[Link]</a>","$content");
$user = $_POST['user'];
if(empty($user)){
$user = $_COOKIE['forum'];
}
$signature = $_COOKIE['forum_sig'];
if(empty($signature)){
$signature = "None.";
}
$ok = mysql_query("INSERT INTO `forum_reply` ( `id` , `reply_id` , `autor` , `forum`, `content`, `signature`)
VALUES (
'NULL', '$reply_id', '$user', '$forum', '$content', '$signature'
);");
if($ok){
echo "The post reply has been sucesfully added, thanks $user, <br> Click <a href=?id=forum&forum=$forum&see=read&f_id=$reply_id>here</a> to see it.";
}else{
echo "Oops, error.";
}
}else{
/* Else, if there isn't any &forum=.. or other variable it will show the forums */
$query_forum = "SELECT * FROM `forum_forums` ORDER BY `id` ASC";
$result_forum = mysql_query($query_forum);
while($r=mysql_fetch_array($result_forum)){
$forum_name = "$r[forum]";
$forum_name = str_replace("_"," ","$forum_name");
echo "<span class=box3><a href=?id=forum&forum=$r[forum]&see=true><b>$forum_name</b></a></span>";
}
};
?>


Без админ панел за къде смеconfused.gif?
<p><strong>Add Forum</strong></p>
<form action="add_forum.php" method="post"><table border="0">
  <tr>
    <td>Name</td>
    <td>
      <input name="name" type="text" id="name">
</td>
  </tr>
  <tr>
    <td> </td>
    <td>
      <select name="permission" id="permission">
        <option value="1" selected>Guest allowed to post and reply</option>
        <option value="0">Guest are not allowed to post and reply</option>
      </select>
</td>
  </tr>
  <tr>
    <td> </td>
    <td><input type="submit" name="Submit" value="Create"></td>
  </tr>
</table>
</form>
<?php
if($_POST['Submit']){
include("../config.php");
$name = $_POST['name'];
$name = str_replace(" ","_","$name");
$permission = $_POST['permission'];
$ok = mysql_query("INSERT INTO `forum_forums` ( `id` , `forum` , `permission`)
VALUES (
'NULL', '$name', '$permission'
);");
if($ok){
echo "The forum has been created.<br>";
if($permission == "0"){
$name = str_replace("_"," ","$name");
echo "Guest are not allowed to post in $name";
}else{
$name = str_replace("_"," ","$name");
echo "Guest are allowed to post in $name";
}
}else{
echo "The forum could not be created.";
}
};
?>


<?php
include("../config.php");
$query_forum = "SELECT * FROM `forum_forums` ORDER BY `id` ASC";
$result_forum = mysql_query($query_forum);
while($r=mysql_fetch_array($result_forum)){
echo "<b>$r[forum]</b> - <a href=forum_delete_process.php?f_id=$r[id]>Delete</a><br>";
}
?>


<?php
include("../config.php");
$id = $_GET['f_id'];
mysql_query("DELETE FROM `forum_forums` WHERE id='$id' LIMIT 1");
echo "The forum has been deleted";
?>


За да може и форума да има и външен вид няма да е зле да добавим малко css, сложете този линк във главната част на форума:

<link href="style.css" rel="stylesheet" type="text/css">


Сега и самия css:
.box1 {
background-color: #f8f8f8;
display:block;
border-top: 1px dotted #000000;
border-right: 1px dotted #000000;
border-bottom: 1px #000000;
border-left: 1px dotted #000000;
margin: 2px;
padding: 2px;
}
.box2 {
background-color: #E6E6E6;
display:block;
border-top: 1px dotted #000000;
border-right: 1px dotted #000000;
border-bottom: 1px #000000;
border-left: 1px dotted #000000;
margin: 2px;
padding: 2px;
}
.box3 {
background-color: #E6E6E6;
display:block;
border: 1px dotted #000000;
margin: 2px;
padding: 2px;
}
.box4 {
background-color: #f8f8f8;
display:block;
border: 1px dotted #000000;
margin: 2px;
padding: 2px;
}
Relevant Advertise!
Крадец на рози
И за да можем сами да си го напишем това кой език трябва да научим ?
ogata
Крадец това май трябва да е PHP ама на мен ми е друг въпроса .... как се кръщава всеки един от документите ? Тоест как трябва да се казва всеки един от файловете ... да кажем за вход ще трябва да е login предполагам , как са им имената на другите и какво е разширението ? login.php confused.gif
advokata
Тук са написани само скриптове на ПХП и css. wink.gif
StoNelHa
А нещо за config.php защото ще се търси за достъп до базата данни ( include("../config.php"); ) ?
Naminator_X_
Е добре поне няма ли да поставиш източник на статията...то е ясно, че не си го мислил това ти.Не е етично/морално така спрямо автора...и между другото наистина трябва да сложиш имената на файловете...това твоето простичко е все едно за вишисти....иначе добър урок...ама ако имаше и по малко обяснения от твоя страна...
vIkToRsHeFa
(Naminator_X_ @ Oct 31 2006, 15:53) *

и между другото наистина трябва да сложиш имената на файловете...това твоето простичко е все едно за вишисти....


Тези които не знаят как работи е по-добре изобщо да не го ползват ами да ползват някоя от готовите форунм системи които се поддържат. 4.gif
Иначе като туториал мда добра алтернатива е но за наистина добър скрипт трябват възможности за смяна на език и скин доста надвишаващи простата css промяна на цветове и картинки. Иначе като увод е наистина добра статийка. 4.gif
BooM
Каде е Copyright www.webleit.com??
http://forums.webleit.com/lofiversion/index.php/t814.html
advokata
Цитат(BooM @ Nov 20 2006, 20:45) *
Каде е Copyright www.webleit.com??
http://forums.webleit.com/lofiversion/index.php/t814.html


Или по-точно от Ethereal-Designs.com blush.gif mrgreen[1].gif

Edit1
Аааа и забравих този форум е пригоден за Case PHP навигация (?id=page)
Това е "lo-fi" версия на нашия форум. За да видите пълната версия, моля натиснете тук.
Invision Power Board © 2001-2018 Invision Power Services, Inc.