Inurl shoutbox php смелый. Ломаем и защищаем WordPress своими руками

Хотели бы вы иметь на своем сайте мини-чат? Думаю, многие скажут "ДА". Сегодня мы рассмотрим замечательный мини-чат Shoutbox, он работает на php, mysql и jQuery. Прежде чем начать работу, посмотрите Демо (после советую до конца прочитать урок, дабы не делать поспешных выводов)


Не правда ли классно? Теперь о том, как такую вещь реализовать.

Скрипт для работы использует БД Mysql. Давайте создадим в базе таблицу shoutbox для упрощения задачи Вам и себе привожу готовый SQL-запрос:

CREATE TABLE `shoutbox` (
`id` INT(5) NOT NULL AUTO_INCREMENT ,
`date` TIMESTAMP NOT NULL ,
`user` VARCHAR(25) NOT NULL ,
`message` VARCHAR(255) NOT NULL ,
PRIMARY KEY (`id`)
) CHARACTER SET = utf8;

Обрабатывает сообщения файл shoutbox.php . Найдите в нем следующие строки и отредактируйте:

define("HOST", "Ваш MySql-хост - обычно это localhost");
define("USER", "имя пользователя MySql");
define("PASSWORD", "пароль к вашей MySql ");
define("DB", "Имя БД");

Думаю, с этим сложностей быть не должно Еще пара настроек в этом же файле:

header ("Location: index.html");
$res = getContent($link, 50);

header - Здесь мы отправляем нерадивых юзеров, которые пытаются напрямую вызвать работу файла, shoutbox.php на страницу index.html.
getContent($link, 50) - количество сообщений на страницу. В данном примере будет выбрано 50 последних сообщений.

Теперь в нужном месте вставляем форму отправки сообщения и div-контейнер , который будет содержать последние сообщения чата:















Ваше имя
Сообщение




Последние сообщения




    Обычная форма с 3-ми input. После формы идет div#container, пусть вас не смущает наличие одинокого тега p. Все сообщения выводяться в виде

    Имя - сообщение

    (см. файл shoutbox.php ). И в конце мы подключаем jQuery и сам скрипт shoutbox.js (можете это сделать и традиционно между тегами head)

    CSS здесь отвечает только за внешний вид чата. Поэтому подробно рассматривать его в этом уроке не будем. Просто не забудьте включить стили из файла css/general.css на вашу страницу, или, что еще лучше, сделайте индивидуальный дизайн. Единственное что стоит помнить, id и class из приведенного выше кода использует и скрипт shoutbox.js, поэтому если вы будете изменять имена id и class на свои, не забудьте сделать это также в shoutbox.js

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

    P.S. Для тех кто хочет из этого скрипта получить более полноценный чат, слегка доработаем оригинальный скрипт:

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

    $(".content > p").everyTime(30000, function() {
    $.ajax({
    type: "POST", url: "shoutbox.php", data: "action=update",
    complete: function(data){
    loading.fadeOut();
    messageList.html(data.responseText);
    messageList.fadeIn("fast");
    }
    });

    EveryTime(30000) - время в милисекундах, через которое содержимое окна будет обновляться. В примере стоит 30 секунд.
    Скачать плагин с исправленным shoutbox.js . Демка работает по первоначальному варианту, но вы можете легко протестировать обновленный скрипт у себя на сайте.

    P.P.S исправляем проблему букв "И" и "ш"
    Я решил эти буквы просто заменить на их символы из "Таблица символов Unicode". Найдите строчку case "insert": (66-ая строка) в файле shoutbox.php и замените содержимое case на этот код: напишите следующее правило:

    $message = str_replace("ш", "ш", $_POST["message"]);
    $message = str_replace("И", "И", $message);
    $nick = str_replace("ш", "ш", $_POST["nick"]);
    $nick = str_replace("И", "И", $nick);
    echo insertMessage($nick, $message);

    Решение достаточно простое: мы просто перед тем как новое сообщение добавить в БД, заменяем проблемные буквы на них же, но в символьном варианте


    • FalleN

    • 9225

    • 159

    In this tutorial, we are going to build a shout box with PHP and jQuery, which allows visitors of your website to leave short comments to one another. Shouts will be stored on the server as files, no database like MySQL will be required. We are going to use two PHP libraries to make things easier - Flywheel for storing the shouts as json files and RelativeTime for creating human readable relative time stamps. We will be using Composer to install these libraries.

    On the client side, we are using plain jQuery code, and the Emoji One library, which is a free project and library for adding pretty emojis to web apps. Let"s begin!

    Running the shoutbox

    You can grab the source code from the download button above. It has plenty of comments and is easy to follow. To run it, simply upload it to your web hosting space or add it to the apache htdocs folder if you run something like XAMPP or MAMP. Then, open http://localhost in your browser (or your website, if you uploaded it to your hosting space). Here are a few things to look for:

    • The zip files already contains the dependencies, so you don"t need to install Composer . This makes it easy to get started with the code - simply upload it and use it!
    • Make sure that the data/shouts directory exists and is writable. Otherwise you will see errors in your log file and no shouts will be stored. You might need to chmod it to 777 if you keep seeing errors.
    The HTML

    Let"s start with index.html . It is a regular HTML5 document, which includes our JavaScript libraries, scripts and stylesheets. Here are the parts relevant to the shoutbox:

    index.html Shout box Write a message × nickname message

    With JavaScript we will insert the published shouts into the

      element. The form is hidden by default, and only revealed when the "Write a message" header is clicked.

      Shoutbox with PHP and jQuery

      The JavaScript Code

      And here is our script.js , which makes the above HTML work:

      assets/js/script.js $(function(){ // Storing some elements in variables for a cleaner code base var refreshButton = $("h1 img"), shoutboxForm = $(".shoutbox-form"), form = shoutboxForm.find("form"), closeForm = shoutboxForm.find("h2 span"), nameElement = form.find("#shoutbox-name"), commentElement = form.find("#shoutbox-comment"), ul = $("ul.shoutbox-content"); // Replace:) with emoji icons: emojione.ascii = true; // Load the comments. load(); // On form submit, if everything is filled in, publish the shout to the database var canPostComment = true; form.submit(function(e){ e.preventDefault(); if(!canPostComment) return; var name = nameElement.val().trim(); var comment = commentElement.val().trim(); if(name.length && comment.length && comment.length < 240) { publish(name, comment); // Prevent new shouts from being published canPostComment = false; // Allow a new comment to be posted after 5 seconds setTimeout(function(){ canPostComment = true; }, 5000); } }); // Toggle the visibility of the form. shoutboxForm.on("click", "h2", function(e){ if(form.is(":visible")) { formClose(); } else { formOpen(); } }); // Clicking on the REPLY button writes the name of the person you want to reply to into the textbox. ul.on("click", ".shoutbox-comment-reply", function(e){ var replyName = $(this).data("name"); formOpen(); commentElement.val("@"+replyName+" ").focus(); }); // Clicking the refresh button will force the load function var canReload = true; refreshButton.click(function(){ if(!canReload) return false; load(); canReload = false; // Allow additional reloads after 2 seconds setTimeout(function(){ canReload = true; }, 2000); }); // Automatically refresh the shouts every 20 seconds setInterval(load,20000); function formOpen(){ if(form.is(":visible")) return; form.slideDown(); closeForm.fadeIn(); } function formClose(){ if(!form.is(":visible")) return; form.slideUp(); closeForm.fadeOut(); } // Store the shout in the database function publish(name,comment){ $.post("publish.php", {name: name, comment: comment}, function(){ nameElement.val(""); commentElement.val(""); load(); }); } // Fetch the latest shouts function load(){ $.getJSON("./load.php", function(data) { appendComments(data); }); } // Render an array of shouts as HTML function appendComments(data) { ul.empty(); data.forEach(function(d){ ul.append("
    • "+ "" + d.name + ""+ "

      " + emojione.toImage(d.text) + "

      "+ "REPLY"+ "" + d.timeAgo + ""+ "
    • "); }); } });

      The Emoji One library has version for both JavaScript and PHP. In the appendComments method, we use the emojione.toImage() function to convert all typed-out smileys into emoji. See all functions that are supported, and check out this handy emoji code website . Now that the frontend is ready, let"s move on to the backend.

      The PHP Code

      We have two files - publish.php and load.php. The first accepts a POST request for storing shouts in the data store, and the second returns the 20 latest shouts. These files are not opened directly by visitors - they only handle AJAX requests.

      publish.php