Как написать форум на php
Перейти к содержимому

Как написать форум на php

  • автор:

How to Create a Forum in PHP from Scratch

In this tutorial we’ll see how to make a forum using PHP and MySQL. We have to cover a lot of different things, so let’s start!

Some details about this tutorial

  • You can download a compressed folder with the whole project inside. So sometimes I won’t show all the code of a file in order to focus on the important parts of the project.
  • The code I’ll show is exactly the same than the one you can download, except for some comments. In the original project you’ll have everything well documented (using phpDocumentor).
  • I’ll ommit the <?php and ?> tags in the tutorial, but every time you type PHP code in a file you should put it between them.
  • This project doesn’t follow a MVC pattern, but we’ll use classes and try to separate the different functionalities.

What and how

What are we going to do? We have to think the answer very carefully, and not only “a forum”, also the functionality we want to offer.

Answer: We are going to develop a forum where anyone can write a post without registration and other people can see it and write a response.

How are we going to do that? Here we have to think about how we are going to organize the project, the files..etc

Answer: As you know we are going to use PHP and MySQL. The files are going to be organized by the code they implement, so a class file will be in a different folder than a CSS file, for instance.

Designing and Building the Database

When we start to code a project, the first thing we usually do is to think about the database. Because that decision is going to be very important, and a lot of the PHP code depends on it.

There are many options here, we could make a table of posts and another of users, even three tables if we want, but we’ll take the easiest way in order to focus on the PHP code.

DB Schema

This table is all we need, at least for a simple forum like ours.

So a thread is going to consist of several rows in the table. The first post of a thread is going to have the permalink_parent set to NULL, and the rest of them are going to have the permalink_parent with the permalink of their parent, as the name suggests.

To create the table we have to execute the following sentence in our database:

The lengths of some fields depend on how many people are going to use the forum, but these values are enough for the moment.

Note that we are defining an UNIQUE KEY over the permalink column, which means that in our forum a title must be unique, I know we usually can post a couple of threads with the same title in other forum, however for the sake of simplicity we are keeping the title as unique.

File Organization

As well as designing the database we need to think about how we are going to organize the project, instead of starting to code without a previous plan.

The title and permalink are going to be unique, so we have to check if a title is taken.

At this point we can also take different approaches, we should try to keep things as simple as we can. So this is a little schema of our final project.

File Schema

As you can see there are many files, but all of them are necessary if we want to keep things organized. Let’s see them step by step, and try to get the techniques we’ll use.

The media folder

This tutorial is focus on the PHP side, so I won’t explain too much about the CSS and the HTML code, you can download all the code at the end of this tutorial, so don’t worry. Anyway I’ll try to summarize the content of this folder.

  • style.css. It’s the CSS file for all the forum, includes the reset CSS code and the rest of the styles like a regular CSS file.
  • bg_container.png. The background of the main container.
  • bg_body.png. The background of the body element.

The Configuration File

This file is going to be useful from almost every script of the project. There are different options to implement it, but probably the most used is just a file with some define() lines, like this:

I’ll explain later the two last lines. So from now on every time we include the file we can get the value of a constant with something as simple as this:

Header and Footer

There is a part of the HTML code that isn’t going to change so we can write once and include the file every time we need it. This is very simple and it will save us time and lines of code.

Header

The header.html file will have all we need to build the first part of a page: the doctype tag, the html, head, the beginning of the body element, the link to the CSS file…

As you can see the #main and #wrap divs, the body and html tags are open so we have to close them in the footer.

Footer

The footer.html file is very similar, we’ll include it when we finish the output to “close” the page.

We are loading the jQuery at the bottom of our page, which is a good practice, because the rest of the site will be rendered before we execute any jQuery code.

