Programmer un forum en PHP


Back to programmation.


thibault    (2009-04-04)

thibault

Programmer un forum en PHP

Je vais tâcher de donner ici les bouts de codes principaux des forums sur lesquels vous êtes en train de surfer, l'idée n'est pas de donner des forums clé en main puisque des tas de sites le font déjà très bien, mais je ne peux que trop vous conseiller de comprendre ces codes et programmer par vous-même pour avoir le plus de liberté possible par la suite.

La programmation d'un forum se fait ici en 4 fichiers principaux :

- forum.php (qui affiche les discussions d'un forum donné)
- discussion.php (qui affiche une discussion donnée)
- formulaire.php (qui affiche le formulaire de nouvelle discussion et de réponse et que vous pouvez inclure n'importe où)
- envoyer.php (qui permet d'analyser le contenu posté et de l'insérer dans la base de données MySql)

Concernant la base de données, la table du forum pourra être créée comme suit. Il ne s'agit que d'un exemple, vous pouvez bien entendu ensuite ajouter des champs "categorie", "notification" et bien d'autres.

<?

$sql = "CREATE TABLE forum (id int(15) NOT NULL auto_increment, reponse_id varchar(30) NOT NULL, reponses varchar(20) NOT NULL, date_verif varchar(20) NOT NULL, date varchar(20) NOT NULL, pseudo varchar(50) NOT NULL, sujet varchar (60) NOT NULL, message text NOT NULL, PRIMARY KEY (id));";
$res = mysql_query($sql);

$sql = "ALTER TABLE forum ADD INDEX (reponse_id);";
$res = mysql_query($sql);

$sql = "ALTER TABLE forum ADD INDEX (date_verif);";
$res = mysql_query($sql);

?>


Le champ reponse_id contiendra l'id du message original si le message en question est une réponse à ce message et sera vide dans les autres cas, le champ date_verif du premier message d'une discussion contiendra la date (au format américain pour faciliter la recherche chronologique dans la base de données) de la dernière réponse postée pour pouvoir classer les discussions par ordre de date de dernière réponse.

Le fichier forum.php contient notamment le code suivant :

<?

include_once ('bbcode.php');

$db = mysql_connect($serveur,$utilisateur,$password);

mysql_select_db($base,$db) or die ("erreur de connexion base");

include('formulaire.php');

// on sélectionne ici les dernières discussions, ce sont des posts qui ne sont pas eux-mêmes des réponses à d'autres posts
$req = @mysql_query("SELECT id,reponses,date,date_verif, pseudo,sujet,message FROM forum WHERE reponse_id='' ORDER BY date_verif DESC ") or die ("erreur requete");

while($forum = mysql_fetch_array ($req))
{
print '<a href="'.makelink($forum['sujet']).'-f'.$forum['id'].'.html" title="'.substr(bbcode_title($forum['message']),0,500).'" rel="canonical">'. stripslashes($forum['sujet']).'</a> &nbsp; &nbsp; &nbsp; <font size="2"><b>replies : '.stripslashes($forum['reponses']).'</b> &nbsp; <font color="#888888"> &nbsp; &nbsp; <a title="'.$forum['date_verif'].'">'.substr($forum['date_verif'],0,10).'</a></font></font><br>';
}

mysql_close();

?>


Le fichier discussion quant à lui contiendra le code suivant :

<?

include_once ('bbcode.php');

$db = mysql_connect($serveur,$utilisateur,$password);

mysql_select_db($base,$db) or die ("erreur de connexion base");

$req = mysql_query("SELECT id,reponse_id,date,pseudo,sujet, message,date_verif FROM forum WHERE id='$_GET[id]' ") or die ("erreur requête");

$original = mysql_fetch_array ($req);

print '<br>'.stripslashes($original['pseudo']);

print '<b>'.stripslashes($original['sujet']).'</b><br><br>.bbcode($original['message']);

$rep = mysql_query("SELECT id,date,pseudo,sujet,message FROM forum WHERE reponse_id='$_GET[id]' ORDER BY date ASC") or die ("erreur requête reponse ");

while ($reponse = mysql_fetch_array ($rep))
{
print '<br>'.stripslashes($reponse['pseudo']).' &nbsp;&nbsp;&nbsp;<font size="2" color="#999999">('.$reponse['date'].')</font><br><b>'. stripslashes($reponse['sujet']).'</b><br><br>.bbcode($reponse['message']).'<br><br>';
}

include('formulaire.php');

mysql_close();

?>


Le fichier formulaire, justement contiendra comme il se doit le code HTML du formulaire de nouvelle discussion ou de réponse :

<form method="post" name="form" action="envoyer.php">

<table border="0" align="center">
<tr>
      <td width="85"><b><font face="Arial, Helvetica, sans-serif">Sujet</font></b></td>
      <td width="340">
    <input name="sujet" type="text" size="30" maxlength="40" value="<?  echo stripslashes(@$_POST['sujet']); ?>">
        <input type="submit" name="submit" value="Preview"><?  if (@$_POST['submit'] == 'Preview')  print '<input type="submit" name="submit" value="Post" onClick="if(form.title.value == "") { this.form.submit(); this.disabled=true; this.value=\'Posting...\'; }">';  ?>
</td>
</tr>
<tr>
      <td colspan="2" align="center"> <div align="left">
    <textarea wrap="VIRTUAL" name="message" cols="50" rows="9"><?  echo stripslashes(@$_POST['message']); ?></textarea>

..... et je vous laisse terminer le code par vous-même (au pire jetez un oeil au code de cette page), c'est assez trivial quand on a compris le principe.


Enfin le code du fichier envoyer.php :

<?

$db = mysql_connect($serveur,$utilisateur,$password);
mysql_select_db($base,$db) or die ("erreur de connexion base");

// Suppression des sauts de lignes et espaces inutiles
$_POST['message'] = trim(@$_POST['message']);
$_POST['sujet'] = trim(@$_POST['sujet']);

// C'est ici qu'on lave le contenu de tout tag HTML
$sujet = addslashes(htmlspecialchars($_POST['sujet']));
$message = addslashes(htmlspecialchars($_POST['message']));

$reponse_id = addslashes(htmlspecialchars($_POST['reponse_id']));

// Il est évidemment vivement conseillé de vérifier le contenu des messages envoyés, notamment par des filtres anti-spam, vérifier également que le message ou le sujet ne sont pas vides ou qu'il ne s'agit pas d'un doublon reposté par erreur etc...

// On prépare la date au format américain
$date_verif = date("Y-m-d H:i:s");
$date = date("Y-m-d H:i:s");

// On met à jour la date et le nombre de réponses du post original
$sql = "SELECT reponses FROM forum WHERE id='$reponse_id';";
$res = @mysql_query($sql);

while ($message_principal = @mysql_fetch_array($res))
{
$reponses=$message_principal['reponses']+1;

@$sql_update = "UPDATE forum SET date_verif='$date_verif', reponses='$reponses' WHERE id='$reponse_id';";
mysql_query($sql_update);
}

// Et enfin on insère le message dans la base de données
$sql_insert = "INSERT INTO forum VALUES ('','$reponse_id','0','$date_verif', '$date','$pseudo','$sujet','$message')";
@mysql_query($sql_insert) or die ("erreur requete");

?>


Bien entendu n'utilisez pas le code tel quel, il ne s'agit que de pistes et d'observer la syntaxe des fonctions MySql pour pouvoir ensuite construire votre propre forum à votre image, c'est tout l'intérêt de développer soi-même.

En ce qui concerne les fonctions bbcode du fichier bbcode.php, vous pouvez en programmer en utilisant l'exemple fourni ici :

http://www.ficgs.com/Fonction-BBcode-en-PHP-f3058.html



(more options below)

*fumibu    (2011-05-23 19:53:20)
Programmer un forum en PHP

Super site, je pense que g  trouvé l'éssentiel


*qbwmehv@g    (2013-07-25 16:32:36)
SHORT MILAN AC

I’ve been browsing on-line more than three hours lately, yet I never found any fascinating article like yours. It is pretty worth enough for me. In my opinion, if all webmasters and bloggers made good content as you probably did, the web might be a lot more helpful than ever before. SHORT MILAN AC ht*p://maillotacmilan.wehaay.com/


*qofyihaf@    (2013-07-29 14:26:40)
christian louboutin replica

A client may ever be in the spy of morality but module ever rise above a cats glossa


*losico    (2014-11-02 08:54:59)
Il y a 9 ans

I recently went through a breakup from a serious relationship with my ex partner, who after 12 months came back to me. Of course, nobody on the ship can escape his emotions, either. We heard he was doing cocaine, which for most people is nothing, but Ian was straight edge [a punk who avoids alcohol and drugs] and for him to start doing it was, 'No, he wouldn't do that'.".
legend blue 11s


*zujafo    (2015-04-20 22:26:23)
Il y a 9 ans

Curiosity and the temptation of a no strings good time bring them together. And since organization structure tends to influence compensation policies, sub optimal can actually work against the best interests of pensioners.. Excellence in the sciences, excellence in the sciences, an ability to communicate efficiently in writing, and sound analytical and deductive reasoning skills are all very important, but never forget that the student who excels in these areas while excelling in extra curricular areas is who we really want at Queen My classmates were an eclectic group of people, but all of them showed extraordinary talents both inside and outside of the classroom.If you want to be professional, then you have to show up for the job or the audition."' The actress says looking at child actors now, she doesn't want that for her own daughter, "although I keep asking myself why, because I had a great experience." Though it has only been 2 1/2 years since the adoption of Naleigh, Heigl says, "I don't remember not being a mother.
ray ban sunglasses ht*p://www.arabtimes.com/rayban.html


*vudufa    (2015-05-05 23:04:12)
Programmer un forum en PHP

We can drive thank you very much!. "In the beginning, it was just all black smoke and then the front started getting black smoke and I just called 911 and that was it," said Ed Loucks. It one of those things that are maddening at the time, but humorous when you look back on it..
toms shoes online


*pimaco    (2015-05-29 13:31:26)
Il y a 8 ans

It turned out that the body was damaged and it cost $1700 to repair, which he paid out of pocket (luckily we exchanged information before we parted).. More recently, he was photographed holding a bong commonly used to smoke marijuana, which got him suspended from his sport for three months..
Toms Sko Salg Oslo Solbriller Norge


*modapa    (2015-06-13 11:54:38)
Il y a 8 ans

He knows the struggles of Maine people because he has lived them. He has served the Old Town Orono area well, did a great job as secretary of state and knows the state better than any of the other candidates.. On its website, the Las Vegas Sands Corp. Seems to confirm that credit and financial information provided by patrons was taken by the hackers.Law is ubiquitous in the educational context. A vast architecture of legal requirements governs educational institutions and also provides for student and parent rights. An elusive hacker has a taunting message for Japanese police: Catch me if you can.A series of riddles were sent to newspapers and broadcasters in the country Saturday and led to the discovery of the cat. The memory card supposedly contains information about a computer virus, although its contents were not immediately disclosed, according to AFP.The cyber stunts started about six months ago and have been originating from around the country.
jordan 1 shoes for sale


*vulume    (2015-06-15 13:15:26)
Il y a 8 ans

Compared to the US over half a trillion. Venezuela has the largest amount of confirmed oil reserves of any country on the planet. That just the plain math of health insurance  some people cost more than others. Same thing happens in life insurance, disability, car, house, boat, you name it.
pantone blue 11s ht*p://www.szzyedu.com/students/a1e40b-where-to-buy-jordan-retro-3.html


*xixona    (2015-07-15 15:53:07)
Il y a 8 ans

I'm afraid that number's ex-directory shades essay writer officer "We're really trying to build that community so if they are the only woman in a class or on a project team they don't feel like the only one," says Tricia Berry, director of UT—Austin's Women in Engineering program. Female students account for just 10 to 15 percent of students in certain engineering majors at the university, Berry says.
toms shoes


*rofaku    (2015-07-30 17:09:37)
Programmer un forum en PHP

Doh! I was domain name shopping at namecheap.com and went to type in the domain name:  and guess who already acquired it? You did! lol j/k. I was about to purchase this domain name but realized it was taken so I figured I'd come check it out. Great blog!
burberry outlet online


*joboxa    (2017-04-24 22:39:26)
Il y a 6 ans

Have a nice day The problem that I want to discuss have been disturbing me since my graduation. This is all about dissertation writing process.
The problematic question appears first of all for those who is ignorant in his or her topic for any reason. This Resource reveals some information, tips and solutions for such people. Just check it out
Hope I'll get other good advices at this thread


*vucaso    (2018-05-28 04:40:13)
Il y a 5 ans

It s especially important for children to be able to hear correctly. (Xinhua/Li Xueren)BEIJING, Sept. Cheap NHL Jerseys Wholesale."The resolution stresses that Xi's thought must be upheld on a longterm basis and constantly developed. This can provide a startle and prevent you from being able to move out of the way as quickly as you should . This eye problem is considered to be an age related procedure.As Xi put it, "Countries should adopt a concept of common, comprehensive, cooperative and sustainable security, and jointly respond to security challenges..Cheap Jerseys China.Wholesale NFL Jerseys China. In case you know everything there is certainly to learn about arthritis, you may find that it is a manageable condition.Companies or individuals that break rules will be penalized in various ways. The ingredients in these capsules can metabolize complex foods that produce gas on indigestion. This popular herb can grow all year long in the appropriate conditions.com Is Deer Hunting In Utah As Very good As It Employed To Be?A single thing that is clear to anybody who has hunted mule deer in Utah for any duration of time.<br>Visit my site:ht*p://www.wholesalenfljerseysforcheap.us.com/


*gozudo    (2018-06-23 09:46:41)
Il y a 5 ans

NASA confirmed that many viewers experienced "technical difficulties" with the live feed. Some provinces such as Chiang Mai in northern Thailand, has recorded a temperature of 39 degrees Celsius even after the Songkran Festival, known as Thailand's hottest period has passed."It's no longer the case that consumers purely buy a refrigerator just to store things" said Zhang. [url=http://www.cheapnikenfljerseysshop.us.com/]Wholesale Jerseys China[/url].S.48 Canadian dollars (18. With such huge savings, you can also spring for one of the brand’s signature clutches.00 percent to 44.[url=http://www.cheapnikenfljerseysshop.us.com/]Cheap Jerseys Free Shipping[/url].Teammate Huang Yuguo, who only managed fourth in the individual allround, made it a Chinese onetwo with a score of 15.. Different fighting styles is taught and learned all over the world. Nine key members of Church of Almighty God were arrested in Changde, Hunan province on June 5.The TSX Telecommunications received a lift when Rogers Communications Inc, the largest wireless communications firm in the country saw shares jump 1.[url=http://www.cheapnikenfljerseysshop.us.com/]Wholesale NFL Jerseys[/url].<br>Visit my sitehttp://www.cheapnikenfljerseysshop.us.com/


*fivipa    (2019-06-04 14:51:46)
Il y a 4 ans

Discover what's the deal with ingbacks? According to Wikipedia, WP supports automatic pingbacks where all the links in a published article can be pinged when the article is published?we supply cheap nfl jerseys That explains why I get messages about new comments? when posting an edit that cross-references another post of my own. Info on trackbacks and pingbacks in WP here.
cheap replica jerseys ht*p://www.araq.net/wholesalejerseys.asp


ficgs
Suggestions


ficgs
Plus de sources

Vous devez vous enregistrer pour consulter ces sources, vous pourrez alors changer leur ordre en cliquant sur les icones les précédant.



admin
Autres sources

Ce projet est collaboratif, vous pouvez remonter les sources suivantes dans la liste si vous les trouvez utiles.


 Programmer un forum
commentcamarche > forum/affich 28813
  1. Salut, Pourrais tu me dire comment procéder (en gros) en
  2. « Nous sommes présents à toutes les étapes de la recherche de
 PHP Application Design - SitePoint Forums
sitepoint > forums/forumdisplay.php?f=147

Ways to discover what design patterns to use - semantic approach...
How does one move the balance of payment to next month for an...

 Comment * ? - Yahoo! Questions/Réponses
fr.answers.yahoo > question/index?qid=20070313024112AAy8gpC

Je recherche un client torrent qui fonctionnerait sous linux opensuse...
Quel est le salaire moyen pour un ingénieur de développement en...

 Programmer un forum - Langage interprété(Php, Perl...) - Programmation - FORUM Jacky-PC - Syndrome-OC
soj.mesdiscussions > soj/Programmation/LangageinterpretePhpPerl

et ca doit bien être le truc le plus complexe et le plus lourd à...
commence par apprendre le php, fait juste un chat en php déja et...

 Unicode for the working PHP programmer
ibm > developerworks/library/os php unicode/index

', arrows: false, dropShadow: true, cluetipClass:...
client before results begin to look sensible, effective Unicode...

 Joomla! • Information
forum.joomla > viewtopic.php?f=177&t=360935

 Comment programmer son forum?
infos du net > forum/268063 8 comment

Right Column Post Anti Rebound (user from ggl) * 3...
Right Column Post */ path+=...

 JOB LISTING: Junior/Senior PHP/MySql Programmer
forum.seopedia > servicii web jobs/5725 job listing junior senior php mysql

Caut doi programatori pentru angajare fulltime (1 Senior si 1...
Web Site Marketing ť JOB LISTING: Junior/Senior PHP/MySql...

 Job - PHP Programmer - VisualART Forum
visualart > forum/showthread.php?t=18387

with - your resume in plain text format - your contract rate...
You should be capable of rapid development of complex PHP modules...

 intermediate computer programmer - WordReference Forums
forum.wordreference > showthread.php?t=80123

 WEB DEVELOPER (PHP programmer) - Comunitatea PHPRomania PHP, MySQL, Apache, Ajax, Web 2.0
phpromania > job/226 WEB DEVELOPER (PHP

 PHP Programmer Needed ($) - Dev Shed
forums.devshed > project help wanted 40/php

Safari Books Online provides searchable, on-demand access to...
Warburton's the largest independently owned bakery in the UK faced a...

 Umed Mardonov - Senior PHP,Coldfusion,Database developer - JSC "Modern" Programmer / Developer, Tajikistan - oDesk
odesk > users/Senior PHP Coldfusion Database developer ~~6761f7f11d1b364e

Javascript must be enabled to properly navigate this...

 5 Regular Expressions Every Web Programmer Should Know - I’m Mike
immike > blog/2007/04/06/5 regular expressions every web

 Urgent: PHP Programmer Philippines
sulit.com > index.php/view+classifieds/id/1262362/Urgent:+PHP+

Performance of internal testing of the web application and database,...
Lose Weight, Gain Weight, Look Good and Feel Great! Herbalife...

 Comment creer son forum en PHP ? [serieux]
presence pc > forum/ppc/Programmation/serieux creer forum sujet 64 1.htm

Entre : Ce que je pense, ce que je veux dire, ce que je crois dire,...
Database Server Hostname/DSN: Your Database Name: Database...

 php jobs in USA | careerjet.com
careerjet > php jobs

Clearcase Support Engineer (Clearcase, Perl/PHP, Linux, Unix, systems...
Job Description Candidate should have more than eight years of...
The ideal person will have strong web development/programming using...

 ATVGC - Powered by Discuz!
atvgc > forum/redirect.php?tid=33&goto=lastpost

 Webcron.org - Cron job - Crontab online - Home
webcron > index.php?lang=en

 Recherche spécialiste php - pour programmer un site associatif (Clubic.com)
clubic > forum/emploi informatique high tech/recherche specialiste php pour

Modérateur Logiciel Multimédia / Programmation / Petites Annonces...
[Site Web] Projet novateur, homepage personalisé - PHP/MYSQL/JS...

 Lead PHP programmer quits
digg > programming/Lead PHP

 CCS :: View topic - Why Program can work under ICD2 programmer mode?
ccsinfo > forum/viewtopic.php?t=21415

BUt when I use ICD2 as the programmer and wanna burn the hex file...

 hourly rate for PHP programmer - PHP - Web Development
forums.whirlpool.net > forum replies archive.cfm/889301

 [NDS] Arcomage - :: PlayerAdvance.org ::
playeradvance > forum/showthread.php?t=3746

Arcomage est un jeu de cartes de type Heroic Fantasy, qui fit sa...
! Je tiens à préciser (j'ai oublié dans la description, que la...

 LOOKING for a talented PROGRAMMER for NOAH's CLASSIFIED Component Project... - Mambo - Forums Closed for posting
forum.mamboserver > showthread.php?t=53532&page=4

If the code (for Noah) was changed then this would violate the...
Not trying to be argumentative here, but you're talking about...
The Noah's Classifieds software may be downloaded and...

 Offerte Lavoro It - (php, Java, Etc.) - Pagina 3 - Forum Sognando Londra
sognandolondra > it/forum/cerco offro lavoro/217 offerte lavoro php java etc 3

Analista programmatore senior - JAVA, JSP, WINDOWS...
Junior Analyst Programmer (Oracle) 25-28k - Manchester Salary:...
L'ufficio di SognandoLondra si trova al numero 3 di Leigh Street,...

 TipidPC.com | magkano na ba sueldo ng programmer?
tipidpc > viewtopic.php?tid=82847

 ZonePROG.com [Programmer avec DirectX c'est possible]
zoneprog > directx/dxsdk.php

New encoder application programming interface (API) specification:...
The standard effects support parameter curves (when hosted outside of...

 TP arci
daoc.clans > forum/index.php?topic=1957.msg9085;topicseen

Ywain Ywain Ywain Ywain Ywain Ywain Ywain Ywain Ywain Ywain Ywain...
Buone vacanze estive a tutti!!!! Anche a chi, come me, sta a casa...
Heldegar, ti levo quella parentesi nel nickname? sembri quasi un...

 Lead PHP programmer quits (Page 1) - General discussion - PunBB Forums
punbb.informer > forums/topic/12526/lead php

 Programmer un jeux de poker sur Internet - Page : 1 - PHP - Programmation - FORUM HardWare.fr
forum.hardware > hfr/Programmation/PHP

--------------- What if I were smiling and running into your...
est ce que l'on peux programmer la deconnection d'un peripherique...

 40 signs you really are a lousy PHP programmer // Reinhold Weber
reinholdweber > ?p=19

 Flash Programmer - ActionScript 2.0 [Remunerated job] - ActionScript.it - il Forum
actionscript > forum/showthread.php?t=25094

 Print Page - On developer's block, and calling it quits. Being a programmer is hard
donationcoder > Forums/bb/index.php?action=printpage;topic=17537.0

Without you and your colleagues the entire system would soon grind to...
Quote from: zridling on April 08, 2009, 03:51:38...

 programmer un chat avec Webcam en php - Forum des développeurs
developpez > forums/d482695/php/scripts

ame_toggle_view({other : 'true',post : 'true',blog : 'true',group :...

 LAN-PARTY :: Vis forum - Programmer/Spill/Hardware
ungirindal > phpBB2/viewforum.php?f=6&sid=f8f84ef634948e5121ee88b9ac499b6d



Response  
 

Guest name   (option)     Register
Please sum : 3608 + eight  




Trackbacks : If you talked about this article in your blog or website, you may instantly get a backlink 
There's no trackback at the moment.