How to create an admin panel for a PHP site from scratch
Find out what a site control panel is for, what features it has, and how to develop it yourself.
Website management tools:
- phpmyadmin to work with the database;
- FTP client to upload or delete files;
- a graphics editor that compresses images;
- text editor in which articles are drawn up;
- analytics service for evaluating the effectiveness of content and advertising.
It is best to collect them in one place, which is called the site control panel.
How to create an admin panel for a website in PHP
First of all, let's create an admin.php file in the root of the site. As long as it looks like this:
<? include("includes/db.php");
$echo = "info";
?>
<!DOCTYPE html>
<html>
<head>
<title>Admin</title>
<link rel="stylesheet" href="admin.css">
</head>
<body>
<div class='wrapper'>
<main class='main' id='main'>
<?echo $echo;?>
</main>
</div>
</body>
</html>This code receives data using the GET and POST methods , processes it, and then outputs something through the $echo variable . To prevent search engines from trying to enter the admin panel, prohibit it from being indexed in the robots.txt file :
Robot.txt
User-agent: *
Disallow: /admin.php
The main elements for the work of the site admin
- Authorization.
- Main page.
- Editing tools.
- Working with the database.
- Statistics window.
Additional site-management features relate to different areas of PHP that cannot be covered in one article. We talk more about everything in the world in the world of PHP on the course “ PHP developer from scratch to PRO ”.
Now let's start writing functions, queries, and validations.
Authorization
To restrict access, let's create a login form in the control panel:
$echo = "<div class='table'>
<div class='tale-wrapper'>
<div class='table-title'>Sign in</div>
<div class='table-content'>
<form method='post' id='login-form' class='login-form'>
<input type='text' placeholder='Логин' class='input'
name='login' required><br>
<input type='password' placeholder='Пароль' class='input'
name='password' required><br>
<input type='submit' value='Войти' class='button'>
</form>
</div>
</div>
</div>";In the $echo variable, we write the HTML code of the form that sends data to the same page. Then they are processed:
function login($db,$login,$password) {
$loginResult = mysqli_query($db,"SELECT * FROM userlist WHERE login='$login'
AND password='$password' AND admin='1'");
if(mysqli_num_rows($loginResult) == 1) {
возвращается true
return true;
} else {
а возвращается false
unset($_SESSION['login'],$_SESSION['password']);
return false;
}
}
if(isset($_POST['login']) && isset($_POST['password'])) {
$_SESSION['login'] = $_POST['login'];
$_SESSION['password'] = $_POST['password'];
}
if(isset($_SESSION['login']) && isset($_SESSION['password'])) {
if(login($db,$_SESSION['login'],$_SESSION['password'])) { $echo = null;
}
}After the form is submitted, the data is transferred to the $_SESSION super array. Then the login() function is called. She makes a request to the database. If it succeeds, true is returned, if not, the data from $_SESSION is removed and false is returned.
Matches in the query are only searched for among administrators, but you can give limited access to other user groups - for example, for moderators, so that they check comments and articles, but do not have access to global settings and deleting posts.
Main page
Now let's create conditions for the user to do something useful. To do this, the GET method passes the name of the page:
if(isset($_GET['act'])) {$act = $_GET['act'];} else {$act = 'home';}
switch($act) {
case 'home':
$article_result = mysqli_query($db,"SELECT * FROM articles");
if(mysqli_num_rows($article_result) >= 1) {
while($article_array = mysqli_fetch_array($article_result)) {
$articles .= "<div class='table-content__list-item'><a href='? act=edit_article&id=$article_array[id]'>$article_array[id] |
$article_array[title]</a></div>";
}
} else {
$articles = "Статей пока нет";
}
$users_result = mysqli_query($db,"SELECT * FROM userlist");
if(mysqli_num_rows($users_result) >= 1) {
while($users_array = mysqli_fetch_array($users_result)) {
$users .= "<div class='table-content__list-item'><a href='? act=edit_user&id=$users_array[id]'>$users_array[id] |
$users_array[login]</a></div>";
}
} else {
$users = "Статей пока нет";
}
$echo = "<div class='tables'>
<div class='table'>
<div class='table-wrapper'>
<div class='table-title'>Страницы</div>
<div class='table-content'>
$articles
<a href='?act=add_article' class='table__add-button' id='add_article'>+</a>
</div>
</div>
</div>
<div class='table'>
<div class='table-wrapper'>
<div class='table-title'>Пользователи</div>
<div class='table-content'>
$users
<a href='?act=add_user' class='table__add-button'
id='add_user'>+</a>
</div>
</div>
</div>
</div>";
break;
}The $act variable gets the value from $_GET['act'], and if it doesn't exist, then just home . Then, using the switch () function, actions are written for each page.
On the main page of the admin panel, all the components of the site are placed with the ability to manage:
- users;
- articles and comments;
- product cards;
- files and images;
- statistics and advertising blocks.
It should also be possible to edit the general site settings: change meta tags, change captcha settings, update the privacy policy, and so on.
Editing
As you may have noticed, in the tables, each row is a link of this kind:
<a href='?act=edit_article&id=$article_array[id]'>$article_array[id] | $article_array[title]</a>The act variable is passed the edit_article value, and the id is the article ID. By clicking on the link, the administrator gets to the editing page:
case 'edit_article':
if(isset($_GET['id'])) {
$id = $_GET['id'];
$result = mysqli_query($db,"SELECT * FROM articles WHERE id='$id'");
if(mysqli_num_rows($result) == 1) {
if(isset($_POST['title']) && isset($_POST['description']) && isset($_POST['text'])) {
$update = mysqli_query($db,"UPDATE articles SET title='$_POST[title]', description='$_POST[description]', text='$_POST[text]' WHERE id='$id'");
if($update) {
$result = mysqli_query($db,"SELECT * FROM articles WHERE id='$id'");
$message = "Успешно обновлено!";
}
}
$article = mysqli_fetch_array($result);
$echo = "<div class='table'>
<div class='table-wrapper'>
<div class='table-title'>Редактирование статьи</div>
<div class='table-content'>
<a href='?act=home'><- Вернуться</a><br>
$message
<form method='post' class='article-form'>
<b>Название:</b> <input type='text' name='title' value='$article[title]'><br>
<b>Описание:</b> <textarea name='description'>$article[description]</textarea><br>
<b>Текст:</b> <textarea name='text'>$article[text]</textarea></br>
<input type='submit' class='button' value='Сохранить'>
</form>
</div>
</div>
</div>";
}
}
break;First, a request is sent to the database to retrieve the article. Then, if everything is in order, the edit form is displayed. If before that the user sent the changed text, then it is sent to the server, the table is updated, and then with the help of another request, the actual information is displayed.
Adding records to the database
To create a function for adding a user (or any other element on the site), we parse the form and its handler:
case 'add_user':
if(isset($_POST['reglogin']) && isset($_POST['regpassword'])) {
$check = mysqli_query($db,"SELECT * FROM userlist WHERE login='$_POST[reglogin]'");
if(mysqli_num_rows($check) == 0) {
$insert = mysqli_query($db,"INSERT INTO userlist (login,password,admin) VALUE ('$_POST[reglogin]','$_POST[regpassword]','$_POST[regadmin]')");
if($insert) {
$message = "Пользователь успешно добавлен!";
} else {
$message = "Ошибка! ".mysqli_error($db);
}
} else {
$message = "Пользователь с таким логином уже существует!";
}
}
$echo = "<div class='table'>
<div class='table-wrapper'>
<div class='table-title'>Новый пользователь</div>
<div class='table-content'>
<a href='?act=home'><- Вернуться</a><br>
$message
<form method='post' class='user-form'>
<b>Логин:</b> <input type='text' name='reglogin' required><br>
<b>Пароль:</b> <input type='text' name='regpassword' required><br>
<b>Админ:</b> <input type='checkbox' name='regadmin'></br>
<input type='submit' class='button' value='Добавить'>
</form>
</div>
</div>
</div>";
break;First, we check if the specified login is free. If so, then the corresponding data is entered into the database. Also note that the existence of the regadmin variable is not checked because the form does not submit it if the checkbox is left empty.
Statistics
To view the statistics of visits, comments and other activity, we create a table with fields in the database:
- ID;
- date;
- views;
- comments.
They record the total number of views and comments for each day, which is displayed on the graph. To do this, write the HTML code of the table:
<div class='table'>
<div class='table-wrapper'>
<div class='table-title'>Статистика</div>
<div class='table-content'>
<img src='stats.php' class='statistics-img'> <br>
Красный: просмотры <br>
Синий: комментарии <br>
1 шаг — 1 день
</div>
</div>
</div>The source of the image is a PHP file with the code:
<?include("includes/db.php");
$width = 400;
$height = 200;
$canv = imagecreatetruecolor($width, $height);
//Цвета
$white = imagecolorallocate($canv, 255, 255, 255);
$gray = imagecolorallocate($canv, 150, 150, 150);
$black = imagecolorallocate($canv, 0, 0, 0);
$red = imagecolorallocate($canv, 255, 0, 0);
$blue = imagecolorallocate($canv, 0, 0, 255);
imagefill($canv,0,0,$white);
//Рисуется квадрат
imagerectangle($canv, 15, 5, $width-5, $height-15, $gray);
//Горизонтальные линии
for($i = 1; $i <= 5; $i++) {
imageline($canv, 15, $height-$i*35, $width-5, $height-$i*35, $gray);
}
//Вертикальные линии
for($i = 1; $i <= 15; $i++) {
imageline($canv, 15+($i*30), 5, 15+($i*30), $height-15, $gray);
}
//Получение статистики из базы данных
$stats_result = mysqli_query($db,"SELECT * FROM statistics");
if($stats_result) {
$last_y = [0,0];
$x = 15;
//Рисуется график
while($stats = mysqli_fetch_array($stats_result)) {
imageline($canv, $x, ($height-15)-$last_y[0], $x+30, ($height-15)-($stats['views']/10), $red);
imageline($canv, $x, ($height-15)-$last_y[1], $x+30, ($height-15)-($stats['comments']/10), $blue);
$last_y[0] = $stats['views']/10;
$last_y[1] = $stats['comments']/10;
$x += 30;
}
} else {echo mysqli_error($db);}
//Вывод изображения
header("Content-type: image/png");
imagepng($canv);
//Освобождение памяти
imagedestroy($canv);
?>First, an image, a frame, and divisions are created. Then there is a query to the database to get the statistics, which is drawn as a graph. The image is saved for a one-time output, and then deleted. The next time the user accesses the statistics, the information will be re-rendered.
Additional features
What we managed to talk about is only a part of what should be in the admin panel.
For example, you can additionally implement:
- pre-moderation of comments;
- deleting records from the database;
- work with files;
- advanced article editor;
- detailed statistics for each individual page, and so on.
It is equally important to learn how to carefully check incoming data and make authentication great secure again.
No comments:
Post a Comment