The jQuery code is basically to improve the interface, so when a user clicks on an input field all the text will be selected. The if works in this way: when we see the p element (in #message_header) has something, then we hide it with the slideUp effect after 5 seconds. You can see this code working in the live demo after you try to post a message with an empty field or if the title you have selected is already taken.

The difference between require and include is the include() construct will emit a warning if there is an error (script goes on) and require() will emit a fatal error (script stops). As you may guess, adding _once to those statements we prevent the file from being included twice. Let me show you the final result with something very simple like this:

Header and footer with a simple message

Great! Now we have our “template” and all we need to output will be shown between the header and the footer code as long as we include these files.

The Database class

In order to separate the PHP code that is going to execute SQL queries and the rest of PHP code we’ll make a database class, this class will connect to the database, get some rows and save data.

If we think about it, if an object always need to connect to the database, the connection code must be in the constructor. So every time we create an object that object is going to be ready to execute queries with the function mysql_query().

Also, the methods we’ll need are going to depend on the rest of code, but here I show you the beginning of the class as it will be in the end of the development:

Probably the most important method is savePost, so let’s take a look at it apart from the previous ones.

Note when we create the $query string, we use sprintf to make the code cleaner.

The method isValidPost is private and its code is:

The different numbers we return in the savePost method have a meaning (we’ll see it later), but, basically we have to recognize different kind of errors to show a different message each time, so we can’t return just false, and the use of exceptions could be complicated for the beginners.

This is actually a classic approach to manage the database from the PHP code, we’ll see at the end of the tutorial what people are using now and why we should use it too. But this class is enough for us and I assume readers know a little bit about PHP probably also know this way to connect to the database and manage queries.

Validation Helper

This script (helpers/validation.php) is just a group of functions we’ll use all over the project. There are 3 functions here:

String to Permalink (strToPermalink)

Takes a string as input and creates a human-friendly URL string. Its implementation is:

To sum up all we do here is to remove “weird” characters like á or é and others, and then convert -, spaces and others into _. (Permalink is also known as slug or even permanent link).

Clean input (clean)

Here we take care of removing slashes if magic_quotes_gpc is enabled and escaping some characters with mysql_real_escape_string. Don’t worry if you don’t know what magic quotes are or why we code this function, when we talk about security you’ll understand it.

Process post (processPost)

This function has a lot of lines (compare to the rest of this file), I’ll try to explain all of them without code:

  1. Prepare the array to be returned with all values initialized as NULL
  2. If it has everything in the array to start, then checks if the Recaptcha answer is OK, generates the permalink, tries to save the post and returns a message.
  3. If the input array is not empty but it hasn’t got all we need OR the Recaptcha input field is wrong, then it returns an error message.
  4. Finally, the showBox variable in the array is set. The box we’ll be shown if there was an error, or always in case we are in the page where users can write a response.

I’ll explain Recaptcha later, now let’s focus on the rest of the code. The array it will return is initialized in this way:

Then we code the steps 2 and 3 of the list we did before.

You can see here the different kind of errors we return and the reasons. Finally we set the showBox variable of $returnArray:

The View Class

There is a part of the HTML code that depends on some parameters that come from PHP. To keep things as clear as we can we are going to make a class exclusively for this purpose.

The home page is going to show a list of threads, so let’s code that method and the constructor of our new class:

The htmlspecialchars function provides a way to change some HTML elements into entities, so every time we are going to output something from the database we should use this function. We’ll se more about this later.

The next method we’ll code is composeTable, and it will be useful to show all the posts of a thread.

If we call the method from view_thread.php it means we are in a thread that doesn’t exist, so we show a different message in that case.

Now we need to create a form for users who want to send new posts (responses or the beginning of a new thread).

Recaptcha or how to avoid spam

At this point we have to think about the spam problem. As you can see there is no registration process so anyone can just fill the form and post a message with the content they want every time they like. How to handle the input will be discussed later, but the problem here is a bot could fill the form and submit it.

How can we avoid that? Well, the easiest and probably most used solution is a captcha system. Yes, those boring images of characters we have to identify and replicate. Specifically the implementation bought by Google, Recaptcha.

But what are the guarantees? Well, Twitter uses it in the sign up process and if we forum doesn’t grow too much (actually like Amazon or Google) we won’t have more problems. The question now is: how can we use it?

Recaptcha provides a file (in our project is helpers/recaptcha.php) and there we have all the functions we need, actually even more. You can see the documentation at the the end of the tutorial.

Finally, the other two methods are messageBox and buttonPostThread. The first one will return a string with the HTML needed to compose a post (a form) when we need to and the second one just returns a div to go to post_message.php and create a new post.

The $new parameter indicates if the form will be shown in post_message.php to send a new thread or in view_thread.php (to send a response). This will helps, for instance, to ask for the title of the thread if it’s going to be a new one or not.

The $recaptchaError is what we need to render properly the box with the captcha and the input, because in case the user types wrong the code the recaptcha_get_html will take care of showing a message.

Finally, the $errorHTML could contain an string of an error and we have to show it here. (We’ll see later what kind of errors could happen).

The last method will be buttonPostThread, and as I’ve said before its only functionality will be to return a string, but the reason we make it is to keep consistent the idea of not writing HTML code in some scripts like index.php or view_thread.php, besides of that the code of these pages will be very clear if we keep that idea in mind.

Probably you are thinking: “why all this code if we haven’t written a script which shows anything directly?”. And it’s OK you wonder that, but now you will see the advantages of having a modular and independent code.

Home page

Let’s start with our first page, index.php. These are the things we have to show:

  • Header
  • List of threads OR a warning if there aren’t threads
  • Link to make a new thread
  • Footer

The code is as simple as this list:

The output in the browser with 3 threads is:

Home

Create a new post

The post_message.php script is going to show a form, get the input and try to process this input as a new post. If everything is ok we’ll show the link to the new post, otherwise we’ll show an error message.

The processPost function is implemented in helpers/validation.php and, as I’ve explained before, processes the input, tries to save the post and return an array with different values. This is the output in Firefox:

Post Message

View Thread

The view_thread.php script will combine a couple of things.

  • We have to get some posts, the initial one first, and show them properly.
  • The form to write a response is going to be almost the same than the one we did to write a new thread. (Hint: We’ll use the same function).

The first thing we do is to include all the files we need and clean the input ($_GET) with a function (implemented in the helpers/validation.php file).

Here we process the $_POST array and create a “message box”, a form to send a response to the thread.

Finally we print the posts and the form to write a new response. In case we get a false value from messageBox we’ll show an error because there isn’t a thread with that permalink.

So all these parts together compose our view_thread.php script. Here we have the final result with a thread and a response to the first post:

View Thread

MySQL from PHP alternatives

We have used some functions to manage the database like:

The reason I’ve used these functions is because they are well known by the most of novice PHP developers, but you should know these functions have lost their popularity. I’ll explain you why.

Actually, there are many reasons, the mysql functions provide a procedural interface, doesn’t support a lot of things in the new versions of MySQL (newer than 4.1.3) and have more security problems. So take a look at the alternatives:

MySQL Improved (mysqli)

This extension was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. Some features are:

  • Object-oriented interface
  • Support for Prepared Statements
  • Support for Transactions

Apart from that is more secure than the mysql classic extension because we can use bound parameters (details in links at the conclusion).

PHP Data Objects (PDO)

The main difference is this API can be used with any kind of database (in theory), that means it doesn’t have to be MySQL. So the change of the database system in the project it’s going to be easier.

But like yin yang there is a disadvantage, some advanced new features of new MySQL versions are not supported. Anyway is usually better use this or the previous alternative than the classic mysql extension.

Comparative from official documentation

Comparative of MySQL extensions

The details of how to use mysqli or PDO are in the official documentation.

The security issue

First of all I have to say I’m not a security expert but if you are going to make a web app you need to know the possible security holes, and try to prevent attacks, not being a hacker doesn’t mean you don’t need to know about security. So let’s see the most common attacks in a web app, and how to prevent them in our forum.

Cross Site scripting (XSS)

XSS exists when your PHP code outputs some data that has neither been filtered nor escaped. Some code like this is vulnerable to XSS:

That means someone could send whatever they want in a form and will be shown later, and that’s very dangerous. The simplest thing they can send is:

So the the code will be executed by the browser. A more dangerous use, could be extract cookie content with javascript and log in a system using that cookie. So, now we have understood it’s dangerous, how can we prevent it?

We have to escape data which comes from users. In this forum we have made a couple of things. First of all we strip the HTML and PHP code with strip_tags(), and when we show data from database we escape using htmlspecialchars(). Let’s see some code:

As you can see the script tags are not shown so the alert will not be executed. But Hercules wanted to show his name with strong tags, and actually it’s harmless, but we removed those tags too. A possible solution is to provide a list of our own tags and then replace them with the actual HTML elements. We haven’t implemented this, but it would be very easy:

The other thing we do is to use htmlspecialchars(), this is redundant because with strip_tags HTML code will be removed and not inserted into our database, but there are some characters which do nothing so we can convert them into HTML entities. Remember it’s usually better to a be a little bit paranoid when we talk about security.

The output is exactly the string, but some characters are actually HTML entities, so the code is not executed, just shown in the browser.

SQL injection

This vulnerability is, as the name suggests, when someone injects SQL code into your web app. Here we have to take care of a couple of details, but let’s see the main problem.

We have a query with some variables from $_POST, something like:

What if someone sends: ‘ or 1=1 ; — as the password? The query would be:

So the WHERE condition is always true because (1=1) is, and (false) || (true) is also true. Consequence? The query selects all the records.

A simple way to prevent this is to use the function mysql_real_escape_string() which escapes special characters in a string taking into account the current character set of the connection so that it is safe to place it in a mysql_query(), as we do in the clean function (helpers/validation.php file).

But still there could be a problem with slashes and magic_quotes. To summarize magic_quotes is something annoying and we have to deal with it. Magic quotes is a deprecated PHP configuration that, when turned on it automatically escapes characters for you.

The problem is sometimes we don’t want that, so in our forum when we clean the input we use stripslashes() in case magic_quotes is turned on, which un-quotes a quoted string, and from that point we escape the data. (see clean function at the beginning of this tutorial). So with this implementation we can insert O’connor, and it won’t be a problem, without this consideration, the input could be inserted as O\’Connor into the database.

There could be a problem with the magic_quotes_sybase configuration, but, apart from being deprecated, it’s turned off by default so usually it won’t be a problem, and in our forum we don’t deal with it.

If we had used other alternative to manage the database from PHP, a lot of these precautions wouldn’t be necessary, you have more details in the official documentation.

Cross-Site Request Forgery (CSRF)

According to Wikipedia, is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts. But we don’t have to worry about that since our forum is open to anyone who wants to write and there aren’t sign up and log in processes. Anyway at the conclusion you have some links in case you want to know more about this exploit.

How to set up your own forum

When you download the code, you have to follow the next steps to have your own forum working:

  • Get a Recaptcha key here.
  • Create a database with the SQL query at the beginning of the tutorial.
  • Change the values of constants in the config.inc.php file with yours.
  • And, of course, put the files where you can access with PHP and Apache working (localhost’s directory).

Conclusion

I have to admit this tutorial is long but if you read it a couple of times and take a look at the code I’m sure you’ll be able to understand all the project.

The organization of code in classes and files is up to the developer. And as long as we don’t write the same code over and over again, or just type queries, html and PHP code in the same file, the project will be ok. I mean, everything about make more or less classes or create a specific function is not a science. It’s more a design problem, so feel free to think about other ways to develop this forum, it will help you to be a better developer.

For instance I could have written a post class, or make everything procedural, but this was just an approach, and you can see the power of this in how many lines we have written in our index or post_message web pages. In addition, if we need more features the development will be very easy since everything is well documented in the files you can download.

There is other feature we could implement, to set the value of the inputs to the content of $_POST if it’s received, but that could make the code the code less clear, so I’ve avoid it in order to make things easier.

Here you have some links to some sites where you can learn more about security, PHP and MySQL.

Пишем форум на PHP

Если вы имеете некий опыт блужданья по интернету, должны знать, что каждого второго жителя сети так и прет где-нибудь да наследить, и если некий сайт предоставляет такую возможность, то персона, сделавшая целью собственного бытия изливанье на бел свет содержимого своего внутреннего мира, непременно зависнет на нем.. Предпосылкой этому будет, само собой, служить соответствие тематики сайта этому самому содержимому..

Как бы то ни было, но научиться создавать на сайте сервисы, позволяющие оставлять некую информацию, необходимо. В их число входят форумы, комментарии, доски объявлений (рассчитаны на произвольнго пользователя), новостные ленты (рассчитаны на владельца сайта), и прочие.

Так.. Я думаю, что сама техника отправки и сохранения текста сложности вызывать не должна — заполнил форму, кликнул "поехали!" и лицезреешь "здесь был Вася" на форуме или на чем-то подобном.
Потому я предпочту обсудить в этом уроке различные варианты архитектуры вышеупомянутых скриптов. А если тот или иной способ ее реализации будет стоить того — опишу и его.

Начну, пожалуй, с форума. Итак, как правильно спроектировать форум?
Для начала, пропишем его функции.
Здесь встаем перед определенной дилеммой: требовать ли с посетителя регистрации на форуме, или нет.
Посмотрим на проблему с двух точек зрения, а именно — с нашей, программистской, и с точки зрения пользователя.
— пользовательская точка зрения —
«Что дает мне регистрация на данном форуме?»
Тут же переключаемся на точку зрения владельца форума —
«Зачем мне регистрация пользователей?»
Ответ — да мне ж надо удержания их у себя на сайте, да увеличить количество посетителей (если форум интересен, то зарегестрировавшийся пользователь привлечет своих знакомых, коллег).

Итак, мы должны обеспечить ряд идей, удобств и сервисов, способствующих регистрации на нашем форуме и увеличению числа посетителей. Подумаем, что именно стоит для этого сделать.

Во-первых, форум должен быть четко структурирован, как и любой информационный ресурс. А именно иметь строгое разделение по темам и подтемам. Его участники не должны путаться и чувствовать какие бы то ни было неудобства при поиске информации.

Необходимо отметить, что администратор форума должен почаще отслеживать какие темы создаются на форуме, чтоб всякие кретины, кторым нехрен делать, кроме как засирать ваш ресурс, не портили структуру форума.

Приступим к реализации! Коль мы решили сделать форум с регистрацией, начнем именно с нее.
Урок по регистрации и авторизации (php) на сайтах приведен здесь. Если необходимо, просмотрите его, а я пока поговорю о том где и как мы будем хранить информацию о пользователях форума.
Держать все будем в Б.Д. Основные данные о юзерах — в таблице users_main, имеющей следующие поля:

id — уникальный идентификатор в таблице, будет увеличиваться на 1 при регистрации нового пользователя.
login — логин пользователя
pass — пароль
nick — никнейм
email — почта пользователя.
reg_date — дата регистрации
status — статус пользователя (зарегестрирован/не зарегестрирован)
confirmation_id — идентификатор подтверждения регистрации.
Как _первичным_, так и _внешним_ ключем будет служить id.
Зарегестрированные пользователи смогу хранить дополнительную информацию о себе, она будет помещена в таблице users_secondary.

id — идентификатор пользователя (соответствует id в users_main)
name — Реальное имя
surname — фамилия
skype — скайповский контакт.
icq — аська
last_date — дата последнего посещения
last_time — время последнего посещения.
Также нам нужна таблица themes, где мы будем хранить темы, созданные на сайте и привязывать их к конкретным пользователям.

theme_id — идентификатор темы, первичный ключ.
theme_title — наименование темы.
section — тематический раздел, коему сессия принадлежит.
user_id — идентификатор пользователя, создавшего тему
theme_date — дата создания темы
Еще таблица с сообщениями пользователей messages.

msg_id — идентификатор сообщения
msg_text — текст сообщения
msg_date — дата оставления сообщения
user_id — идентификатор пользователя, оставившего сообщение.
theme_id — идентификатор темы, в которой находится сообщение
Начнем писать код.

Build Discussion Forum with PHP and MySQL

In this tutorial we will explain how to develop your own discussion forum system with PHP and MySQL. We have created a running forum example in this tutorial and can download complete example code to enhance this to create own forum.

Forum systems is place for people where they can start discussions on topics. The forum is controlled by administrator or moderators who creates forum categories and manage permissions for forum.

The registered members can create own discussion topics or can participate in existing discussions. The guest members also allowed to create and participate in discussions.

Also, read:

So let’s start developing discussion forum system with PHP and MySQL. The major files are:

  • category.php: File to list categories and category topics.
  • Category.php: A class to keep methods related to category.
  • Topics.php: A class contains methods related to topics.
  • posts.php: File to list topic posts with quick reply editor.
  • Post.php: A class contains methods related to posts.

Step1: Create MySQL Database Table

As there are categories, topics, posts in forum, so first we will create MySQL database table forum_category to store categories.

We will create table forum_topics to store category topics.

We will create table forum_posts to store topics posts.

We will create table forum_users to store user.

Step2: Category Listing

We will implement design and functionality to list forum categories. For this, we will make changes into category.php file. We will call method getCategoryList() from class Category.php to get category list.

We will implement method getCategoryList() in class Category.php to get categories from MySQL database table forum_category and return.

Step3: Topics Listing

We will make design changes and implement functionality to list visited category topics. For this, we will make changes in category.php file and call method getTopicList() from class Topic.php to list category topics.

We will implement method getTopicList() from class Topic.php to get category topics list from table category_topics to list topics.

Step4: Posts Listing

We will implement functionality in file post.php to list post replies of topic. For this, we will call method getPosts() from class Topic.php to list topic posts.

We will implement method getPosts() in class Topic.php to get topic posts from table category_posts to list them.

You may also like:

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download

2 thoughts on “ Build Discussion Forum with PHP and MySQL ”

I added some posts and Categories in DB but only got one post
so i changed Topic.php on line 49 from
“LEFT JOIN “.$this->postTable.” as p ON t.topic_id = p.post_id”
to
“LEFT JOIN “.$this->postTable.” as p ON t.topic_id = p.topic_id”

Please help me, this tutorial is fun, the only thing that I don’t understand is how to let user login and after they can post .

Как создать форум с поддержкой PHP / MySQL с нуля

В этом руководстве мы собираемся создать форум с поддержкой PHP / MySQL с нуля. Этот учебник идеально подходит для привыкания к базовому использованию PHP и баз данных.

Если вам нужна дополнительная помощь по этому или другим вопросам, связанным с PHP, попробуйте связаться с одним из разработчиков PHP в Envato Studio. Они могут помочь вам во всем – от исправлений PHP до разработки надежных приложений PHP.

PHP разработчики на Envato Studio

Шаг 1: Создание таблиц базы данных

Всегда полезно начинать с создания хорошей модели данных при создании приложения. Давайте опишем наше приложение одним предложением: мы собираемся создать форум, на котором есть пользователи, которые создают темы в различных категориях . Другие пользователи могут оставлять ответы. Как видите, я выделил пару существительных, которые представляют имена наших таблиц.

пользователей

  • категории
  • темы
  • Сообщений

Эти три объекта связаны друг с другом, поэтому мы будем обрабатывать их в нашей таблице. Посмотрите на схему ниже.

Выглядит довольно аккуратно, а? Каждый квадрат – это таблица базы данных. Все столбцы перечислены в нем, и линии между ними представляют отношения. Я объясню их далее, так что все в порядке, если это не имеет большого смысла для вас прямо сейчас.

Я буду обсуждать каждую таблицу, объясняя SQL, который я создал, используя схему выше. Для ваших собственных скриптов вы можете создать аналогичную схему и SQL тоже. Некоторые редакторы, такие как MySQL Workbench (тот, который я использовал), также могут генерировать файлы .sql, но я бы порекомендовал изучать SQL, потому что гораздо интереснее делать это самостоятельно. Введение в SQL можно найти в W3Schools .

Таблица пользователей

Конечно, оператор CREATE TABLE используется для указания того, что мы хотим создать новую таблицу. За оператором следует имя таблицы, а все столбцы указаны в скобках. Имена всех полей не требуют пояснений, поэтому мы обсудим только типы данных ниже.

ID пользователя

«Первичный ключ используется для уникальной идентификации каждой строки в таблице».

Тип этого поля – INT, что означает, что это поле содержит целое число. Поле не может быть пустым (NOT NULL) и увеличивается на единицу, добавляемое каждой записью. Внизу таблицы вы можете видеть, что поле user_id объявлено как первичный ключ. Первичный ключ используется для уникальной идентификации каждой строки в таблице. Ни одна из двух отдельных строк в таблице не может иметь одинаковое значение (или комбинацию значений) во всех столбцах. Это может быть немного неясно, поэтому вот небольшой пример.

Есть пользователь по имени Джон Доу. Если другие пользователи регистрируются с тем же именем, возникает проблема, потому что: какой пользователь какой? Вы не можете сказать, и база данных также не может сказать. С помощью первичного ключа эта проблема решается, поскольку обе темы уникальны.

Все остальные таблицы также имеют первичные ключи и работают одинаково.

user_name

Это текстовое поле, называемое полем VARCHAR в MySQL. Число в скобках – это максимальная длина. Пользователь может выбрать имя пользователя длиной до 30 символов. Это поле не может быть пустым. Внизу таблицы видно, что это поле объявлено UNIQUE, что означает, что одно и то же имя пользователя не может быть зарегистрировано дважды. Часть UNIQUE INDEX сообщает базе данных, что мы хотим добавить уникальный ключ. Затем мы определяем имя уникального ключа, user_name_unique в этом случае. Между скобками находится поле, к которому применяется уникальный ключ, то есть user_name.

user_pass

Это поле равно полю user_name, за исключением максимальной длины. Поскольку пароль пользователя, независимо от его длины, хэшируется с помощью sha1 (), пароль всегда будет длиной 40 символов.

user_email

Это поле равно полю user_pass.

user_date

Это поле, в котором мы будем хранить дату регистрации пользователя. Это тип DATETIME, и поле не может быть NULL.

user_level

Это поле содержит уровень пользователя, например: «0» для обычного пользователя и «1» для администратора. Подробнее об этом позже.

Таблица категорий

Эти типы данных в основном работают так же, как и в таблице пользователей. Эта таблица также имеет первичный ключ, и имя категории должно быть уникальным.

Таблица тем

Эта таблица почти такая же, как и другие таблицы, за исключением поля topic_by. Это поле относится к пользователю, который создал тему. Topic_cat относится к категории, к которой относится тема. Мы не можем форсировать эти отношения, просто объявив поле. Мы должны сообщить базе данных, что это поле должно содержать существующий user_id из таблицы users или действительный cat_id из таблицы категорий. Мы добавим некоторые отношения после того, как я обсудил таблицу сообщений.

Таблица сообщений

Это так же, как остальные таблицы; здесь также есть поле, которое ссылается на user_id: поле post_by. Поле post_topic относится к теме, к которой принадлежит сообщение.

«Внешний ключ – это ссылочное ограничение между двумя таблицами. Внешний ключ идентифицирует столбец или набор столбцов в одной (ссылающейся) таблице, которая ссылается на столбец или набор столбцов в другой (ссылочной) таблице».

Теперь, когда мы выполнили эти запросы, у нас есть довольно приличная модель данных, но отношения по-прежнему отсутствуют. Давайте начнем с определения отношений. Мы собираемся использовать то, что называется внешним ключом. Внешний ключ является ссылочным ограничением между двумя таблицами. Внешний ключ идентифицирует столбец или набор столбцов в одной (ссылающейся) таблице, которая ссылается на столбец или набор столбцов в другой (ссылающейся) таблице. Некоторые условия:

  • Столбец в таблице ссылок, на которую ссылается внешний ключ, должен быть первичным ключом
  • Указанные значения должны существовать в ссылочной таблице.

При добавлении внешних ключей информация связывается воедино, что очень важно для нормализации базы данных. Теперь вы знаете, что такое внешний ключ и почему мы его используем. Пришло время добавить их в таблицы, которые мы уже создали, с помощью оператора ALTER, который можно использовать для изменения уже существующей таблицы.

Сначала мы свяжем темы с категориями:

Последняя часть запроса уже говорит, что происходит. Когда категория удаляется из базы данных, все темы также будут удалены. Если cat_id категории изменится, каждая тема также будет обновлена. Вот для чего нужна часть ОБНОВЛЕНИЯ КАСКАДА. Конечно, вы можете отменить это, чтобы защитить свои данные, так что вы не можете удалить категорию, если у нее все еще есть связанные темы. Если вы хотите сделать это, вы можете заменить часть «ON DELETE CASCADE» на «ON DELETE RESTRICT». Также есть SET NULL и NO ACTION, которые говорят сами за себя.

Теперь каждая тема связана с категорией. Давайте свяжем темы с пользователем, который его создаст.

Этот внешний ключ такой же, как и предыдущий, но есть одно отличие: пользователь не может быть удален, пока есть темы с идентификатором пользователя. Мы не используем CASCADE здесь, потому что в наших темах может быть ценная информация. Мы не хотим, чтобы эта информация была удалена, если кто-то решит удалить свою учетную запись. Чтобы по-прежнему предоставлять пользователям возможность удалять свои учетные записи, вы можете создать функцию, которая анонимизирует все их темы, а затем удалить их. К сожалению, это выходит за рамки этого урока.

Связать сообщения с темами:

И, наконец, свяжите каждое сообщение с пользователем, который сделал это:

Это часть базы данных! Это было довольно много работы, но результат, отличная модель данных, определенно стоит того.

Шаг 2: Введение в систему верхнего / нижнего колонтитула

Каждая страница нашего форума нуждается в нескольких основных вещах, таких как тип документа и некоторая разметка. Вот почему мы добавим файл header.php вверху каждой страницы и файл footer.php внизу. Header.php содержит тип документа, ссылку на таблицу стилей и некоторую важную информацию о форуме, такую ​​как тег заголовка и метатеги.

header.php

Div обертки будет использоваться, чтобы упростить стиль всей страницы. Меню div, очевидно, содержит меню со ссылками на страницы, которые нам еще предстоит создать, но помогает понять, куда мы движемся. Div пользовательской панели будет использоваться для небольшой верхней панели, которая содержит некоторую информацию, такую ​​как имя пользователя и ссылку на страницу выхода из системы. Очевидно, что страница содержания содержит фактическое содержимое страницы.

Внимательный читатель, возможно, уже заметил, что мы упускаем некоторые вещи. Нет </body> или </html> . Они находятся на странице footer.php, как вы можете видеть ниже.

Когда мы добавляем верхний и нижний колонтитулы на каждой странице, остальная часть страницы встраивается между верхним и нижним колонтитулом. Этот метод имеет некоторые преимущества. В первую очередь все будет оформлено правильно. Краткий пример:

Как видите, страница без ошибок приведет к хорошей странице с контентом. Но если есть ошибка, все выглядит действительно безобразно; поэтому лучше убедиться, что не только настоящий контент правильно стилизован, но и ошибки, которые мы можем получить.

Еще одним преимуществом является возможность внесения быстрых изменений. Вы можете убедиться сами, отредактировав текст в footer.php, когда закончите этот урок; Вы заметите, что нижний колонтитул меняется на каждой странице сразу. Наконец, мы добавляем таблицу стилей, которая предоставляет нам некоторую базовую разметку – ничего особенного.

Шаг 3: Готовимся к действию

Прежде чем мы сможем прочитать что-либо из нашей базы данных, нам нужно соединение. Вот для чего предназначен connect.php. Мы включим его в каждый файл, который собираемся создать.

Просто замените значения переменных по умолчанию в верхней части страницы на собственную дату, сохраните файл, и все готово!

Шаг 4: Отображение обзора форума

Так как мы только начали с некоторых базовых методов, мы сейчас сделаем упрощенную версию обзора форума.

Вот вам и хороший обзор. Мы будем обновлять эту страницу на протяжении всего урока, чтобы шаг за шагом она больше походила на конечный результат!

Шаг 5: Регистрация пользователя

Давайте начнем с создания простой HTML-формы, чтобы новый пользователь мог зарегистрироваться.

Страница PHP необходима для обработки формы. Мы собираемся использовать переменную $ _SERVER. Переменная $ _SERVER – это массив, значения которого автоматически устанавливаются при каждом запросе. Одним из значений массива $ _SERVER является REQUEST_METHOD. Когда страница запрашивается с помощью GET, эта переменная будет содержать значение «GET». Когда страница запрашивается через POST, она будет содержать значение «POST». Мы можем использовать это значение, чтобы проверить, была ли опубликована форма. Смотрите страницу signup.php ниже.

Многочисленные объяснения есть в комментариях, которые я сделал в файле, поэтому обязательно ознакомьтесь с ними. Обработка данных происходит в три этапа:

  • Проверка данных
  • Если данные неверны, покажите форму еще раз
  • Если данные верны, сохраните запись в базе данных

Часть PHP довольно понятна. Однако SQL-запрос, вероятно, нуждается в небольшом пояснении.

В строке 1 у нас есть оператор INSERT INTO, который говорит сам за себя. Имя таблицы указывается во второй строке. Слова в скобках представляют столбцы, в которые мы хотим вставить данные. Оператор VALUES сообщает базе данных, что мы завершили объявление имен столбцов, и пришло время указать значения. Здесь есть что-то новое: mysql_real_escape_string. Функция экранирует специальные символы в неэкранированной строке, поэтому ее можно безопасно разместить в запросе. Эта функция ДОЛЖНА использоваться всегда, за очень немногими исключениями. Слишком много скриптов, которые не используют его и могут быть взломаны очень легко. Не рискуйте, используйте mysql_real_escape_string ().

«Никогда не вставляйте простой пароль как есть. Вы ДОЛЖНЫ всегда его шифровать».

Также вы можете видеть, что функция sha1 () используется для шифрования пароля пользователя. Это тоже очень важная вещь для запоминания. Никогда не вставляйте простой пароль как есть. Вы ДОЛЖНЫ всегда шифровать это. Представьте себе хакера, которому каким-то образом удается получить доступ к вашей базе данных. Если он видит все текстовые пароли, он может войти в любую учетную запись (администратора), которую он хочет. Если столбцы пароля содержат строки sha1, он должен сначала взломать их, что практически невозможно.

Примечание: также возможно использовать md5 (), я всегда использую sha1 (), потому что тесты показали, что он немного быстрее, хотя и немного. Вы можете заменить sha1 на md5, если хотите.

Если процесс регистрации прошел успешно, вы должны увидеть что-то вроде этого:

Попробуйте обновить экран phpMyAdmin, новая запись должна быть видна в таблице пользователей.

Шаг 6: Добавление аутентификации и пользовательских уровней

Важным аспектом форума является разница между обычными пользователями и администраторами / модераторами. Поскольку это небольшой форум, и добавление таких функций, как добавление новых модераторов и прочего, займет слишком много времени, мы сосредоточимся на процессе входа в систему и создадим некоторые функции администратора, такие как создание новых категорий и закрытие темы.

Теперь, когда вы выполнили предыдущий шаг, мы сделаем вашу вновь созданную учетную запись учетной записью администратора. В phpMyAdmin, нажмите на таблицу пользователей, а затем «Обзор». Ваша учетная запись, вероятно, появится сразу же. Нажмите на значок редактирования и измените значение поля user_level с 0 на 1. Вот и все. Вы не заметите никакой разницы в нашем приложении сразу, но когда мы добавим администратора, у него будет обычная учетная запись, и у вашей учетной записи будут другие возможности.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *