<?xml version="1.0" encoding="UTF-8"?> <rss
version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
><channel><title>Script Tutorials &#187; PHP | Script Tutorials | Web development</title> <atom:link href="http://www.script-tutorials.com/category/php/feed/" rel="self" type="application/rss+xml" /><link>http://www.script-tutorials.com</link> <description>Tutorials for Web Developers</description> <lastBuildDate>Fri, 03 Feb 2012 06:07:51 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <item><title>Powerful Chat System &#8211; Lesson 3</title><link>http://www.script-tutorials.com/powerful-chat-system-lesson-3/</link> <comments>http://www.script-tutorials.com/powerful-chat-system-lesson-3/#comments</comments> <pubDate>Mon, 30 Jan 2012 17:01:39 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[HTML5]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[ajax chat]]></category> <category><![CDATA[chat]]></category> <category><![CDATA[chat system]]></category> <category><![CDATA[registration]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1396</guid> <description><![CDATA[Powerful Chat System &#8211; Lesson 3 Today we continue a series of articles on the creation of powerful chat system. Our third lesson will contain next elements: join form (with html5 validation). A long ago, I have already made similar validation. So you can refresh your memories if you like. Today I will publish updated [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-2/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/221/thumb.png" alt="Powerful Chat System &#8211; Lesson 2" /> Powerful Chat System &#8211; Lesson 2</a></li><li> <a
href="http://www.script-tutorials.com/powerful-chat-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/218/thumb.png" alt="Powerful Chat System" /> Powerful Chat System</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-make-ajax-style-php-chat-application/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily Make AJAX Style PHP Chat Application" /> How to Easily Make AJAX Style PHP Chat Application</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Powerful Chat System" alt="Powerful Chat System" src="http://www.script-tutorials.com/demos/226/thumb.png"></div><p><strong>Powerful Chat System &#8211; Lesson 3</strong><br
/> <br
/>Today we continue a series of articles on the creation of powerful chat system. Our third lesson will contain next elements: join form (with html5 validation). A long ago, I have already made similar <a
target="_blank" href="http://www.script-tutorials.com/data-validation-html5/">validation</a>. So you can refresh your memories if you like.<br
/> <span
id="more-1396"></span></p><p>Today I will publish updated sources of our growing project (several files was modified, plus I expanded structure of database slightly). All project is well structured: system classes is in &#8216;classes&#8217; folder, stylesheets in &#8216;css&#8217; folder, template files in &#8216;templates&#8217; folder, and &#8211; new folder &#8216;js&#8217; for javascript files.</p><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - demo 226" href="http://www.script-tutorials.com/demos/226/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - package" href="http://www.script-tutorials.com/demos/226/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>I have added new field into table of profiles where we will store its first names. So, please execute next SQL:</p><pre class="brush:sql">
ALTER TABLE `cs_profiles` ADD `first_name` varchar(255) NOT NULL default '' AFTER `name`;
</pre><h3>Step 2. HTML</h3><p>I have updated template with login form. As you can see &#8211; I have expanded this markup and added join form here:</p><h4>templates/logout_form.html</h4><pre class="brush:html">
&lt;div class=&quot;column&quot;&gt;
    &lt;h3&gt;Powerful Chat System Demonstration&lt;/h3&gt;
    &lt;p&gt;Our chat will contain next features: registration, main chat, profiles with avatars, ranking system, private messaging, custom rooms, moderation / administration and possible something else (in future).&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;column&quot;&gt;

    &lt;div class=&quot;tabs_container&quot;&gt;
        &lt;ul class=&quot;tabs&quot;&gt;
            &lt;li class=&quot;active&quot;&gt;&lt;h3&gt;Log In&lt;/h3&gt;&lt;/li&gt;
            &lt;li&gt;&lt;h3&gt;Join&lt;/h3&gt;&lt;/li&gt;
        &lt;/ul&gt;
    &lt;/div&gt;

    &lt;div class=&quot;nav_container&quot;&gt;
        &lt;form class=&quot;login_form&quot; action=&quot;index.php&quot; method=&quot;post&quot; id=&quot;1&quot;&gt;
            &lt;label&gt;Username:&lt;/label&gt;&lt;input type=&quot;text&quot; name=&quot;username&quot;&gt;
            &lt;label&gt;Password:&lt;/label&gt;&lt;input type=&quot;password&quot; name=&quot;password&quot;&gt;
            &lt;input type=&quot;submit&quot; name=&quot;Login&quot; value=&quot;Login&quot;&gt;
        &lt;/form&gt;
        &lt;form class=&quot;join_form&quot; action=&quot;index.php&quot; method=&quot;post&quot; id=&quot;2&quot; style=&quot;display: none;&quot;&gt;

            &lt;label&gt;Full name:&lt;/label&gt;
            &lt;input type=&quot;text&quot; id=&quot;username&quot; name=&quot;username&quot; placeholder=&quot;Your name&quot; maxlength=&quot;128&quot; title=&quot;Your name&quot; required&gt;

            &lt;label&gt;First name:&lt;/label&gt;
            &lt;input type=&quot;text&quot; id=&quot;firstname&quot; name=&quot;firstname&quot; placeholder=&quot;Your first name&quot; maxlength=&quot;128&quot; title=&quot;Your first name&quot;&gt;

            &lt;label&gt;Last name:&lt;/label&gt;
            &lt;input type=&quot;text&quot; id=&quot;lastname&quot; name=&quot;lastname&quot; placeholder=&quot;Your last name&quot; maxlength=&quot;128&quot; title=&quot;Your last name&quot;&gt;

            &lt;label&gt;Email:&lt;/label&gt;
            &lt;input type=&quot;text&quot; id=&quot;email&quot; name=&quot;email&quot; placeholder=&quot;Your email&quot; maxlength=&quot;128&quot; title=&quot;Format: *@gmail.com&quot; pattern=&quot;.*@gmail\.com&quot; required&gt;

            &lt;label&gt;Password:&lt;/label&gt;
            &lt;input type=&quot;text&quot; id=&quot;password&quot; name=&quot;password&quot; maxlength=&quot;128&quot; title=&quot;Password&quot; required&gt;

            &lt;label&gt;Repeat Password:&lt;/label&gt;
            &lt;input type=&quot;text&quot; id=&quot;password&quot; name=&quot;password&quot; maxlength=&quot;128&quot; title=&quot;Repeat password&quot; required oninput=&quot;checkpass(this)&quot;&gt;

            &lt;input type=&quot;submit&quot; name=&quot;Join&quot; value=&quot;Join&quot;&gt;
        &lt;/form&gt;
    &lt;/div&gt;

&lt;/div&gt;

&lt;script&gt;
$(document).ready(function(){
    $('.tabs li h3').click(function () {
      $('.tabs li').removeClass('active');
      $(this).parent().addClass('active');

      $('.nav_container form').hide();
      var index = $('.tabs li h3').index(this);
      $('.nav_container form').eq(index).show();
      return false;
    });
});

function checkpass(input) {
    if (input.value != document.getElementById('password').value) {
        input.setCustomValidity('Password must match.');
    } else {
        input.setCustomValidity('');
    }
}
&lt;/script&gt;
</pre><p>Please pay attention to HTML structure of join form, it contain several new attributes for html5 validation: placeholder, required and pattern. This is pretty interesting.</p><h3>Step 3. CSS</h3><p>This file has updated too</p><h4>css/main.css</h4><pre class="brush:html">
/* page layout */
*{
    margin:0;
    padding:0;
}
body {
    background-color:#eee;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}
header {
    background-color:#212121;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    position:relative;
    width:100%;
    z-index:100;
}
header h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}
header a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}
header .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

/* main styles */
.container {
    background-color: #222;
    color: #bbb;
    margin: 20px auto;
    overflow: hidden;
    padding: 20px;
    position: relative;
    width: 800px;
}
.container h2 {
    color: #fff;
    margin-bottom: 10px;
}
.column {
    float: left;
    width: 48%;
}
.column:first-child {
    margin-right: 4%;
}
.column &gt; * {
    color: #ddd;
    margin-bottom: 10px;
}

/* tabs section */
.tabs_container {
    margin: 0;
}
.tabs {
    overflow: hidden;
}
.tabs li {
    float: left;
    list-style: none;
}
.tabs li h3:first-child {
    margin-left: 10px
}
.tabs li h3 {
    border: 1px solid #ddd;
    border-bottom-width: 0;
    display: block;
    margin: 0 2px 0 0;
    padding: 6px 10px 4px
}
.tabs li.active h3 {
    background-color: #555;
    border: 1px solid #ddd;
    border-bottom-width: 0;

    -moz-border-radius: 4px 4px 0 0;
    -ms-border-radius: 4px 4px 0 0;
    -o-border-radius: 4px 4px 0 0;
    -webkit-border-radius: 4px 4px 0 0;
    border-radius: 4px 4px 0 0;
}
.tabs li h3:hover {
    background-color: #666;
    cursor: pointer;
}
.tabs li.active h3:hover {
    background-color: #555;
    cursor: normal;
}
.nav_container form {
    background-color: #555;
    display: block;
    padding: 15px;
}
.column h3 {
    color: #fff;
}
.login_form input,.login_form label,
.join_form input,.join_form label {
    display: block;
    margin-bottom: 10px;
}
input[type=text], input[type=password], input[type=submit] {
    -moz-border-radius: 5px;
    -ms-border-radius: 5px;
    -o-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
}
input[type=text], input[type=password] {
    font-size: 16px;
    height: 25px;
    margin-right: 10px;
    width: 200px;
}
input[type=submit]{
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
    height: 35px;
    padding: 5px;
}

/* chat block */
.chat_messages {
    border: 1px solid #888;
    box-shadow: 0 0 5px #AAA;
    color: #000;
    padding: 10px;
}
.chat_messages h2 {
    color: #fff;
}
.chat_messages .message {
    background-color: #fff;
    margin: 5px;
    padding: 5px;

    -moz-border-radius: 5px;
    -ms-border-radius: 5px;
    -o-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
}
.chat_messages .message span {
    color: #444;
    font-size: 10px;
    margin-left: 10px;
}
.chat_submit_form {
    margin: 10px 0px;
}
.chat_submit_form div {
    float: left;
    width: 49%;
}
.chat_submit_form .error, .chat_submit_form .success, .chat_submit_form .protect {
    display: none;
}
.chat_submit_form .error {
    color: #f55;
}
.chat_submit_form .success {
    color: #5f5;
}
.chat_submit_form .protect {
    color: #55f;
}
</pre><h3>Step 4. PHP</h3><p>Now, lets review php sources. Our index.php file has updated. I have added here join processing functional. Before actual joining, we have to check if someone else was joined with same email (this field should be unique of course)</p><h4>index.php</h4><pre class="brush:php">
&lt;?php

// set error reporting level
if (version_compare(phpversion(), '5.3.0', '&gt;=') == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE);

require_once('classes/Services_JSON.php');
require_once('classes/CMySQL.php'); // including service class to work with database
require_once('classes/CLogin.php'); // including service class to work with login processing

$sErrors = '';
// join processing
if (! isset($_SESSION['member_id']) &amp;&amp; $_POST['Join'] == 'Join') {
    $sUsername = $GLOBALS['MySQL']-&gt;escape($_POST['username']);
    $sFirstname = $GLOBALS['MySQL']-&gt;escape($_POST['firstname']);
    $sLastname = $GLOBALS['MySQL']-&gt;escape($_POST['lastname']);
    $sEmail = $GLOBALS['MySQL']-&gt;escape($_POST['email']);
    $sPassword = $GLOBALS['MySQL']-&gt;escape($_POST['password']);

    if ($sUsername &amp;&amp; $sEmail &amp;&amp; $sPassword) {
        // check if already exist
        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `email`='{$sEmail}'&quot;);
        if ($aProfile['id'] &gt; 0) {
            $sErrors = '&lt;h2&gt;Another profile with same email already exist&lt;/h2&gt;';
        } else {
            // generate Salt and Cached password
            $sSalt = 'testing'; // TODO - we will add generation of salt in future
            $sPass = sha1(md5($sPassword) . $sSalt);

            // add new member into database
            $sSQL = &quot;
                INSERT INTO `cs_profiles` SET
                `name` = '{$sUsername}',
                `first_name` = '{$sFirstname}',
                `last_name` = '{$sLastname}',
                `email` = '{$sEmail}',
                `password` = '{$sPass}',
                `salt` = '{$sSalt}',
                `status` = 'active',
                `role` = '1',
                `date_reg` = NOW();
            &quot;;
            $GLOBALS['MySQL']-&gt;res($sSQL);

            // autologin
            $GLOBALS['CLogin']-&gt;performLogin($sUsername, $sPassword);
        }
    }
}

// login system init and generation code
$sLoginForm = $GLOBALS['CLogin']-&gt;getLoginBox();

$sChat = '&lt;h2&gt;You do not have rights to use chat&lt;/h2&gt;';
$sInput = '';
if ($_SESSION['member_id'] &amp;&amp; $_SESSION['member_status'] == 'active' &amp;&amp; $_SESSION['member_role']) {
    require_once('classes/CChat.php'); // including service class to work with chat

    // get last messages
    $sChat = $GLOBALS['MainChat']-&gt;getMessages();
    if ($_GET['action'] == 'get_last_messages') { // regular updating of messages in chat
        $oJson = new Services_JSON();
        header('Content-type: application/json');
        echo $oJson-&gt;encode(array('messages' =&gt; $sChat));
        exit;
    }

    // get input form
    $sInput = $GLOBALS['MainChat']-&gt;getInputForm();

    if ($_POST['message']) { // POST-ing of message
        $iRes = $GLOBALS['MainChat']-&gt;acceptMessage();

        $oJson = new Services_JSON();
        header('Content-type: application/json');
        echo $oJson-&gt;encode(array('result' =&gt; $iRes));
        exit;
    }
}

// draw common page
echo strtr(file_get_contents('templates/main_page.html'), array('{form}' =&gt; $sLoginForm . $sErrors, '{chat}' =&gt; $sChat, '{input}' =&gt; $sInput));
</pre><p>As you can see &#8211; I have added chat functionality today.</p><h4>classes/CLogin.php</h4><pre class="brush:php">
&lt;?php

class CLogin {

    // constructor
    function CLogin() {
        session_start();
    }

    // get login box function
    function getLoginBox() {
        if (isset($_GET['logout'])) { // logout processing
            if (isset($_SESSION['member_name']) &amp;&amp; isset($_SESSION['member_pass']))
                $this-&gt;performLogout();
        }

        if ($_POST &amp;&amp; $_POST['Login'] == 'Login' &amp;&amp; $_POST['username'] &amp;&amp; $_POST['password']) { // login processing
            if ($this-&gt;checkLogin($_POST['username'], $_POST['password'], false)) { // successful login
                $this-&gt;performLogin($_POST['username'], $_POST['password']);
                header( &quot;Location:{$_SERVER['REQUEST_URI']}&quot; );
                exit;
            } else { // wrong login
                return file_get_contents('templates/login_form.html') . '&lt;h2&gt;Username or Password is incorrect&lt;/h2&gt;';
            }
        } else { // in case if we already logged (on refresh page):
            if (isset($_SESSION['member_name']) &amp;&amp; $_SESSION['member_name'] &amp;&amp; $_SESSION['member_pass']) {
                $aReplaces = array(
                    '{name}' =&gt; $_SESSION['member_name'],
                    '{status}' =&gt; $_SESSION['member_status'],
                    '{role}' =&gt; $_SESSION['member_role'],
                );
                return strtr(file_get_contents('templates/logout_form.html'), $aReplaces);
            }

            // otherwise - draw login form
            return file_get_contents('templates/login_form.html');
        }
    }

    // perform login
    function performLogin($sName, $sPass) {
        $this-&gt;performLogout();

        // make variables safe
        $sName = $GLOBALS['MySQL']-&gt;escape($sName);

        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `name`='{$sName}'&quot;);
        // $sPassEn = $aProfile['password'];
        $iPid = $aProfile['id'];
        $sSalt = $aProfile['salt'];
        $sStatus = $aProfile['status'];
        $sRole = $aProfile['role'];

        $sPass = sha1(md5($sPass) . $sSalt);

        $_SESSION['member_id'] = $iPid;
        $_SESSION['member_name'] = $sName;
        $_SESSION['member_pass'] = $sPass;
        $_SESSION['member_status'] = $sStatus;
        $_SESSION['member_role'] = $sRole;
    }

    // perform logout
    function performLogout() {
        unset($_SESSION['member_id']);
        unset($_SESSION['member_name']);
        unset($_SESSION['member_pass']);
        unset($_SESSION['member_status']);
        unset($_SESSION['member_role']);
    }

    // check login
    function checkLogin($sName, $sPass, $isHash = true) {
        // make variables safe
        $sName = $GLOBALS['MySQL']-&gt;escape($sName);
        $sPass = $GLOBALS['MySQL']-&gt;escape($sPass);

        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `name`='{$sName}'&quot;);
        $sPassEn = $aProfile['password'];

        if ($sName &amp;&amp; $sPass &amp;&amp; $sPassEn) {
            if (! $isHash) {
                $sSalt = $aProfile['salt'];
                $sPass = sha1(md5($sPass) . $sSalt);
            }
            return ($sPass == $sPassEn);
        }
        return false;
    }
}

$GLOBALS['CLogin'] = new CLogin();
</pre><p>Minor changes were made in this file too. The rest of the functional was not changed. We will continue enhance our chat soon.</p><hr
/><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - demo 226" href="http://www.script-tutorials.com/demos/226/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - package" href="http://www.script-tutorials.com/demos/226/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>I hope that our new series of articles of chat system creation is useful and interesting for you. If you want to share your ideas, or you noticed any weakness &#8211; don&#8217;t hesitate to contact us. Good luck and welcome back!</p><div
class="shr-publisher-1396"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-2/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/221/thumb.png" alt="Powerful Chat System &#8211; Lesson 2" /> <br
/> Powerful Chat System &#8211; Lesson 2</a></li><li> <a
href="http://www.script-tutorials.com/powerful-chat-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/218/thumb.png" alt="Powerful Chat System" /> <br
/> Powerful Chat System</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-make-ajax-style-php-chat-application/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily Make AJAX Style PHP Chat Application" /> <br
/> How to Easily Make AJAX Style PHP Chat Application</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/powerful-chat-system-lesson-3/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Powerful Chat System &#8211; Lesson 2</title><link>http://www.script-tutorials.com/powerful-chat-system-lesson-2/</link> <comments>http://www.script-tutorials.com/powerful-chat-system-lesson-2/#comments</comments> <pubDate>Wed, 18 Jan 2012 17:17:45 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[ajax chat]]></category> <category><![CDATA[chat]]></category> <category><![CDATA[chat system]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1373</guid> <description><![CDATA[Powerful Chat System &#8211; Lesson 2 Today we continue a series of articles on the creation of powerful chat system. Our second lesson will contain next elements: smart chat (ajax, with spam filtering &#8211; protection from the frequent messages). I have decided to make registration for next lesson. Hope that it is ok for you. [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/226/thumb.png" alt="Powerful Chat System &#8211; Lesson 3" /> Powerful Chat System &#8211; Lesson 3</a></li><li> <a
href="http://www.script-tutorials.com/powerful-chat-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/218/thumb.png" alt="Powerful Chat System" /> Powerful Chat System</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-make-ajax-style-php-chat-application/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily Make AJAX Style PHP Chat Application" /> How to Easily Make AJAX Style PHP Chat Application</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Powerful Chat System" alt="Powerful Chat System" src="http://www.script-tutorials.com/demos/221/thumb.png"></div><p><strong>Powerful Chat System &#8211; Lesson 2</strong><br
/> <br
/>Today we continue a series of articles on the creation of powerful chat system. Our second lesson will contain next elements: smart chat (ajax, with spam filtering &#8211; protection from the frequent messages). I have decided to make registration for next lesson. Hope that it is ok for you.<br
/> <span
id="more-1373"></span></p><p>Today I have included next elements: chat processor, plus &#8211; slight corrections in our previous sources. All project is well structured: system classes is in &#8216;classes&#8217; folder, stylesheets in &#8216;css&#8217; folder, template files in &#8216;templates&#8217; folder, and &#8211; new folder &#8216;js&#8217; for javascript files.</p><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - demo 221" href="http://www.script-tutorials.com/demos/221/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - package" href="http://www.script-tutorials.com/demos/221/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>This table has got minor changes. I have changed type of field &#8216;when&#8217;.</p><pre class="brush:sql">
CREATE TABLE `cs_messages` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `sender` int(11) unsigned NOT NULL,
  `recipient` int(11) unsigned NOT NULL default '0',
  `message` VARCHAR(255) NOT NULL,
  `when` int(11) NOT NULL default '0',
  `room` int(5) unsigned NOT NULL default '0',
  `type` tinyint(1) unsigned NOT NULL default '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</pre><h3>Step 2. HTML</h3><p>This is main (index) page html markup:</p><h4>templates/main_page.html</h4><pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
&lt;head&gt;
    &lt;title&gt;Powerful Chat System - Lesson 2&lt;/title&gt;
    &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
    &lt;script src=&quot;http://code.jquery.com/jquery-latest.min.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;header&gt;
        &lt;h2&gt;Powerful Chat System - Lesson 2&lt;/h2&gt;
        &lt;a href=&quot;http://www.script-tutorials.com/powerful-chat-system-lesson-2/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
    &lt;/header&gt;
    &lt;div class=&quot;container&quot;&gt;
        {form}
    &lt;/div&gt;
    &lt;div class=&quot;container&quot;&gt;
        &lt;h2&gt;Main Chat Block&lt;/h2&gt;
        &lt;div class=&quot;chat_messages&quot;&gt;
            {chat}
        &lt;/div&gt;
        {input}
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>As you can see &#8211; I have changed our second container (which contains our ajax chat).</p><h4>templates/login_form.html and templates/logout_form.html</h4><p>These files haven&#8217;t changed since last time. Next one new template &#8211; chat form:</p><h4>templates/chat.html</h4><pre class="brush:html">
&lt;form class=&quot;chat_submit_form&quot;&gt;
    &lt;div&gt;&lt;input type=&quot;text&quot; name=&quot;message&quot; /&gt;&lt;input type=&quot;submit&quot; value=&quot;Submit&quot; name=&quot;Submit&quot; /&gt;&lt;/div&gt;
    &lt;div&gt;
        &lt;h3 class=&quot;error&quot;&gt;Some error occurs during sending message&lt;/h3&gt;
        &lt;h3 class=&quot;success&quot;&gt;Message successfully sent&lt;/h3&gt;
        &lt;h3 class=&quot;protect&quot;&gt;Please wait 5 secs before adding next message&lt;/h3&gt;
    &lt;/div&gt;
&lt;/form&gt;
&lt;script src=&quot;js/chat.js&quot;&gt;&lt;/script&gt;
</pre><h3>Step 3. CSS</h3><p>This file contains updated styles of our chat</p><h4>css/main.css</h4><pre class="brush:html">
/* page layout */
*{
    margin:0;
    padding:0;
}
body {
    background-color:#eee;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}
header {
    background-color:#212121;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    position:relative;
    width:100%;
    z-index:100;
}
header h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}
header a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}
header .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

/* main styles */
.container {
    background-color: #222;
    color: #bbb;
    margin: 20px auto;
    overflow: hidden;
    padding: 20px;
    position: relative;
    width: 800px;
}
.container h2 {
    color: #fff;
    margin-bottom: 10px;
}
.column {
    float: left;
    width: 48%;
}
.column:first-child {
    margin-right: 4%;
}
.column &gt; * {
    color: #ddd;
    margin-bottom: 10px;
}
.column h3 {
    color: #fff;
}
.login_form input,.login_form label {
    display: block;
    margin-bottom: 10px;
}
input[type=text], input[type=password], input[type=submit] {
    -moz-border-radius: 5px;
    -ms-border-radius: 5px;
    -o-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
}
input[type=text], input[type=password] {
    font-size: 16px;
    height: 30px;
    margin-right: 10px;
    width: 200px;
}
input[type=submit]{
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
    height: 35px;
    padding: 5px;
}

/* chat block */
.chat_messages {
    border: 1px solid #888;
    box-shadow: 0 0 5px #AAA;
    color: #000;
    padding: 10px;
}
.chat_messages h2 {
    color: #fff;
}
.chat_messages .message {
    background-color: #fff;
    margin: 5px;
    padding: 5px;

    -moz-border-radius: 5px;
    -ms-border-radius: 5px;
    -o-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
}
.chat_messages .message span {
    color: #444;
    font-size: 10px;
    margin-left: 10px;
}
.chat_submit_form {
    margin: 10px 0px;
}
.chat_submit_form div {
    float: left;
    width: 49%;
}
.chat_submit_form .error, .chat_submit_form .success, .chat_submit_form .protect {
    display: none;
}
.chat_submit_form .error {
    color: #f55;
}
.chat_submit_form .success {
    color: #5f5;
}
.chat_submit_form .protect {
    color: #55f;
}
</pre><h3>Step 4. JS</h3><p>I have created first JS for our chat. At beginning &#8211; it contain one function for regular obtaining messages, and handler of form submitting.</p><h4>js/chat.js</h4><pre class="brush:js">
$(function() {
    getMessages = function() {
        $.getJSON('index.php?action=get_last_messages', function(data){
            if (data.messages) {
                $('.chat_messages').html(data.messages);
            }

            // get recent chat messages in loop
            setTimeout(function(){
               getMessages();
            }, 5000);
        });
    }
    getMessages();

    $('.chat_submit_form').submit(function() {
        $.post('index.php', { message: $('.chat_submit_form input[name=message]').val() },
            function(data){
                if (data.result == 1) {
                    $('.chat_submit_form .success').fadeIn('slow', function () {
                        $(this).delay(1000).fadeOut('slow');
                    });
                } else if (data.result == 2) {
                    $('.chat_submit_form .protect').fadeIn('slow', function () {
                        $(this).delay(1000).fadeOut('slow');
                    });
                } else {
                    $('.chat_submit_form .error').fadeIn('slow', function () {
                        $(this).delay(1000).fadeOut('slow');
                    });
                }
            }
        );
        return false;
    });
});
</pre><h3>Step 5. PHP</h3><p>Now, lets review php sources:</p><h4>index.php</h4><pre class="brush:php">
&lt;?php

// set error reporting level
if (version_compare(phpversion(), '5.3.0', '&gt;=') == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE);

require_once('classes/Services_JSON.php');
require_once('classes/CMySQL.php'); // including service class to work with database
require_once('classes/CLogin.php'); // including service class to work with login processing

// login system init and generation code
$sLoginForm = $GLOBALS['CLogin']-&gt;getLoginBox();

$sChat = '&lt;h2&gt;You do not have rights to use chat&lt;/h2&gt;';
$sInput = '';
if ($_SESSION['member_id'] &amp;&amp; $_SESSION['member_status'] == 'active' &amp;&amp; $_SESSION['member_role']) {
    require_once('classes/CChat.php'); // including service class to work with chat

    // get last messages
    $sChat = $GLOBALS['MainChat']-&gt;getMessages();
    if ($_GET['action'] == 'get_last_messages') { // regular updating of messages in chat
        $oJson = new Services_JSON();
        header('Content-type: application/json');
        echo $oJson-&gt;encode(array('messages' =&gt; $sChat));
        exit;
    }

    // get input form
    $sInput = $GLOBALS['MainChat']-&gt;getInputForm();

    if ($_POST['message']) { // POST-ing of message
        $iRes = $GLOBALS['MainChat']-&gt;acceptMessage();

        $oJson = new Services_JSON();
        header('Content-type: application/json');
        echo $oJson-&gt;encode(array('result' =&gt; $iRes));
        exit;
    }
}

// draw common page
echo strtr(file_get_contents('templates/main_page.html'), array('{form}' =&gt; $sLoginForm, '{chat}' =&gt; $sChat, '{input}' =&gt; $sInput));
</pre><p>As you can see &#8211; I have added chat functionality today.</p><h4>classes/CLogin.php</h4><pre class="brush:php">
&lt;?php

class CLogin {

    // constructor
    function CLogin() {
        session_start();
    }

    // get login box function
    function getLoginBox() {
        if (isset($_GET['logout'])) { // logout processing
            if (isset($_SESSION['member_name']) &amp;&amp; isset($_SESSION['member_pass']))
                $this-&gt;performLogout();
        }

        if ($_POST &amp;&amp; $_POST['username'] &amp;&amp; $_POST['password']) { // login processing
            if ($this-&gt;checkLogin($_POST['username'], $_POST['password'], false)) { // successful login
                $this-&gt;performLogin($_POST['username'], $_POST['password']);
                header( &quot;Location:{$_SERVER['REQUEST_URI']}&quot; );
                exit;
            } else { // wrong login
                return file_get_contents('templates/login_form.html') . '&lt;h2&gt;Username or Password is incorrect&lt;/h2&gt;';
            }
        } else { // in case if we already logged (on refresh page):
            if (isset($_SESSION['member_name']) &amp;&amp; $_SESSION['member_name'] &amp;&amp; $_SESSION['member_pass']) {
                $aReplaces = array(
                    '{name}' =&gt; $_SESSION['member_name'],
                    '{status}' =&gt; $_SESSION['member_status'],
                    '{role}' =&gt; $_SESSION['member_role'],
                );
                return strtr(file_get_contents('templates/logout_form.html'), $aReplaces);
            }

            // otherwise - draw login form
            return file_get_contents('templates/login_form.html');
        }
    }

    // perform login
    function performLogin($sName, $sPass) {
        $this-&gt;performLogout();

        // make variables safe
        $sName = $GLOBALS['MySQL']-&gt;escape($sName);

        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `name`='{$sName}'&quot;);
        // $sPassEn = $aProfile['password'];
        $iPid = $aProfile['id'];
        $sSalt = $aProfile['salt'];
        $sStatus = $aProfile['status'];
        $sRole = $aProfile['role'];

        $sPass = sha1(md5($sPass) . $sSalt);

        $_SESSION['member_id'] = $iPid;
        $_SESSION['member_name'] = $sName;
        $_SESSION['member_pass'] = $sPass;
        $_SESSION['member_status'] = $sStatus;
        $_SESSION['member_role'] = $sRole;
    }

    // perform logout
    function performLogout() {
        unset($_SESSION['member_id']);
        unset($_SESSION['member_name']);
        unset($_SESSION['member_pass']);
        unset($_SESSION['member_status']);
        unset($_SESSION['member_role']);
    }

    // check login
    function checkLogin($sName, $sPass, $isHash = true) {
        // make variables safe
        $sName = $GLOBALS['MySQL']-&gt;escape($sName);
        $sPass = $GLOBALS['MySQL']-&gt;escape($sPass);

        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `name`='{$sName}'&quot;);
        $sPassEn = $aProfile['password'];

        if ($sName &amp;&amp; $sPass &amp;&amp; $sPassEn) {
            if (! $isHash) {
                $sSalt = $aProfile['salt'];
                $sPass = sha1(md5($sPass) . $sSalt);
            }
            return ($sPass == $sPassEn);
        }
        return false;
    }
}

$GLOBALS['CLogin'] = new CLogin();
</pre><p>This class is updated too. I have decided to add &#8216;member_id&#8217; in sessions too. It will useful afterward.</p><h4>classes/CMySQL.php</h4><p>This is database service class. Available in package. Pay attention &#8211; database settings of our project is in this file.</p><h4>classes/Services_JSON.php</h4><p>This is JSON service class. Available in package.</p><h4>classes/CChat.php</h4><pre class="brush:php">
&lt;?php

class CChat {

    // constructor
    function CChat() {}

    // add to DB message
    function acceptMessage() {
        $sName = $GLOBALS['MySQL']-&gt;escape($_SESSION['member_name']);
        $iPid = (int)$_SESSION['member_id'];
        $sMessage = $GLOBALS['MySQL']-&gt;escape($_POST['message']);

        if ($iPid &amp;&amp; $sName != '' &amp;&amp; $sMessage != '') {
            $sSQL = &quot;
                SELECT `id`
                FROM `cs_messages`
                WHERE `sender` = '{$iPid}' AND UNIX_TIMESTAMP( ) - `when` &lt; 5
                LIMIT 1
            &quot;;
            $iLastId = $GLOBALS['MySQL']-&gt;getOne($sSQL);
            if ($iLastId) return 2; // as protection from very often messages

            $bRes = $GLOBALS['MySQL']-&gt;res(&quot;INSERT INTO `cs_messages` SET `sender` = '{$iPid}', `message` = '{$sMessage}', `when` = UNIX_TIMESTAMP()&quot;);
            return ($bRes) ? 1 : 3;
        }
    }

    // return input text form
    function getInputForm() {
        return file_get_contents('templates/chat.html');
    }

    // get last 10 messages
    function getMessages() {
        $sSQL = &quot;
            SELECT `a` . * , `cs_profiles`.`name` , UNIX_TIMESTAMP( ) - `a`.`when` AS 'diff'
            FROM `cs_messages` AS `a`
            INNER JOIN `cs_profiles` ON `cs_profiles`.`id` = `a`.`sender`
            ORDER BY `a`.`id` DESC
            LIMIT 10
        &quot;;
        $aMessages = $GLOBALS['MySQL']-&gt;getAll($sSQL);
        asort($aMessages);

        // create list of messages
        $sMessages = '';
        foreach ($aMessages as $i =&gt; $aMessage) {
            $sExStyles = $sExJS = '';
            $iDiff = (int)$aMessage['diff'];
            if ($iDiff &lt; 7) { // less than 7 seconds
                $sExStyles = 'style=&quot;display:none;&quot;';
                $sExJS = &quot;&lt;script&gt; $('#message_{$aMessage['id']}').fadeIn('slow'); &lt;/script&gt;&quot;;
            }

            $sWhen = date(&quot;H:i:s&quot;, $aMessage['when']);
            $sMessages .= '&lt;div class=&quot;message&quot; id=&quot;message_'.$aMessage['id'].'&quot; '.$sExStyles.'&gt;&lt;b&gt;' . $aMessage['name'] . ':&lt;/b&gt; ' . $aMessage['message'] . '&lt;span&gt;(' . $sWhen . ')&lt;/span&gt;&lt;/div&gt;' . $sExJS;
        }
        return $sMessages;
    }
}

$GLOBALS['MainChat'] = new CChat();
</pre><p>This is our new class for chat processor. For now &#8211; it contain only 3 functions: acceptMessage, getInputForm and getMessages.</p><hr
/><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - demo 221" href="http://www.script-tutorials.com/demos/221/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - package" href="http://www.script-tutorials.com/demos/221/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>I will hope that our new series of articles of chat system creation will be useful and interesting for you. If you want to share your ideas, or you noticed any weakness &#8211; don&#8217;t hesitate to contact us. Good luck and welcome back!</p><div
class="shr-publisher-1373"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/226/thumb.png" alt="Powerful Chat System &#8211; Lesson 3" /> <br
/> Powerful Chat System &#8211; Lesson 3</a></li><li> <a
href="http://www.script-tutorials.com/powerful-chat-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/218/thumb.png" alt="Powerful Chat System" /> <br
/> Powerful Chat System</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-make-ajax-style-php-chat-application/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily Make AJAX Style PHP Chat Application" /> <br
/> How to Easily Make AJAX Style PHP Chat Application</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/powerful-chat-system-lesson-2/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Powerful Chat System</title><link>http://www.script-tutorials.com/powerful-chat-system/</link> <comments>http://www.script-tutorials.com/powerful-chat-system/#comments</comments> <pubDate>Fri, 13 Jan 2012 14:14:57 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[ajax chat]]></category> <category><![CDATA[chat]]></category> <category><![CDATA[chat system]]></category> <category><![CDATA[profiles]]></category> <category><![CDATA[registration]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1360</guid> <description><![CDATA[Powerful Chat System Today we begin a series of articles on the creation of powerful chat system. The system will contain next elements: registration, login processing, main chat, profiles with avatars, ranking system (of profiles), private messaging, custom rooms, moderation / administration and possible something else (in future). This will be ajax chat PHP) with [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/226/thumb.png" alt="Powerful Chat System &#8211; Lesson 3" /> Powerful Chat System &#8211; Lesson 3</a></li><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-2/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/221/thumb.png" alt="Powerful Chat System &#8211; Lesson 2" /> Powerful Chat System &#8211; Lesson 2</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-make-a-php-chat-application/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily Make a PHP Chat Application" /> How to Easily Make a PHP Chat Application</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Powerful Chat System" alt="Powerful Chat System" src="http://www.script-tutorials.com/demos/218/thumb.png"></div><p><strong>Powerful Chat System</strong><br
/> <br
/>Today we begin a series of articles on the creation of powerful chat system. The system will contain next elements: registration, login processing, main chat, profiles with avatars, ranking system (of profiles), private messaging, custom rooms, moderation / administration and possible something else (in future). This will be ajax chat PHP) with storing messages in database (MySQL). Plus we will implement CSS3/HTML5 features in our development process.<br
/> <span
id="more-1360"></span></p><p>Today I have included next elements: initial code (PHP + SQL) with login processor. All project will be well structured: system classes is in &#8216;classes&#8217; folder, stylesheets in &#8216;css&#8217; folder, template files in &#8216;templates&#8217; folder.</p><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - demo 218" href="http://www.script-tutorials.com/demos/218/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - package" href="http://www.script-tutorials.com/demos/218/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>Here is SQL structure of tables for profiles and messages</p><pre class="brush:sql">
CREATE TABLE `cs_profiles` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(255) NOT NULL default '',
  `last_name` varchar(255) NOT NULL default '',
  `email` varchar(255) NOT NULL default '',
  `password` varchar(40) NOT NULL default '',
  `salt` varchar(10) NOT NULL default '',
  `status` enum('active','passive') NOT NULL default 'active',
  `role` tinyint(4) unsigned NOT NULL default '1',
  `about` varchar(255) NOT NULL,
  `date_reg` datetime NOT NULL default '0000-00-00 00:00:00',
  `rate` float NOT NULL,
  `rate_count` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

INSERT INTO `cs_profiles` (`name`, `last_name`, `email`, `password`, `salt`, `status`, `role`, `about`, `date_reg`, `rate`, `rate_count`) VALUES
('test user', 'test user last name', 'user@user.com', 'b88c654d6c68fc37f4dda1d29935235eea9a845b', 'testing', 'active', 1, 'Few words about test user', '2012-01-14 00:00:00', 0, 0),
('moderator', 'moderator last name', 'moderator@moderator.com', 'b88c654d6c68fc37f4dda1d29935235eea9a845b', 'testing', 'active', 4, 'Few words about moderator', '2012-01-14 00:00:00', 0, 0),
('admin', 'admin last name', 'admin@admin.com', 'b88c654d6c68fc37f4dda1d29935235eea9a845b', 'testing', 'active', 5, 'Few words about admin', '2012-01-14 00:00:00', 0, 0);

CREATE TABLE `cs_messages` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `sender` int(11) unsigned NOT NULL,
  `recipient` int(11) unsigned NOT NULL default '0',
  `message` VARCHAR(255) NOT NULL,
  `when` TIMESTAMP NOT NULL default CURRENT_TIMESTAMP,
  `room` int(5) unsigned NOT NULL default '0',
  `type` tinyint(1) unsigned NOT NULL default '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</pre><p>I have added 3 profiles in the system. Each of them have different role. I plan to make ordinary members (1), moderators (4), administrators (5). You can use another roles (as example 2 and 3) for any other purposes (paid members?). And, quite forgot &#8211; password for all of them is <b>&#8216;password&#8217;</b>. So you can login as &#8216;test user&#8217; -> &#8216;password&#8217;, &#8216;moderator&#8217; -> &#8216;password&#8217; and &#8216;admin&#8217; -> &#8216;password&#8217;. Registration process will in next article.</p><h3>Step 2. HTML</h3><p>This is main (index) page html markup:</p><h4>templates/main_page.html</h4><pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
&lt;head&gt;
    &lt;title&gt;Powerful Chat System&lt;/title&gt;
    &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;header&gt;
        &lt;h2&gt;Powerful Chat System&lt;/h2&gt;
        &lt;a href=&quot;http://www.script-tutorials.com/powerful-chat-system/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
    &lt;/header&gt;
    &lt;div class=&quot;container&quot;&gt;
        {form}
    &lt;/div&gt;
    &lt;div class=&quot;container&quot;&gt;
        {chat}
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>It is easy layout, isn&#8217;t it?. Now, next template file for login form:</p><h4>templates/login_form.html</h4><pre class="brush:html">
&lt;div class=&quot;column&quot;&gt;
    &lt;h3&gt;Powerful Chat System Demonstration&lt;/h3&gt;
    &lt;p&gt;Our chat will contain next features: registration, main chat, profiles with avatars, ranking system, private messaging, custom rooms, moderation / administration and possible something else (in future).&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;column&quot;&gt;
    &lt;form class=&quot;login_form&quot; action=&quot;index.php&quot; method=&quot;post&quot;&gt;
        &lt;h3&gt;Log In&lt;/h3&gt;
        &lt;label&gt;Username:&lt;/label&gt;&lt;input type=&quot;text&quot; name=&quot;username&quot;&gt;
        &lt;label&gt;Password:&lt;/label&gt;&lt;input type=&quot;password&quot; name=&quot;password&quot;&gt;
        &lt;input type=&quot;submit&quot; name=&quot;LogIn&quot; value=&quot;Login&quot;&gt;
    &lt;/form&gt;
&lt;/div&gt;
</pre><p>Next one template &#8211; logout form:</p><h4>logout_form.html</h4><pre class="brush:html">
&lt;div class=&quot;column&quot;&gt;
    &lt;h3&gt;Hello {name}&lt;/h3&gt;
    &lt;h3&gt;Your status:&lt;/h3&gt;
    &lt;div&gt;{status}&lt;/div&gt;
    &lt;h3&gt;Your role:&lt;/h3&gt;
    &lt;div&gt;{role}&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;column&quot;&gt;
    &lt;a href=&quot;index.php?logout&quot;&gt;Log Out&lt;/a&gt;
&lt;/div&gt;
</pre><h3>Step 3. CSS</h3><p>This file contains styles of our page layout</p><h4>css/main.css</h4><pre class="brush:html">
/* page layout */
*{
    margin:0;
    padding:0;
}
body {
    background-color:#eee;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}
header {
    background-color:#212121;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    position:relative;
    width:100%;
    z-index:100;
}
header h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}
header a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}
header .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

/* main styles */
.container {
    background-color:#222;
    color: #bbb;
    margin: 20px auto;
    overflow: hidden;
    padding:20px;
    position: relative;
    width: 800px;
}
.column {
    float:left;
    width:48%;
}
.column:first-child {
    margin-right:4%;
}
.column &gt; * {
    color:#ddd;
    margin-bottom:10px;
}
.column h3 {
    color:#fff;
}
.login_form input,.login_form label {
    display:block;
    margin-bottom:5px;
}
input[type=text],
input[type=password] {
    width:200px;
}
input[type=submit]{
    height:30px;
    margin-top:10px;
    width:72px;
}
</pre><h3>Step 4. PHP</h3><p>Now, lets review php sources:</p><h4>index.php</h4><pre class="brush:php">
&lt;?php

// set error reporting level
if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;) == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE);

require_once('classes/CMySQL.php'); // including service class to work with database
require_once('classes/CLogin.php'); // including service class to work with login processing

// login system init and generation code
$sLoginForm = $GLOBALS['CLogin']-&gt;getLoginBox();

$sChat = ($_SESSION['member_name'] &amp;&amp; $_SESSION['member_status'] == 'active') ? '&lt;h2&gt;TODO chat&lt;/h2&gt;' : '&lt;h2&gt;You have to login before use chat&lt;/h2&gt;';

echo strtr(file_get_contents('templates/main_page.html'), array('{form}' =&gt; $sLoginForm, '{chat}' =&gt; $sChat));
</pre><p>As we need only login processing for today &#8211; our index file is pretty small. New functional will appear in further articles. Here is sources of our login processor:</p><h4>classes/CLogin.php</h4><pre class="brush:php">
&lt;?php

class CLogin {

    // constructor
    function CLogin() {
        session_start();
    }

    // get login box function
    function getLoginBox() {
        if (isset($_GET['logout'])) { // logout processing
            if (isset($_SESSION['member_name']) &amp;&amp; isset($_SESSION['member_pass']))
                $this-&gt;performLogout();
        }

        if ($_POST &amp;&amp; $_POST['username'] &amp;&amp; $_POST['password']) { // login processing
            if ($this-&gt;checkLogin($_POST['username'], $_POST['password'], false)) { // successful login
                $this-&gt;performLogin($_POST['username'], $_POST['password']);
                header( &quot;Location:{$_SERVER['REQUEST_URI']}&quot; );
                exit;
            } else { // wrong login
                return file_get_contents('templates/login_form.html') . '&lt;h2&gt;Username or Password is incorrect&lt;/h2&gt;';
            }
        } else { // in case if we already logged (on refresh page):
            if (isset($_SESSION['member_name']) &amp;&amp; $_SESSION['member_name'] &amp;&amp; $_SESSION['member_pass']) {
                $aReplaces = array(
                    '{name}' =&gt; $_SESSION['member_name'],
                    '{status}' =&gt; $_SESSION['member_status'],
                    '{role}' =&gt; $_SESSION['member_role'],
                );
                return strtr(file_get_contents('templates/logout_form.html'), $aReplaces);
            }

            // otherwise - draw login form
            return file_get_contents('templates/login_form.html');
        }
    }

    // perform login
    function performLogin($sName, $sPass) {
        $this-&gt;performLogout();

        // make variables safe
        $sName = $GLOBALS['MySQL']-&gt;escape($sName);

        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `name`='{$sName}'&quot;);
        // $sPassEn = $aProfile['password'];
        $sSalt = $aProfile['salt'];
        $sStatus = $aProfile['status'];
        $sRole = $aProfile['role'];

        $sPass = sha1(md5($sPass) . $sSalt);

        $_SESSION['member_name'] = $sName;
        $_SESSION['member_pass'] = $sPass;
        $_SESSION['member_status'] = $sStatus;
        $_SESSION['member_role'] = $sRole;
    }

    // perform logout
    function performLogout() {
        unset($_SESSION['member_name']);
        unset($_SESSION['member_pass']);
        unset($_SESSION['member_status']);
        unset($_SESSION['member_role']);
    }

    // check login
    function checkLogin($sName, $sPass, $isHash = true) {
        // make variables safe
        $sName = $GLOBALS['MySQL']-&gt;escape($sName);
        $sPass = $GLOBALS['MySQL']-&gt;escape($sPass);

        $aProfile = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `cs_profiles` WHERE `name`='{$sName}'&quot;);
        $sPassEn = $aProfile['password'];

        if ($sName &amp;&amp; $sPass &amp;&amp; $sPassEn) {
            if (! $isHash) {
                $sSalt = $aProfile['salt'];
                $sPass = sha1(md5($sPass) . $sSalt);
            }
            return ($sPass == $sPassEn);
        }
        return false;
    }
}

$GLOBALS['CLogin'] = new CLogin();
</pre><p>I hope you still remember our <a
href="http://www.script-tutorials.com/creating-advance-level-login-system-with-logic-captcha/" target="_blank">previous article of advanced login system</a>. We will have similar system with using sha1 + md5 encryption. All profiles will kept in database.</p><h4>classes/CMySQL.php</h4><p>This is database service class. Available in package. Pay attention &#8211; database settings of our project is in this file.</p><hr
/><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - demo 218" href="http://www.script-tutorials.com/demos/218/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Powerful Chat System - package" href="http://www.script-tutorials.com/demos/218/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>I will hope that our new series of articles of chat system creation will be useful and interesting for you. If you want to share your ideas, or you noticed any weakness &#8211; don&#8217;t hesitate to contact us. Good luck and welcome back!</p><div
class="shr-publisher-1360"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/226/thumb.png" alt="Powerful Chat System &#8211; Lesson 3" /> <br
/> Powerful Chat System &#8211; Lesson 3</a></li><li> <a
href="http://www.script-tutorials.com/powerful-chat-system-lesson-2/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/221/thumb.png" alt="Powerful Chat System &#8211; Lesson 2" /> <br
/> Powerful Chat System &#8211; Lesson 2</a></li><li> <a
href="http://www.script-tutorials.com/how-to-easily-make-a-php-chat-application/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to Easily Make a PHP Chat Application" /> <br
/> How to Easily Make a PHP Chat Application</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/powerful-chat-system/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Access Control with Bit Masks</title><link>http://www.script-tutorials.com/access-control-with-bit-masks/</link> <comments>http://www.script-tutorials.com/access-control-with-bit-masks/#comments</comments> <pubDate>Fri, 23 Dec 2011 16:59:30 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[Access Control]]></category> <category><![CDATA[Bit Masks]]></category> <category><![CDATA[Bitwise Operators]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1321</guid> <description><![CDATA[Access Control with Bit Masks Today I want to tell you about the organization of access rights to users (on your site) using bit masks. Perhaps you have already known it, probably not, but anyway I want to give you this information. Why bit masks &#8211; easy, because this is and fast and easy way [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/advance-php-login-system-tutorial/" rel="bookmark"> <img
src="http://www.script-tutorials.com/wp-content/uploads/2010/03/php-login-system-icon.png" alt="How to Easily Make an Advance Level Login system" /> How to Easily Make an Advance Level Login system</a></li><li> <a
href="http://www.script-tutorials.com/creating-advance-level-login-system-with-logic-captcha/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/121/thumb.png" alt="Creating Advance Level Login system with Logic captcha" /> Creating Advance Level Login system with Logic captcha</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Access Control with Bit Masks" alt="Access Control with Bit Masks" src="http://www.script-tutorials.com/demos/207/thumb.png"></div><p><strong>Access Control with Bit Masks</strong><br
/> <br
/>Today I want to tell you about the organization of access rights to users (on your site) using bit masks. Perhaps you have already known it, probably not, but anyway I want to give you this information. Why bit masks &#8211; easy, because this is and fast and easy way to recognize user&#8217;s possibilities. In our system, I have identified six possible actions (it will keep 6 bits, each bit &#8211; one of the possible actions). There are next actions: Read, Create, Edit Own, Delete Own, Edit Any and Delete Any (moderator&#8217;s / admin&#8217;s actions). It can be applied to everything &#8211; blogs, news articles, photos and more. Ok, lets start.<br
/> <span
id="more-1321"></span></p><p>Here are a little of theory about Bitwise Operators:</p><table><thead
valign="middle"><tr
valign="middle"><th>Example</th><th>Name</th><th>Result</th></tr></thead><tbody
valign="middle"><tr
valign="middle"><td
align="left"><code>$a &amp; $b</code></td><td
align="left">And</td><td
align="left">Bits that are set in both <var><var>$a</var></var> and <var><var>$b</var></var> are set.</td></tr><tr
valign="middle"><td
align="left"><code>$a | $b</code></td><td
align="left">Or (inclusive or)</td><td
align="left">Bits that are set in either <var><var>$a</var></var> or <var><var>$b</var></var> are set.</td></tr><tr
valign="middle"><td
align="left"><code>$a ^ $b</code></td><td
align="left">Xor (exclusive or)</td><td
align="left"> Bits that are set in <var><var>$a</var></var> or <var><var>$b</var></var> but not both are set.</td></tr><tr
valign="middle"><td
align="left"><code>~ $a</code></td><td
align="left">Not</td><td
align="left"> Bits that are set in <var><var>$a</var></var> are not set, and vice versa.</td></tr><tr
valign="middle"><td
align="left"><code>$a &lt;&lt; $b</code></td><td
align="left">Shift left</td><td
align="left"> Shift the bits of <var><var>$a</var></var> <var><var>$b</var></var> steps to the left (each step means &#8220;multiply by two&#8221;)</td></tr><tr
valign="middle"><td
align="left"><code>$a &gt;&gt; $b</code></td><td
align="left">Shift right</td><td
align="left"> Shift the bits of <var><var>$a</var></var> <var><var>$b</var></var> steps to the right (each step means &#8220;divide by two&#8221;)</td></tr></tbody></table><h5 style="text-align: center;"><strong><a
title="Access Control with Bit Masks - demo 207" href="http://www.script-tutorials.com/demos/207/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Access Control with Bit Masks - package" href="http://www.script-tutorials.com/demos/207/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. HTML</h3><p>Our demo uses 3 html template files:</p><h4>main_page.html</h4><pre class="brush:html">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
&lt;head&gt;
    &lt;title&gt;Access Control with Bit Masks&lt;/title&gt;
    &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;header&gt;
        &lt;h2&gt;Access Control with Bit Masks&lt;/h2&gt;
        &lt;a href=&quot;http://www.script-tutorials.com/access-control-with-bit-masks/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
    &lt;/header&gt;
    &lt;div class=&quot;container&quot;&gt;
        {form}
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>This is very easy layout, isn&#8217;t it?. Next one template file:</p><h4>login_form.html</h4><pre class="brush:html">
&lt;div class=&quot;column&quot;&gt;
    &lt;h3&gt;Access control demonstration&lt;/h3&gt;
    &lt;p&gt;You can use next usernames &quot;User&quot;, &quot;Writer&quot;, &quot;Moderator&quot; and &quot;Admin&quot; and password &quot;password&quot; to login in system. Each of them have own set of possibilities.&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;column&quot;&gt;
    &lt;form class=&quot;login_form&quot; action=&quot;index.php&quot; method=&quot;post&quot;&gt;
        &lt;h3&gt;Log In&lt;/h3&gt;
        &lt;label&gt;Username:&lt;/label&gt;&lt;input type=&quot;text&quot; name=&quot;username&quot;&gt;
        &lt;label&gt;Password:&lt;/label&gt;&lt;input type=&quot;password&quot; name=&quot;password&quot;&gt;
        &lt;input type=&quot;submit&quot; name=&quot;LogIn&quot; value=&quot;Login&quot;&gt;
    &lt;/form&gt;
&lt;/div&gt;
</pre><p>Another one easy template for login form. Next one template file:</p><h4>logout_form.html</h4><pre class="brush:html">
&lt;div class=&quot;column&quot;&gt;
    &lt;h3&gt;Hello {name}&lt;/h3&gt;
    &lt;h3&gt;Your bit mask:&lt;/h3&gt;
    &lt;div&gt;{bit_mask}&lt;/div&gt;
    &lt;h3&gt;Your possibilities:&lt;/h3&gt;
    &lt;div&gt;{possibilities}&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;column&quot;&gt;
    &lt;a href=&quot;index.php?logout&quot;&gt;Log Out&lt;/a&gt;
&lt;/div&gt;
</pre><p>This is template where we will display our possibilities and link to logout.</p><h3>Step 2. CSS</h3><h4>css/main.css</h4><p>This file contains several styles of our page layout, no need to publish it today.</p><h3>Step 3. PHP</h3><p>Now, lets review our main functionality:</p><h4>index.php</h4><pre class="brush:php">
&lt;?php

// define bit mask for access rights
define('CAN_READ', 1 &lt;&lt; 0);   // 000001
define('CAN_CREATE', 1 &lt;&lt; 1); // 000010
define('CAN_EDIT_OWN', 1 &lt;&lt; 2);   // 000100
define('CAN_DELETE_OWN', 1 &lt;&lt; 3); // 001000
define('CAN_EDIT_ANY', 1 &lt;&lt; 4);   // 010000
define('CAN_DELETE_ANY', 1 &lt;&lt; 5); // 100000

// login system init and generation code
$oSimpleAccessSystem = new SimpleAccessSystem();
$sLoginForm = $oSimpleAccessSystem-&gt;getLoginBox();
echo strtr(file_get_contents('main_page.html'), array('{form}' =&gt; $sLoginForm));

// class SimpleAccessSystem
class SimpleAccessSystem {

    // variables
    var $aMembers; // Existed members array

    // constructor
    function SimpleAccessSystem() {
        session_start();

        // different sets of permissions
        $sUserPerm = CAN_READ;
        $sWriterPerm = CAN_READ | CAN_CREATE | CAN_EDIT_OWN | CAN_DELETE_OWN;
        $sModeratorPerm = CAN_READ | CAN_EDIT_ANY | CAN_DELETE_ANY;
        $sAdminPerm = CAN_READ | CAN_CREATE | CAN_EDIT_OWN | CAN_DELETE_OWN | CAN_EDIT_ANY | CAN_DELETE_ANY;

        /* hash = sha1(md5('password') . 'testing'); */
        $this-&gt;aMembers = array(
            'User' =&gt; array('hash' =&gt; 'b88c654d6c68fc37f4dda1d29935235eea9a845b', 'salt' =&gt; 'testing', 'rule' =&gt; $sUserPerm),
            'Writer' =&gt; array('hash' =&gt; 'b88c654d6c68fc37f4dda1d29935235eea9a845b', 'salt' =&gt; 'testing', 'rule' =&gt; $sWriterPerm),
            'Moderator' =&gt; array('hash' =&gt; 'b88c654d6c68fc37f4dda1d29935235eea9a845b', 'salt' =&gt; 'testing', 'rule' =&gt; $sModeratorPerm),
            'Admin' =&gt; array('hash' =&gt; 'b88c654d6c68fc37f4dda1d29935235eea9a845b', 'salt' =&gt; 'testing', 'rule' =&gt; $sAdminPerm)
        );
    }

    // get login box function
    function getLoginBox() {
        if (isset($_GET['logout'])) { // logout processing
            if (isset($_SESSION['member_name']) &amp;&amp; isset($_SESSION['member_pass']))
                $this-&gt;performLogout();
        }

        if ($_POST &amp;&amp; $_POST['username'] &amp;&amp; $_POST['password']) { // login processing
            if ($this-&gt;checkLogin($_POST['username'], $_POST['password'], false)) { // successful login
                $this-&gt;performLogin($_POST['username'], $_POST['password']);
                header( &quot;Location:{$_SERVER['REQUEST_URI']}&quot; );
                exit;
            } else { // wrong login
                ob_start(); // get template of Login form
                require_once('login_form.html');
                $sLoginForm = ob_get_clean();
                return $sLoginForm . '&lt;h2&gt;Username or Password is incorrect&lt;/h2&gt;';
            }
        } else { // in case if we already logged (on refresh page):
            if (isset($_SESSION['member_name']) &amp;&amp; $_SESSION['member_name'] &amp;&amp; $_SESSION['member_pass']) {
                if ($this-&gt;checkLogin($_SESSION['member_name'], $_SESSION['member_pass'])) {
                    $sRule = $this-&gt;aMembers[$_SESSION['member_name']]['rule'];
                    $sPermissions = '';
                    $sPermissions .= $this-&gt;isCanRead($sRule);
                    $sPermissions .= $this-&gt;isCanCreate($sRule);
                    $sPermissions .= $this-&gt;isCanEdit($sRule);
                    $sPermissions .= $this-&gt;isCanEditAny($sRule);
                    $sPermissions .= $this-&gt;isCanDelete($sRule);
                    $sPermissions .= $this-&gt;isCanDeleteAny($sRule);

                    ob_start(); // get template of Logout form
                    require_once('logout_form.html');
                    $sLogoutForm = ob_get_clean();
                    $sLogoutForm = str_replace('{name}', $_SESSION['member_name'], $sLogoutForm);
                    $sLogoutForm = str_replace('{bit_mask}', $sRule, $sLogoutForm);
                    $sLogoutForm = str_replace('{possibilities}', $sPermissions, $sLogoutForm);
                    return $sLogoutForm;
                }
            }

            // otherwise - draw login form
            ob_start();
            require_once('login_form.html');
            $sLoginForm = ob_get_clean();
            return $sLoginForm;
        }
    }

    // check functions
    function isCanRead($sRule) {
        return ($sRule &amp; CAN_READ) ? 'You can Read&lt;br /&gt;' : '';
    }
    function isCanCreate($sRule) {
        return ($sRule &amp; CAN_CREATE) ? 'You can Create&lt;br /&gt;' : '';
    }
    function isCanEdit($sRule) {
        return ($sRule &amp; CAN_EDIT_OWN) ? 'You can Edit&lt;br /&gt;' : '';
    }
    function isCanEditAny($sRule) {
        return ($sRule &amp; CAN_EDIT_ANY) ? 'You can Edit anything&lt;br /&gt;' : '';
    }
    function isCanDelete($sRule) {
        return ($sRule &amp; CAN_DELETE_OWN) ? 'You can Delete&lt;br /&gt;' : '';
    }
    function isCanDeleteAny($sRule) {
        return ($sRule &amp; CAN_DELETE_ANY) ? 'You can Delete anything&lt;br /&gt;' : '';
    }

    // perform login
    function performLogin($sName, $sPass) {
        $this-&gt;performLogout();

        $sSalt = $this-&gt;aMembers[$sName]['salt'];
        $sPass = sha1(md5($sPass) . $sSalt);

        $_SESSION['member_name'] = $sName;
        $_SESSION['member_pass'] = $sPass;
    }

    // perform logout
    function performLogout() {
        unset($_SESSION['member_name']);
        unset($_SESSION['member_pass']);
    }

    // check login
    function checkLogin($sName, $sPass, $isHash = true) {
        if (isset($this-&gt;aMembers[$sName])) {
            if (! $isHash) {
                $sSalt = $this-&gt;aMembers[$sName]['salt'];
                $sPass = sha1(md5($sPass) . $sSalt);
            }
            return ($sPass == $this-&gt;aMembers[$sName]['hash']);
        }
        return false;
    }
}
</pre><p>First, we define the constants for access rights (bit mask). Further, when we enumerate users on the system &#8211; we grant them different sets of rights (using the logical operator | or). Keep in mind that I am not forcing you to keep users in the same array, in your case, your users can easily be in the database. And, in this case, you can grant them their right in the database itself. Further, I have added extra check functions, so that we can understand if user can perform a certain action.</p><p>In such functions we use logic operator &amp; (and). Most of these checks uses single bit check. If you want to make multiple check, as example &#8211; lets create function to check if member can read and create. Then this function will looks like this:</p><pre class="brush:php">
    function isCanReadCreate($sRule) {
        return ($sRule &amp; (CAN_READ | CAN_CREATE));
    }
</pre><p>This function will return us True or False.</p><hr
/><h5 style="text-align: center;"><strong><a
title="Access Control with Bit Masks - demo 207" href="http://www.script-tutorials.com/demos/207/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Access Control with Bit Masks - package" href="http://www.script-tutorials.com/demos/207/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>I hope that it was interesting for you to remember how works bitwise and logical operands. If you have any good ideas you would like to share, be sure to write us as well. Good luck!</p><div
class="shr-publisher-1321"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/advance-php-login-system-tutorial/" rel="bookmark"> <img
src="http://www.script-tutorials.com/wp-content/uploads/2010/03/php-login-system-icon.png" alt="How to Easily Make an Advance Level Login system" /> <br
/> How to Easily Make an Advance Level Login system</a></li><li> <a
href="http://www.script-tutorials.com/creating-advance-level-login-system-with-logic-captcha/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/121/thumb.png" alt="Creating Advance Level Login system with Logic captcha" /> <br
/> Creating Advance Level Login system with Logic captcha</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/access-control-with-bit-masks/feed/</wfw:commentRss> <slash:comments>6</slash:comments> </item> <item><title>Own XML/JSON/HTML API with PHP</title><link>http://www.script-tutorials.com/own-xmljsonhtml-api-with-php/</link> <comments>http://www.script-tutorials.com/own-xmljsonhtml-api-with-php/#comments</comments> <pubDate>Thu, 24 Nov 2011 19:22:40 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1242</guid> <description><![CDATA[Own XML/JSON/HTML API with PHP Today I have new PHP article for you. I will tell you about developing own API service for your projects. As an example &#8211; let&#8217;s imagine that we have a video site for which we are going to write the API interface. We teach our API to work with POST [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4>No related posts.</div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Own XML/JSON/HTML API with PHP" alt="Own XML/JSON/HTML API with PHP" src="http://www.script-tutorials.com/demos/189/thumb.png"></div><p><strong>Own XML/JSON/HTML API with PHP</strong><br
/> <br
/>Today I have new PHP article for you. I will tell you about developing own API service for your projects. As an example &#8211; let&#8217;s imagine that we have a video site for which we are going to write the API interface. We teach our API to work with POST / GET requests, and return the result in any of the following formats: XML / JSON / HTML. Also &#8211; as an additional sub-sample &#8211; will show you how to send CURL requests (for example to add records) to our service.<br
/> <span
id="more-1242"></span></p><h5 style="text-align: center;"><strong><a
title="Own XML/JSON/HTML API with PHP - demo 189" href="http://www.script-tutorials.com/demos/189/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Own XML/JSON/HTML API with PHP - package" href="http://www.script-tutorials.com/demos/189/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>Lets add new table for database to keep records about test videos:</p><pre class="brush:sql">
CREATE TABLE IF NOT EXISTS `s189_videos` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `title` varchar(255) default '',
  `author` varchar(255) default '',
  `thumb` varchar(255) default '',
  `views` int(10) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `s189_videos` (`title`, `author`, `thumb`, `views`) VALUES
('SURPRISE? - Ray William Johnson Video', 'RayWilliamJohnson', 'http://i1.ytimg.com/vi/4EwSAzHj8VM/default.jpg', 10000),
('Sophia Grace and Rosie Hit ...', 'TheEllenShow', 'http://i4.ytimg.com/vi/KUWpd91UBrA/default.jpg', 20000),
('The Thanksgiving Massacre!', 'FPSRussia', 'http://i2.ytimg.com/vi/Mgd0Hsgl8gU/default.jpg', 30000),
('WE''RE MARRIED!!!!!!', 'CTFxC', 'http://i2.ytimg.com/vi/q1tsmlKXqK8/default.jpg', 40000),
('Guinea Pig Boat IN OUR MAIL?!', 'IanH', 'http://i4.ytimg.com/vi/3t1YysIt598/default.jpg', 50000),
('SCARED PUPPY!!!', 'Tobuscus', 'http://i1.ytimg.com/vi/8RcYkGr_IIw/default.jpg', 60000),
('Review: Jawbone Up', 'SoldierKnowsBest', 'http://i4.ytimg.com/vi/WraMbywRR9M/default.jpg', 70000);
</pre><p>This is just random records from youtube.</p><h3>Step 2. PHP</h3><p>Now, lets review our test page:</p><h4>index.php</h4><pre class="brush:php">
&lt;?php

// Test - using POST for add video record
if (isset($_GET['action']) &amp;&amp; $_GET['action'] == 'curl') {

    $sUrl = &quot;http://your_host_url/service.php&quot;;
    $sData = 'title=TestVideo&amp;action=add_video&amp;type=xml';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $sUrl);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $sData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    $vRes = curl_exec($ch);
    curl_close($ch);

    header('Content-Type: text/xml');
    echo $vRes;
    exit;
}

?&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;Own XML/JSON/HTML API with PHP | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;header&gt;
            &lt;h2&gt;Own XML/JSON/HTML API with PHP&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/own-xmljsonhtml-api-with-php/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/header&gt;
        &lt;div class=&quot;container&quot;&gt;

            &lt;div class=&quot;contr&quot;&gt;
                &lt;form action=&quot;service.php&quot; target=&quot;results&quot;&gt;
                    &lt;label&gt;Action: &lt;/label&gt;
                    &lt;select name=&quot;action&quot;&gt;
                        &lt;option value=&quot;last_videos&quot;&gt;Last videos&lt;/option&gt;
                        &lt;option value=&quot;top_videos&quot;&gt;Top videos&lt;/option&gt;
                    &lt;/select&gt;
                    &lt;label&gt;Limit: &lt;/label&gt;
                    &lt;select name=&quot;limit&quot;&gt;
                        &lt;option value=&quot;1&quot;&gt;1&lt;/option&gt;
                        &lt;option value=&quot;2&quot;&gt;2&lt;/option&gt;
                        &lt;option value=&quot;3&quot;&gt;3&lt;/option&gt;
                        &lt;option value=&quot;4&quot; selected&gt;4&lt;/option&gt;
                        &lt;option value=&quot;5&quot;&gt;5&lt;/option&gt;
                        &lt;option value=&quot;6&quot;&gt;6&lt;/option&gt;
                        &lt;option value=&quot;7&quot;&gt;7&lt;/option&gt;
                    &lt;/select&gt;
                    &lt;label&gt;Method: &lt;/label&gt;
                    &lt;select name=&quot;type&quot;&gt;
                        &lt;option value=&quot;xml&quot;&gt;XML&lt;/option&gt;
                        &lt;option value=&quot;json&quot;&gt;JSON&lt;/option&gt;
                        &lt;option value=&quot;html&quot;&gt;HTML&lt;/option&gt;
                    &lt;/select&gt;
                    &lt;input type=&quot;submit&quot; /&gt;
                &lt;/form&gt;
                &lt;a href=&quot;index.php?action=curl&quot;&gt;Add video (CURL)&lt;/a&gt;
            &lt;/div&gt;

            &lt;div&gt;Results:&lt;/div&gt;
            &lt;iframe name=&quot;results&quot; style=&quot;width:600px;height:400px&quot;&gt;
            &lt;/iframe&gt;
        &lt;/div&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>As you can see &#8211; most of code is just HTML code. But in beginning &#8211; our sub-sample of sending CURL request. Next file &#8211; our service file (service index file)</p><h4>service.php</h4><pre class="brush:php">
&lt;?php

require_once('classes/CMySQL.php'); // including service class to work with database
require_once('classes/CServices.php'); // including service class to work with database
$oServices = new CServices();

// set method
$oServices-&gt;setMethod($_REQUEST['type']);

// set possible limit
if (isset($_GET['limit']) &amp;&amp; (int)$_GET['limit']) {
    $oServices-&gt;setLimit((int)$_GET['limit']);
}

// process actions
switch ($_REQUEST['action']) {
    case 'last_videos':
        $oServices-&gt;getLastVideos();
        break;
    case 'top_videos':
        $oServices-&gt;setOrder('top');
        $oServices-&gt;getLastVideos();
        break;
    case 'add_video':
        $oServices-&gt;addVideo($_POST['title']);
        break;
}
</pre><p>Pretty easy file. It processing all requests with using &#8216;CServices&#8217; class (main service class). Now we going to develop this class that will provide all the utility functions we need.</p><h4>classes/CServices.php</h4><pre class="brush:php">
&lt;?php

class CServices {

    private $sMethod;
    private $iLimit;
    private $sOrder;

    // constructor
    public function CServices() {
        $this-&gt;sMethod = 'xml';
        $this-&gt;iLimit = 5;
        $this-&gt;sOrder = 'last';
    }

    // set method
    public function setMethod($s) {
        $this-&gt;sMethod = $s;
    }

    // set limit
    public function setLimit($i) {
        $this-&gt;iLimit = ($i &gt; 0 &amp;&amp; $i &lt; 10) ? $i : $this-&gt;iLimit;
    }

    // set order
    public function setOrder($s) {
        $this-&gt;sOrder = $s;
    }

    // return list of videos
    public function getLastVideos() {
        // define order field
        $sOrderField = ($this-&gt;sOrder == 'last') ? 'title' : 'views';

        // obtain data from database
        $aData = $GLOBALS['MySQL']-&gt;getAll(&quot;SELECT * FROM `s189_videos` ORDER BY `{$sOrderField}` DESC LIMIT {$this-&gt;iLimit}&quot;);

        // output in necessary format
        switch ($this-&gt;sMethod) {
            case 'json': // gen JSON result
                // you can uncomment it for Live version
                // header('Content-Type: text/xml; charset=utf-8');
                if (count($aData)) {
                    echo json_encode(array('data' =&gt; $aData));
                } else {
                    echo json_encode(array('data' =&gt; 'Nothing found'));
                }
                break;
            case 'xml': // gen XML result
                $sCode = '';
                if (count($aData)) {
                    foreach ($aData as $i =&gt; $aRecords) {
                        $sCode .= &lt;&lt;&lt;EOF
&lt;unit&gt;
    &lt;id&gt;{$aRecords['id']}&lt;/id&gt;
    &lt;title&gt;{$aRecords['title']}&lt;/title&gt;
    &lt;author&gt;{$aRecords['author']}&lt;/author&gt;
    &lt;image&gt;{$aRecords['thumb']}&lt;/image&gt;
    &lt;views&gt;{$aRecords['views']}&lt;/views&gt;
&lt;/unit&gt;
EOF;
                    }
                }

                header('Content-Type: text/xml; charset=utf-8');
                echo &lt;&lt;&lt;EOF
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;videos&gt;
{$sCode}
&lt;/videos&gt;
EOF;
                break;
            case 'html': // gen HTML result
                $sCode = '';
                if (count($aData)) {
                    foreach ($aData as $i =&gt; $aRecords) {
                        $sCode .= &lt;&lt;&lt;EOF
&lt;div&gt;
    &lt;img src=&quot;{$aRecords['thumb']}&quot; style=&quot;float:left;margin-right:10px;&quot; /&gt;
    &lt;p&gt;Title: {$aRecords['title']}&lt;/p&gt;
    &lt;p&gt;Author: {$aRecords['author']}&lt;/p&gt;
    &lt;p&gt;Views: {$aRecords['views']}&lt;/p&gt;
&lt;/div&gt;
EOF;
                    }
                } else {
                    $sCode = '&lt;div&gt;Nothing found&lt;/div&gt;';
                }

                header('Content-Type: text/html; charset=utf-8');
                echo $sCode;
                break;
        }
    }

    public function addVideo($sTitle) {
        // just simulation
        $aData = array('res' =&gt; 'Video &quot;' . $sTitle . '&quot; added successfully');

        switch ($this-&gt;sMethod) {
            case 'json':
                header('Content-Type: text/xml; charset=utf-8');
                echo json_encode($aData);
                break;
            case 'xml':
                header('Content-Type: text/xml; charset=utf-8');
                echo &lt;&lt;&lt;EOF
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;res&gt;
{$aData['res']}
&lt;/res&gt;
EOF;
                break;
            case 'html':
                header('Content-Type: text/html; charset=utf-8');
                echo '&lt;div&gt;' . $aData['res'] . '&lt;/div&gt;';
                break;
        }
    }
}
</pre><p>In this class I added all service functions. One of the functions &#8211; &#8216;getLastVideos&#8217; is made to retrieve lists the video. Second one &#8216;addVideo&#8217; &#8211; for adding new videos. Of course &#8211; I did not add the video actually &#8211; just model the process. As a result of the function &#8211; I generate the result in the requested format.</p><h4>classes/CMySQL.php</h4><p>This is our regular service class to work with the database. Available in package.</p><hr
/><h5 style="text-align: center;"><strong><a
title="Own XML/JSON/HTML API with PHP - demo 189" href="http://www.script-tutorials.com/demos/189/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Own XML/JSON/HTML API with PHP - package" href="http://www.script-tutorials.com/demos/189/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>Pretty cool stuff, isn`t it? With a little bit of code and some clever logic, you can add a fully functional API to your projects. If you have got any good ideas you would like to share, be sure to drop those in the comments as well. Good luck!</p><div
class="shr-publisher-1242"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><p>No related posts.</p></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/own-xmljsonhtml-api-with-php/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Creating a Diary style PHP Guestbook</title><link>http://www.script-tutorials.com/php-guestbook/</link> <comments>http://www.script-tutorials.com/php-guestbook/#comments</comments> <pubDate>Mon, 07 Nov 2011 18:02:58 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[diary]]></category> <category><![CDATA[guestbook]]></category> <category><![CDATA[script]]></category> <category><![CDATA[style]]></category> <category><![CDATA[tutorial]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1187</guid> <description><![CDATA[PHP guestbook Today I prepared new interesting tutorial &#8211; I will tell how you can create ajax PHP guestbook with own unique design. Our records will be saved into SQL database. This table will contain next info: name of sender, email, guestbook record, date-time of record and ip of sender. Of course, we will use [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-make-a-php-guestbook-with-math-captcha-security/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to make a PHP Guestbook with Math Captcha Security" /> How to make a PHP Guestbook with Math Captcha Security</a></li><li> <a
href="http://www.script-tutorials.com/how-to-create-own-commenting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/163/thumb.png" alt="Creating Your Own Commenting System from Scratch" /> Creating Your Own Commenting System from Scratch</a></li><li> <a
href="http://www.script-tutorials.com/autocomplete-with-php-jquery-mysql-and-xml/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/160/thumb.png" alt="Autocomplete with PHP, jQuery, MySQL and XML" /> Autocomplete with PHP, jQuery, MySQL and XML</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="PHP guestbook" alt="PHP guestbook" src="http://www.script-tutorials.com/demos/178/thumb.png"></div><p><strong>PHP guestbook</strong><br
/> <br
/>Today I prepared new interesting tutorial &#8211; I will tell how you can create ajax PHP guestbook with own unique design. Our records will be saved into SQL database. This table will contain next info: name of sender, email, guestbook record, date-time of record and ip of sender. Of course, we will use jQuery too (to make it ajaxy). One of important features will spam protection (we can post no more than one record every 10 minutes)!<br
/> <span
id="more-1187"></span></p><h5 style="text-align: center;"><strong><a
title="PHP guestbook - demo 178" href="http://www.script-tutorials.com/demos/178/guestbook.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="PHP guestbook - package" href="http://www.script-tutorials.com/demos/178/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>We need to add one table to our database (to store our records):</p><pre class="brush:php">
CREATE TABLE IF NOT EXISTS `s178_guestbook` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(255) default '',
  `email` varchar(255) default '',
  `description` varchar(255) default '',
  `when` int(11) NOT NULL default '0',
  `ip` varchar(20) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</pre><h3>Step 2. PHP</h3><p>Here are source code of our main file:</p><h4>guestbook.php</h4><pre class="brush:php">
&lt;?php
// disabling possible warnings
if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;)  == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE); 

require_once('classes/CMySQL.php'); // including service class to work with database

// get visitor IP
function getVisitorIP() {
    $ip = &quot;0.0.0.0&quot;;
    if( ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) &amp;&amp; ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif( ( isset( $_SERVER['HTTP_CLIENT_IP'])) &amp;&amp; (!empty($_SERVER['HTTP_CLIENT_IP'] ) ) ) {
        $ip = explode(&quot;.&quot;,$_SERVER['HTTP_CLIENT_IP']);
        $ip = $ip[3].&quot;.&quot;.$ip[2].&quot;.&quot;.$ip[1].&quot;.&quot;.$ip[0];
    } elseif((!isset( $_SERVER['HTTP_X_FORWARDED_FOR'])) || (empty($_SERVER['HTTP_X_FORWARDED_FOR']))) {
        if ((!isset( $_SERVER['HTTP_CLIENT_IP'])) &amp;&amp; (empty($_SERVER['HTTP_CLIENT_IP']))) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    }
    return $ip;
}

// get last guestbook records
function getLastRecords($iLimit = 3) {
    $sRecords = '';
    $aRecords = $GLOBALS['MySQL']-&gt;getAll(&quot;SELECT * FROM `s178_guestbook` ORDER BY `id` DESC LIMIT {$iLimit}&quot;);
    foreach ($aRecords as $i =&gt; $aInfo) {
        $sWhen = date('F j, Y H:i', $aInfo['when']);
        $sRecords .= &lt;&lt;&lt;EOF
&lt;div class=&quot;record&quot; id=&quot;{$aInfo['id']}&quot;&gt;
    &lt;p&gt;Record from {$aInfo['name']} &lt;span&gt;({$sWhen})&lt;/span&gt;:&lt;/p&gt;
    &lt;p&gt;{$aInfo['description']}&lt;/p&gt;
&lt;/div&gt;
EOF;
    }
    return $sRecords;
}

if ($_POST) { // accepting new records

    $sIp = getVisitorIP();
    $sName = $GLOBALS['MySQL']-&gt;escape(strip_tags($_POST['name']));
    $sEmail = $GLOBALS['MySQL']-&gt;escape(strip_tags($_POST['name']));
    $sDesc = $GLOBALS['MySQL']-&gt;escape(strip_tags($_POST['text']));

    if ($sName &amp;&amp; $sEmail &amp;&amp; $sDesc &amp;&amp; $sIp) {

        // spam protection
        $iOldId = $GLOBALS['MySQL']-&gt;getOne(&quot;SELECT `id` FROM `s178_guestbook` WHERE `ip` = '{$sIp}' AND `when` &gt;= UNIX_TIMESTAMP() - 600 LIMIT 1&quot;);
        if (! $iOldId) {

            // allow to add comment
            $GLOBALS['MySQL']-&gt;res(&quot;INSERT INTO `s178_guestbook` SET `name` = '{$sName}', `email` = '{$sEmail}', `description` = '{$sDesc}', `when` = UNIX_TIMESTAMP(), `ip` = '{$sIp}'&quot;);

            // drawing last 10 records
            $sOut = getLastRecords();
            echo $sOut;
            exit;
        }
    }
    echo 1;
    exit;
}

// drawing last 10 records
$sRecords = getLastRecords();

ob_start();
?&gt;
&lt;div class=&quot;container&quot; id=&quot;records&quot;&gt;
    &lt;div id=&quot;col1&quot;&gt;
        &lt;h2&gt;Guestbook Records&lt;/h2&gt;
        &lt;div id=&quot;records_list&quot;&gt;&lt;?= $sRecords ?&gt;&lt;/div&gt;
    &lt;/div&gt;

    &lt;div id=&quot;col2&quot;&gt;
        &lt;h2&gt;Add your record here&lt;/h2&gt;
        &lt;script type=&quot;text/javascript&quot;&gt;
        function submitComment(e) {
            var name = $('#name').val();
            var email = $('#email').val();
            var text = $('#text').val();

            if (name &amp;&amp; email &amp;&amp; text) {
                $.post('guestbook.php', { 'name': name, 'email': email, 'text': text },
                    function(data){
                        if (data != '1') {
                          $('#records_list').fadeOut(1000, function () {
                            $(this).html(data);
                            $(this).fadeIn(1000);
                          });
                        } else {
                          $('#warning2').fadeIn(2000, function () {
                            $(this).fadeOut(2000);
                          });
                        }
                    }
                );
            } else {
              $('#warning1').fadeIn(2000, function () {
                $(this).fadeOut(2000);
              });
            }
        };
        &lt;/script&gt;

        &lt;form onsubmit=&quot;submitComment(this); return false;&quot;&gt;
            &lt;table&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&lt;label&gt;Your name: &lt;/label&gt;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;&quot; title=&quot;Please enter your name&quot; id=&quot;name&quot; /&gt;&lt;/td&gt;&lt;/tr&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&lt;label&gt;Your email: &lt;/label&gt;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;&quot; title=&quot;Please enter your email&quot; id=&quot;email&quot; /&gt;&lt;/td&gt;&lt;/tr&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&lt;label&gt;Comment: &lt;/label&gt;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;&lt;textarea name=&quot;text&quot; id=&quot;text&quot; maxlength=&quot;255&quot;&gt;&lt;/textarea&gt;&lt;/td&gt;&lt;/tr&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&amp;nbsp;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;
                    &lt;div id=&quot;warning1&quot; style=&quot;display:none&quot;&gt;Don`t forget to fill all required fields&lt;/div&gt;
                    &lt;div id=&quot;warning2&quot; style=&quot;display:none&quot;&gt;You can post no more than one comment every 10 minutes (spam protection)&lt;/div&gt;
                    &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;
                &lt;/td&gt;&lt;/tr&gt;
            &lt;/table&gt;
        &lt;/form&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;?
$sGuestbookBlock = ob_get_clean();

?&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;PHP guestbook | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;!--[if lt IE 9]&gt;
          &lt;script src=&quot;http://html5shiv.googlecode.com/svn/trunk/html5.js&quot;&gt;&lt;/script&gt;
        &lt;![endif]--&gt;
        &lt;script src=&quot;http://code.jquery.com/jquery-latest.min.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;?= $sGuestbookBlock ?&gt;
        &lt;footer&gt;
            &lt;h2&gt;PHP guestbook&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/php-guestbook/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>When we open this page we will see book, at left side we will draw list of last three records, at right &#8211; form of posting new records. When we submitting form &#8211; script sending POST data (to same php page), script saving this data to database, and returning us list of fresh 3 records. Then, via fading effect we draw returned data at left column. All code contains comments &#8211; read it for better understanding code. Ok, next PHP file is:</p><h4>classes/CMySQL.php</h4><p>This is my own service class to work with database. This is nice class which you can use too. Database connection details located in this class in few variables, sure that you will able to configure this to your database. I don`t will publish its sources &#8211; this is not necessary for now. Available in package.</p><h3>Step 3. CSS</h3><p>Now &#8211; all used CSS styles:</p><h4>css/main.css</h4><pre class="brush:js">
*{
    margin:0;
    padding:0;
}
body {
    background-color:#fff;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}
footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}
footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}
footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}
footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

.container {
    background: transparent url(../images/book_open.jpg) no-repeat top center ;
    color: #000000;
    height: 600px;
    margin: 20px auto;
    overflow: hidden;
    padding: 35px 100px;
    position: relative;
    width: 600px;
}
#col1, #col2 {
    float: left;
    margin: 0 10px;
    overflow: hidden;
    text-align: center;
    width: 280px;
}
#col1 {
    -webkit-transform: rotate(3deg);
    -moz-transform: rotate(3deg);
    -ms-transform: rotate(3deg);
    -o-transform: rotate(3deg);
}
#records form {
    margin:10px 0;
    padding:10px;
    text-align:left;
}
#records table td.label {
    color: #000;
    font-size: 13px;
    padding-right: 3px;
    text-align: right;
}
#records table label {
    font-size: 12px;
    vertical-align: middle;
}
#records table td.field input, #records table td.field textarea {
    background-color: rgba(255, 255, 255, 0.4);
    border: 0px solid #96A6C5;
    font-family: Verdana,Arial,sans-serif;
    font-size: 13px;
    margin-top: 2px;
    padding: 6px;
    width: 190px;
}
#records table td.field input[type=submit] {
    background-color: rgba(200, 200, 200, 0.4);
    cursor: pointer;
    float:right;
    width: 100px;
}
#records table td.field input[type=submit]:hover {
    background-color: rgba(200, 200, 200, 0.8);
}
#records_list {
    text-align:left;
}
#records_list .record {
    border-top: 1px solid #000000;
    font-size: 13px;
    padding: 10px;
}
#records_list .record:first-child {
    border-top-width:0px;
}
#records_list .record p:first-child {
    font-weight:bold;
    font-size:11px;
}
</pre><hr
/><h5 style="text-align: center;"><strong><a
title="PHP guestbook - demo 178" href="http://www.script-tutorials.com/demos/178/guestbook.php" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="PHP guestbook - package" href="http://www.script-tutorials.com/demos/178/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>Today we have prepared great PHP guestbook for your website. Sure that this material will be useful for your own projects. Good luck in your work!</p><div
class="shr-publisher-1187"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-make-a-php-guestbook-with-math-captcha-security/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="How to make a PHP Guestbook with Math Captcha Security" /> <br
/> How to make a PHP Guestbook with Math Captcha Security</a></li><li> <a
href="http://www.script-tutorials.com/how-to-create-own-commenting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/163/thumb.png" alt="Creating Your Own Commenting System from Scratch" /> <br
/> Creating Your Own Commenting System from Scratch</a></li><li> <a
href="http://www.script-tutorials.com/autocomplete-with-php-jquery-mysql-and-xml/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/160/thumb.png" alt="Autocomplete with PHP, jQuery, MySQL and XML" /> <br
/> Autocomplete with PHP, jQuery, MySQL and XML</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/php-guestbook/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Creating a Smooth Curve Graphs with PHP and GD</title><link>http://www.script-tutorials.com/smooth-curve-graphs-with-php-and-gd/</link> <comments>http://www.script-tutorials.com/smooth-curve-graphs-with-php-and-gd/#comments</comments> <pubDate>Mon, 24 Oct 2011 16:53:21 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[curve]]></category> <category><![CDATA[gd]]></category> <category><![CDATA[graph]]></category> <category><![CDATA[php graph]]></category> <category><![CDATA[smoot]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1140</guid> <description><![CDATA[Smooth Curve Graphs with PHP and GD Today I have new article for PHP. I will tell you about drawing graphs with GD. Plus &#8211; we will smooth our graph with curve lines using cubic splines interpolation method. You can read more about method at Wiki. Live Demo download in package Now &#8211; download the [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-animation-patterns-with-loops/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/194/thumb.png" alt="HTML5 animation &#8211; patterns with loops" /> HTML5 animation &#8211; patterns with loops</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Smooth Curve Graphs with PHP and GD" alt="Smooth Curve Graphs with PHP and GD" src="http://www.script-tutorials.com/demos/169/thumb.png"></div><p><strong>Smooth Curve Graphs with PHP and GD</strong><br
/> <br
/>Today I have new article for PHP. I will tell you about drawing graphs with GD. Plus &#8211; we will smooth our graph with curve lines using <strong>cubic splines</strong> interpolation method. You can read more about method at <a
href="http://en.wikipedia.org/wiki/Cubic_splines" target="_blank">Wiki</a>.<br
/> <span
id="more-1140"></span></p><h5 style="text-align: center;"><strong><a
title="Smooth Curve Graphs with PHP and GD - demo 169" href="http://www.script-tutorials.com/demos/169/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Smooth Curve Graphs with PHP and GD - package" href="http://www.script-tutorials.com/demos/169/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. HTML</h3><p>Here are HTML layout for our example page:</p><h4>index.html</h4><pre class="brush:php">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;Smooth Curve Graphs with PHP and GD | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;img src=&quot;smooth_graph.php&quot; alt=&quot;&quot; /&gt;
        &lt;/div&gt;
        &lt;footer&gt;
            &lt;h2&gt;Smooth Curve Graphs with PHP and GD&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/smooth-curve-graphs-with-php-and-gd/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><h3>Step 2. CSS</h3><p>Now, lets define all used styles:</p><h4>css/main.css</h4><pre class="brush:css">
*{
    margin:0;
    padding:0;
}

body {
    background-repeat:no-repeat;
    background-color:#bababa;
    background-image: -webkit-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -moz-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -o-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
    min-height:600px;
}

footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}

footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}

footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}

footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

.container {
    border:3px #111 solid;
    margin:20px auto;
    padding:20px;
    position:relative;
    width:550px;
    height:430px;

    border-radius:15px;
    -moz-border-radius:15px;
    -webkit-border-radius:15px;
}
</pre><p>And first step and second &#8211; not very important of course, most important will now:</p><h3>Step 3. PHP</h3><p>This is our image generator (of graph):</p><h4>smooth_graph.php</h4><pre class="brush:php">
&lt;?php
set_time_limit(100);

define('GRAPH_WIDTH',  500);
define('GRAPH_HEIGHT', 400);

include_once ('classes/Plot.php');
include_once ('classes/CubicSplines.php');

$iPoints = 15;
$dx = (GRAPH_WIDTH - 40) / ($iPoints - 1);
$x = 20;

for ($i = 0; $i &lt; $iPoints; $i++) {
    $y = rand(20, GRAPH_HEIGHT - 20);
    $aCoords[$x] = $y;
    $x+= $dx;
}

$vImagegHeight = GRAPH_HEIGHT + 30;
$vImage = imagecreatetruecolor(GRAPH_WIDTH + 50, $vImagegHeight);

$vBgColor = imagecolorallocate($vImage, 160, 160, 160);
$vTextColor = imagecolorallocate($vImage, 0, 0, 0);
$vAxisColor = imagecolorallocate($vImage, 0, 0, 0);
$vDotColor  = imagecolorallocate($vImage, 192, 64, 64);

imagefill($vImage, 0, 0, $vBgColor);

$oPlot = new Plot($aCoords);
$oPlot-&gt;drawDots($vImage, $vDotColor, 10, GRAPH_HEIGHT, 8);

$oCurve = new CubicSplines();
$vColor = imagecolorallocate($vImage, 225, 64, 64);

$iStart = microtime(1);
if ($oCurve) {
    $oCurve-&gt;setInitCoords($aCoords, 1);
    $r = $oCurve-&gt;processCoords();
    if ($r)
        $curveGraph = new Plot($r);
    else
        continue;
} else {
    $curveGraph = $oPlot;
}

$curveGraph-&gt;drawLine($vImage, $vColor, 10, GRAPH_HEIGHT);

// unset($oCurve);
$sTime = sprintf(&quot;%1.4f&quot;, microtime(1) - $iStart);

imagefilledrectangle($vImage, 0, GRAPH_HEIGHT, GRAPH_WIDTH + 50, $vImagegHeight, $vBgColor);
$oPlot-&gt;drawAxis($vImage, $vAxisColor, 10, GRAPH_HEIGHT);
$iPanelY = GRAPH_HEIGHT;

imagefilledrectangle($vImage, 10, $iPanelY + 10, 20, $iPanelY + 20, $vColor);
imagerectangle($vImage, 10, $iPanelY + 10, 20, $iPanelY + 20, $vAxisColor);
imagettftext($vImage, 10, 0, 30, $iPanelY + 20, $vTextColor, 'Ds-digib.ttf', 'Cubic splines in PHP for graphs:         ' . $sTime . ' sec');

header(&quot;Content-type: image/png&quot;);
imagepng($vImage);
imagedestroy($vImage);

?&gt;
</pre><p>In this file I using 2 another classes (as separated service classes):</p><h4>classes/Plot.php</h4><pre class="brush:php">
&lt;?php

class Plot {
    private $aCoords;

    function __construct(&amp;$aCoords) {
        $this-&gt;aCoords = &amp;$aCoords;
    }

    public function drawLine($vImage, $vColor, $iPosX = 0, $iPosY = false) {
        if ($iPosY === false)
            $iPosY = imagesy($vImage);

        reset($this-&gt;aCoords);
        list($iPrevX, $iPrevY) = each($this-&gt;aCoords);

        while (list ($x, $y) = each($this-&gt;aCoords)) {
            imageline($vImage, $iPosX + round($iPrevX), $iPosY - round($iPrevY), $iPosX + round($x), $iPosY - round($y), $vColor);
            $iPrevX = $x;
            $iPrevY = $y;
        }
    }

    public function drawDots($vImage, $vColor, $iPosX = 0, $iPosY = false, $iDotSize = 1) {
        if ($iPosY === false)
            $iPosY = imagesy($vImage);

        $vBorderColor = imagecolorallocate($vImage, 0, 0, 0);
        foreach ($this-&gt;aCoords as $x =&gt; $y) {
            imagefilledellipse($vImage, $iPosX + round($x), $iPosY - round($y), $iDotSize, $iDotSize, $vColor);
            imageellipse($vImage, $iPosX + round($x), $iPosY - round($y), $iDotSize, $iDotSize, $vBorderColor);
        }
    }

    public function drawAxis($vImage, $vColor, $iPosX = 0, $iPosY = false) {
        if ($iPosY === false)
            $iPosY = imagesy($vImage);

        $vImageWidth = imagesx($vImage);
        imageline($vImage, $iPosX, $iPosY, $iPosX, 0, $vColor);
        imageline($vImage, $iPosX, $iPosY, $vImageWidth, $iPosY, $vColor);

        imagefilledpolygon($vImage, array($iPosX, 0, $iPosX - 3, 5, $iPosX + 3, 5), 3, $vColor);
        imagefilledpolygon($vImage, array($vImageWidth, $iPosY, $vImageWidth - 5, $iPosY - 3, $vImageWidth - 5, $iPosY + 3), 3, $vColor);
    }
}

?&gt;
</pre><h4>and classes/CubicSplines.php</h4><pre class="brush:php">
&lt;?php

class CubicSplines {
    protected $aCoords;
    protected $aCrdX;
    protected $aCrdY;
    protected $aSplines = array();
    protected $iMinX;
    protected $iMaxX;
    protected $iStep;

    protected function prepareCoords(&amp;$aCoords, $iStep, $iMinX = -1, $iMaxX = -1) {
        $this-&gt;aCrdX = array();
        $this-&gt;aCrdY = array();
        $this-&gt;aCoords = array();

        ksort($aCoords);
        foreach ($aCoords as $x =&gt; $y) {
            $this-&gt;aCrdX[] = $x;
            $this-&gt;aCrdY[] = $y;
        }

        $this-&gt;iMinX = $iMinX;
        $this-&gt;iMaxX = $iMaxX;

        if ($this-&gt;iMinX == -1)
            $this-&gt;iMinX = min($this-&gt;aCrdX);
        if ($this-&gt;iMaxX == -1)
            $this-&gt;iMaxX = max($this-&gt;aCrdX);

        $this-&gt;iStep = $iStep;
    }

    public function setInitCoords(&amp;$aCoords, $iStep = 1, $iMinX = -1, $iMaxX = -1) {
        $this-&gt;aSplines = array();

        if (count($aCoords) &lt; 4) {
            return false;
        }

        $this-&gt;prepareCoords($aCoords, $iStep, $iMinX, $iMaxX);
        $this-&gt;buildSpline($this-&gt;aCrdX, $this-&gt;aCrdY, count($this-&gt;aCrdX));
    }

    public function processCoords() {
        for ($x = $this-&gt;iMinX; $x &lt;= $this-&gt;iMaxX; $x += $this-&gt;iStep) {
            $this-&gt;aCoords[$x] = $this-&gt;funcInterp($x);
        }

        return $this-&gt;aCoords;
    }

    private function buildSpline($x, $y, $n) {
        for ($i = 0; $i &lt; $n; ++$i) {
            $this-&gt;aSplines[$i]['x'] = $x[$i];
            $this-&gt;aSplines[$i]['a'] = $y[$i];
        }

        $this-&gt;aSplines[0]['c'] = $this-&gt;aSplines[$n - 1]['c'] = 0;
        $alpha[0] = $beta[0] = 0;
        for ($i = 1; $i &lt; $n - 1; ++$i) {
            $h_i = $x[$i] - $x[$i - 1];
            $h_i1 = $x[$i + 1] - $x[$i];
            $A = $h_i;
            $C = 2.0 * ($h_i + $h_i1);
            $B = $h_i1;
            $F = 6.0 * (($y[$i + 1] - $y[$i]) / $h_i1 - ($y[$i] - $y[$i - 1]) / $h_i);
            $z = ($A * $alpha[$i - 1] + $C);
            $alpha[$i] = - $B / $z;
            $beta[$i] = ($F - $A * $beta[$i - 1]) / $z;
        }

        for ($i = $n - 2; $i &gt; 0; --$i) {
            $this-&gt;aSplines[$i]['c'] = $alpha[$i] * $this-&gt;aSplines[$i + 1]['c'] + $beta[$i];
        }

        for ($i = $n - 1; $i &gt; 0; --$i) {
            $h_i = $x[$i] - $x[$i - 1];
            $this-&gt;aSplines[$i]['d'] = ($this-&gt;aSplines[$i]['c'] - $this-&gt;aSplines[$i - 1]['c']) / $h_i;
            $this-&gt;aSplines[$i]['b'] = $h_i * (2.0 * $this-&gt;aSplines[$i]['c'] + $this-&gt;aSplines[$i - 1]['c']) / 6.0 + ($y[$i] - $y[$i - 1]) / $h_i;
        }
    }

    private function funcInterp($x) {
        $n = count($this-&gt;aSplines);
        if ($x &lt;= $this-&gt;aSplines[0]['x'])  {
            $s = $this-&gt;aSplines[1];
        } else {
            if ($x &gt;= $this-&gt;aSplines[$n - 1]['x']) {
                $s = $this-&gt;aSplines[$n - 1];
            } else {
                $i = 0;
                $j = $n - 1;
                while ($i + 1 &lt; $j) {
                    $k = $i + ($j - $i) / 2;
                    if ($x &lt;= $this-&gt;aSplines[$k]['x']) {
                        $j = $k;
                    } else {
                        $i = $k;
                    }
                }

                $s = $this-&gt;aSplines[$j];
            }
        }

        $dx = ($x - $s['x']);
        return $s['a'] + ($s['b'] + ($s['c'] / 2.0 + $s['d'] * $dx / 6.0) * $dx) * $dx;
    }
}

?&gt;
</pre><hr
/><h5 style="text-align: center;"><strong><a
title="Smooth Curve Graphs with PHP and GD - demo 169" href="http://www.script-tutorials.com/demos/169/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Smooth Curve Graphs with PHP and GD - package" href="http://www.script-tutorials.com/demos/169/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>I hope that you got interesting lesson for today. Good luck in your work!</p><div
class="shr-publisher-1140"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/html5-animation-patterns-with-loops/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/194/thumb.png" alt="HTML5 animation &#8211; patterns with loops" /> <br
/> HTML5 animation &#8211; patterns with loops</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/smooth-curve-graphs-with-php-and-gd/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>Creating Your Own Commenting System from Scratch</title><link>http://www.script-tutorials.com/how-to-create-own-commenting-system/</link> <comments>http://www.script-tutorials.com/how-to-create-own-commenting-system/#comments</comments> <pubDate>Fri, 14 Oct 2011 17:08:46 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[commenting system]]></category> <category><![CDATA[comments]]></category> <category><![CDATA[creating]]></category> <category><![CDATA[script]]></category> <category><![CDATA[system]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1109</guid> <description><![CDATA[How to create own commenting system Today I prepared new interesting article &#8211; I will tell how you can create own commenting system (AJAX) for your items (any units at your website) with PHP. For our demonstration &#8211; I prepared two SQL tables: first table will keep records of our items. It contain several fields: [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-create-own-voting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/155/thumb.png" alt="How to Create Your Own 5 Stars Voting System" /> How to Create Your Own 5 Stars Voting System</a></li><li> <a
href="http://www.script-tutorials.com/php-guestbook/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/178/thumb.png" alt="Creating a Diary style PHP Guestbook" /> Creating a Diary style PHP Guestbook</a></li><li> <a
href="http://www.script-tutorials.com/creating-own-ajax-poll-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/183/thumb.png" alt="Creating Your Own Ajax Poll System" /> Creating Your Own Ajax Poll System</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="How to create own commenting system" alt="How to create own commenting system" src="http://www.script-tutorials.com/demos/163/thumb.png"></div><p><strong>How to create own commenting system</strong><br
/> <br
/>Today I prepared new interesting article &#8211; I will tell how you can create own commenting system (AJAX) for your items (any units at your website) with PHP. For our demonstration &#8211; I prepared two SQL tables: first table will keep records of our items. It contain several fields: title, description, time of adding and comments count. Another table will keep records of comments. We will use jQuery too (for better interface behavior). One of features will spam protection (we can post no more than one comment every 10 minutes)!<br
/> <span
id="more-1109"></span></p><h5 style="text-align: center;"><strong><a
title="How to create own commenting system - demo 163" href="http://www.script-tutorials.com/demos/163/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="How to create own commenting system - package" href="http://www.script-tutorials.com/demos/163/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>We will need to add 2 tables into our database:</p><pre class="brush:php">
CREATE TABLE IF NOT EXISTS `s163_items` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `title` varchar(255) default '',
  `description` text NOT NULL,
  `when` int(11) NOT NULL default '0',
  `comments_count` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `s163_items` (`title`, `description`, `when`, `comments_count`) VALUES
('Item #1', 'Here are you can put description of Item #1', UNIX_TIMESTAMP(), '0'),
('Item #2', 'Here are you can put description of Item #2', UNIX_TIMESTAMP()+1, '0'),
('Item #3', 'Here are you can put description of Item #3', UNIX_TIMESTAMP()+2, '0'),
('Item #4', 'Here are you can put description of Item #4', UNIX_TIMESTAMP()+3, '0'),
('Item #5', 'Here are you can put description of Item #5', UNIX_TIMESTAMP()+4, '0');

CREATE TABLE IF NOT EXISTS `s163_items_cmts` (
  `c_id` int(11) NOT NULL AUTO_INCREMENT ,
  `c_item_id` int(12) NOT NULL default '0',
  `c_ip` varchar(20) default NULL,
  `c_name` varchar(64) default '',
  `c_text` text NOT NULL ,
  `c_when` int(11) NOT NULL default '0',
  PRIMARY KEY (`c_id`),
  KEY `c_item_id` (`c_item_id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8;
</pre><p>This is simple tables: first for records of items, second one &#8211; for comments</p><h3>Step 2. PHP</h3><p>Here are source code of our main file:</p><h4>index.php</h4><pre class="brush:php">
&lt;?php
// disabling possible warnings
if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;)  == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE); 

require_once('classes/CMySQL.php'); // including service class to work with database

$sCode = '';
$iItemId = (int)$_GET['id'];
if ($iItemId) { // View item output
    $aItemInfo = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `s163_items` WHERE `id` = '{$iItemId}'&quot;); // getting info about item from database
    $sCode .= '&lt;h1&gt;'.$aItemInfo['title'].'&lt;/h1&gt;';
    $sCode .= '&lt;h3&gt;'.date('F j, Y', $aItemInfo['when']).'&lt;/h3&gt;';
    $sCode .= '&lt;h2&gt;Description:&lt;/h2&gt;';
    $sCode .= '&lt;h3&gt;'.$aItemInfo['description'].'&lt;/h3&gt;';
    $sCode .= '&lt;h3&gt;&lt;a href=&quot;'.$_SERVER['PHP_SELF'].'&quot;&gt;back&lt;/a&gt;&lt;/h3&gt;';

    // drawing last 5 comments
    $sComments = '';
    $aComments = $GLOBALS['MySQL']-&gt;getAll(&quot;SELECT * FROM `s163_items_cmts` WHERE `c_item_id` = '{$iItemId}' ORDER BY `c_when` DESC LIMIT 5&quot;);
    foreach ($aComments as $i =&gt; $aCmtsInfo) {
        $sWhen = date('F j, Y H:i', $aCmtsInfo['c_when']);
        $sComments .= &lt;&lt;&lt;EOF
&lt;div class=&quot;comment&quot; id=&quot;{$aCmtsInfo['c_id']}&quot;&gt;
    &lt;p&gt;Comment from {$aCmtsInfo['c_name']} &lt;span&gt;({$sWhen})&lt;/span&gt;:&lt;/p&gt;
    &lt;p&gt;{$aCmtsInfo['c_text']}&lt;/p&gt;
&lt;/div&gt;
EOF;
    }

    ob_start();
    ?&gt;
    &lt;div class=&quot;container&quot; id=&quot;comments&quot;&gt;
        &lt;h2&gt;Comments&lt;/h2&gt;
        &lt;script type=&quot;text/javascript&quot;&gt;
        function submitComment(e) {
            var sName = $('#name').val();
            var sText = $('#text').val();

            if (sName &amp;&amp; sText) {
                $.post('comment.php', { name: sName, text: sText, id: &lt;?= $iItemId ?&gt; },
                    function(data){
                        if (data != '1') {
                          $('#comments_list').fadeOut(1000, function () {
                            $(this).html(data);
                            $(this).fadeIn(1000);
                          });
                        } else {
                          $('#comments_warning2').fadeIn(1000, function () {
                            $(this).fadeOut(1000);
                          });
                        }
                    }
                );
            } else {
              $('#comments_warning1').fadeIn(1000, function () {
                $(this).fadeOut(1000);
              });
            }
        };
        &lt;/script&gt;

        &lt;div id=&quot;comments_warning1&quot; style=&quot;display:none&quot;&gt;Don`t forget to fill both fields (Name and Comment)&lt;/div&gt;
        &lt;div id=&quot;comments_warning2&quot; style=&quot;display:none&quot;&gt;You can post no more than one comment every 10 minutes (spam protection)&lt;/div&gt;
        &lt;form onsubmit=&quot;submitComment(this); return false;&quot;&gt;
            &lt;table&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&lt;label&gt;Your name: &lt;/label&gt;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;&quot; title=&quot;Please enter your name&quot; id=&quot;name&quot; /&gt;&lt;/td&gt;&lt;/tr&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&lt;label&gt;Comment: &lt;/label&gt;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;&lt;textarea name=&quot;text&quot; id=&quot;text&quot;&gt;&lt;/textarea&gt;&lt;/td&gt;&lt;/tr&gt;
                &lt;tr&gt;&lt;td class=&quot;label&quot;&gt;&amp;nbsp;&lt;/td&gt;&lt;td class=&quot;field&quot;&gt;&lt;input type=&quot;submit&quot; value=&quot;Post comment&quot; /&gt;&lt;/td&gt;&lt;/tr&gt;
            &lt;/table&gt;
        &lt;/form&gt;
        &lt;div id=&quot;comments_list&quot;&gt;&lt;?= $sComments ?&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;?
    $sCommentsBlock = ob_get_clean();

} else {
    $sCode .= '&lt;h1&gt;List of items:&lt;/h1&gt;';

    $aItems = $GLOBALS['MySQL']-&gt;getAll(&quot;SELECT * FROM `s163_items` ORDER by `when` ASC&quot;); // taking info about all items from database
    foreach ($aItems as $i =&gt; $aItemInfo) {
        $sCode .= '&lt;h2&gt;&lt;a href=&quot;'.$_SERVER['PHP_SELF'].'?id='.$aItemInfo['id'].'&quot;&gt;'.$aItemInfo['title'].' item&lt;/a&gt;&lt;/h2&gt;';
    }
}

?&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;Creating own commenting system | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.5.2.min.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;?= $sCode ?&gt;
        &lt;/div&gt;
        &lt;?= $sCommentsBlock ?&gt;
        &lt;footer&gt;
            &lt;h2&gt;Creating own commenting system&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/how-to-create-own-commenting-system/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>By default &#8211; this script will draw list of items. Each item have own page. All easy &#8211; we will display item title, time of adding (&#8216;when&#8217; field), description, and, most important &#8211; our new Comments block. This block contain form of adding new comments, and also will load us last 5 comments. I added my comments in most of places for better understanding. Ok, next PHP file is:</p><h4>comment.php</h4><pre class="brush:php">
&lt;?php
// disabling possible warnings
if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;)  == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE); 

require_once('classes/CMySQL.php'); // including service class to work with database

$iItemId = (int)$_POST['id']; // obtaining necessary information
$sIp = getVisitorIP();
$sName = $GLOBALS['MySQL']-&gt;escape(strip_tags($_POST['name']));
$sText = $GLOBALS['MySQL']-&gt;escape(strip_tags($_POST['text']));

if ($sName &amp;&amp; $sText) {
    // checking - are you posted any comment recently or not?
    $iOldId = $GLOBALS['MySQL']-&gt;getOne(&quot;SELECT `c_item_id` FROM `s163_items_cmts` WHERE `c_item_id` = '{$iItemId}' AND `c_ip` = '{$sIp}' AND `c_when` &gt;= UNIX_TIMESTAMP() - 600 LIMIT 1&quot;);
    if (! $iOldId) {
        // if all fine - allow to add comment
        $GLOBALS['MySQL']-&gt;res(&quot;INSERT INTO `s163_items_cmts` SET `c_item_id` = '{$iItemId}', `c_ip` = '{$sIp}', `c_when` = UNIX_TIMESTAMP(), `c_name` = '{$sName}', `c_text` = '{$sText}'&quot;);
        $GLOBALS['MySQL']-&gt;res(&quot;UPDATE `s163_items` SET `comments_count` = `comments_count` + 1 WHERE `id` = '{$iItemId}'&quot;);

        // and printing out last 5 comments
        $sOut = '';
        $aComments = $GLOBALS['MySQL']-&gt;getAll(&quot;SELECT * FROM `s163_items_cmts` WHERE `c_item_id` = '{$iItemId}' ORDER BY `c_when` DESC LIMIT 5&quot;);
        foreach ($aComments as $i =&gt; $aCmtsInfo) {
            $sWhen = date('F j, Y H:i', $aCmtsInfo['c_when']);
            $sOut .= &lt;&lt;&lt;EOF
&lt;div class=&quot;comment&quot; id=&quot;{$aCmtsInfo['c_id']}&quot;&gt;
    &lt;p&gt;Comment from {$aCmtsInfo['c_name']} &lt;span&gt;({$sWhen})&lt;/span&gt;:&lt;/p&gt;
    &lt;p&gt;{$aCmtsInfo['c_text']}&lt;/p&gt;
&lt;/div&gt;
EOF;
        }

        echo $sOut;
        exit;
    }
}
echo 1;
exit;

function getVisitorIP() {
    $ip = &quot;0.0.0.0&quot;;
    if( ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) &amp;&amp; ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif( ( isset( $_SERVER['HTTP_CLIENT_IP'])) &amp;&amp; (!empty($_SERVER['HTTP_CLIENT_IP'] ) ) ) {
        $ip = explode(&quot;.&quot;,$_SERVER['HTTP_CLIENT_IP']);
        $ip = $ip[3].&quot;.&quot;.$ip[2].&quot;.&quot;.$ip[1].&quot;.&quot;.$ip[0];
    } elseif((!isset( $_SERVER['HTTP_X_FORWARDED_FOR'])) || (empty($_SERVER['HTTP_X_FORWARDED_FOR']))) {
        if ((!isset( $_SERVER['HTTP_CLIENT_IP'])) &amp;&amp; (empty($_SERVER['HTTP_CLIENT_IP']))) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    }
    return $ip;
}

?&gt;
</pre><p>This file will accept POSTed comments and save them into database. In our project we have another one PHP file:</p><h4>classes/CMySQL.php</h4><p>This is service class to work with database prepared by me. This is nice class which you can use too. Database connection details located in this class in few variables, sure that you will able to configure this to your database. I don`t will publish its sources &#8211; this is not necessary for now. Available in package.</p><h3>Step 3. JS</h3><h4>js/jquery-1.5.2.min.js</h4><p>This is just jQuery library. Available in package.</p><h3>Step 4. CSS</h3><p>Now &#8211; all used CSS styles:</p><h4>css/main.css</h4><pre class="brush:js">
*{
    margin:0;
    padding:0;
}

body {
    background-repeat:no-repeat;
    background-color:#bababa;
    background-image: -webkit-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -moz-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -o-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
    min-height:600px;
}

footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}

footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}

footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}

footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

.container {
    border:3px #111 solid;
    color:#000;
    margin:20px auto;
    padding:15px;
    position:relative;
    text-align:center;
    width:500px;

    border-radius:15px;
    -moz-border-radius:15px;
    -webkit-border-radius:15px;
}

#comments form {
    background-color: rgba(255, 255, 255, 0.4);
    margin:10px 0;
    padding:10px;
    text-align:left;
}

#comments table td.label {
    color: #000;
    font-size: 13px;
    padding-right: 3px;
    text-align: right;
    width: 105px;
}

#comments table label {
    color: #000;
    font-size: 16px;
    font-weight: normal;
    vertical-align: middle;
}

#comments table td.field input, #comments table td.field textarea {
    border: 1px solid #96A6C5;
    font-family: Verdana,Arial,sans-serif;
    font-size: 16px;
    margin-top: 2px;
    padding: 6px;
    width: 250px;
}

#comments_list {
    background-color: rgba(255, 255, 255, 0.4);
    margin:10px 0;
    padding:10px;
    text-align:left;
}

#comments_list .comment {
    border-top:1px solid #000;
    padding:10px 0;
}

#comments_list .comment:first-child {
    border-top-width:0px;
}

#comments_list .comment span {
    font-size:11px;
}
</pre><hr
/><h5 style="text-align: center;"><strong><a
title="How to create own commenting system - demo 163" href="http://www.script-tutorials.com/demos/163/index.php" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="How to create own commenting system - package" href="http://www.script-tutorials.com/demos/163/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>Today we prepared great commenting system for your website. Sure that this material will useful for your own projects. Good luck in your work!</p><div
class="shr-publisher-1109"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-create-own-voting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/155/thumb.png" alt="How to Create Your Own 5 Stars Voting System" /> <br
/> How to Create Your Own 5 Stars Voting System</a></li><li> <a
href="http://www.script-tutorials.com/php-guestbook/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/178/thumb.png" alt="Creating a Diary style PHP Guestbook" /> <br
/> Creating a Diary style PHP Guestbook</a></li><li> <a
href="http://www.script-tutorials.com/creating-own-ajax-poll-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/183/thumb.png" alt="Creating Your Own Ajax Poll System" /> <br
/> Creating Your Own Ajax Poll System</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/how-to-create-own-commenting-system/feed/</wfw:commentRss> <slash:comments>8</slash:comments> </item> <item><title>Autocomplete with PHP, jQuery, MySQL and XML</title><link>http://www.script-tutorials.com/autocomplete-with-php-jquery-mysql-and-xml/</link> <comments>http://www.script-tutorials.com/autocomplete-with-php-jquery-mysql-and-xml/#comments</comments> <pubDate>Tue, 11 Oct 2011 16:35:31 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[autocomplete]]></category> <category><![CDATA[how-to]]></category> <category><![CDATA[js]]></category> <category><![CDATA[tutorial]]></category> <category><![CDATA[xml]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1094</guid> <description><![CDATA[Autocomplete with PHP, jQuery, MySQL and XML Today I have new article for PHP. I will tell you about implementation autocomplete for your sites. Data can be located in different sources &#8211; directly in the JS code, in the database, and even in the XML file. Live Demo download in package Now &#8211; download the [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/easily-interact-between-server-and-client-using-these-jquery-with-ajax-snippets/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="Easily Interact between Server and Client using these jQuery with Ajax Snippets" /> Easily Interact between Server and Client using these jQuery with Ajax Snippets</a></li><li> <a
href="http://www.script-tutorials.com/php-guestbook/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/178/thumb.png" alt="Creating a Diary style PHP Guestbook" /> Creating a Diary style PHP Guestbook</a></li><li> <a
href="http://www.script-tutorials.com/how-to-create-own-commenting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/163/thumb.png" alt="Creating Your Own Commenting System from Scratch" /> Creating Your Own Commenting System from Scratch</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="Autocomplete with PHP, jQuery, MySQL and XML" alt="Autocomplete with PHP, jQuery, MySQL and XML" src="http://www.script-tutorials.com/demos/160/thumb.png"></div><p><strong>Autocomplete with PHP, jQuery, MySQL and XML</strong><br
/> <br
/>Today I have new article for PHP. I will tell you about implementation autocomplete for your sites. Data can be located in different sources &#8211; directly in the JS code, in the database, and even in the XML file.<br
/> <span
id="more-1094"></span></p><h5 style="text-align: center;"><strong><a
title="Autocomplete with PHP - demo 160" href="http://www.script-tutorials.com/demos/160/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Autocomplete with PHP - package" href="http://www.script-tutorials.com/demos/160/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. HTML</h3><p>Here are HTML layout for our autocomplete example page:</p><h4>index.html</h4><pre class="brush:php">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;Autocomplete with PHP, jQuery, MySQL and XML | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/jquery.autocomplete.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.5.2.min.js&quot;&gt;&lt;/script&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery.autocomplete.pack.js&quot;&gt;&lt;/script&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/script.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;form action=&quot;#&quot;&gt;
                &lt;p&gt;&lt;label&gt;Your month:&lt;/label&gt; &lt;input id=&quot;month&quot; type=&quot;text&quot; autocomplete=&quot;off&quot;&gt;&lt;/p&gt;
                &lt;p&gt;&lt;label&gt;Your year:&lt;/label&gt; &lt;input id=&quot;year&quot; type=&quot;text&quot; autocomplete=&quot;off&quot;&gt;&lt;/p&gt;
                &lt;p&gt;&lt;label&gt;Your country:&lt;/label&gt; &lt;input id=&quot;country&quot; type=&quot;text&quot; autocomplete=&quot;off&quot;&gt;&lt;/p&gt;
            &lt;/form&gt;
        &lt;/div&gt;
        &lt;footer&gt;
            &lt;h2&gt;Autocomplete with PHP, jQuery, MySQL and XML&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/autocomplete-with-php-jquery-mysql-and-xml/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><h3>Step 2. CSS</h3><p>Now, lets define all used styles:</p><h4>css/main.css</h4><pre class="brush:css">
*{
    margin:0;
    padding:0;
}

body {
    background-repeat:no-repeat;
    background-color:#bababa;
    background-image: -webkit-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -moz-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -o-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
    min-height:600px;
}

footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}

footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}

footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}

footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

.container {
    border:3px #111 solid;
    color:#000;
    margin:20px auto;
    padding:20px;
    position:relative;
    text-align:center;
    width:300px;

    border-radius:15px;
    -moz-border-radius:15px;
    -webkit-border-radius:15px;
}

.ac_results  {
    border: solid 1px #E5E5E5;
    color:#000;

    border-radius:0 0 5px 5px;
    -moz-border-radius:0 0 5px 5px;
    -webkit-border-radius:0 0 5px 5px;
}
.ac_over {
    background-color:#444;
}

form p {
    margin-bottom:5px;
    text-align:right;
}

form input {
    background-color: #FFFFFF;
    background: -moz-linear-gradient(top, #FFFFFF, #EEEEEE 1px, #FFFFFF 25px);
    background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #EEEEEE), to(#FFFFFF));
    border: solid 1px #E5E5E5;
    font-size:14px;
    outline: 0;
    padding: 9px;
    width: 180px;

    border-radius:5px;
    -moz-border-radius:5px;
    -webkit-border-radius:5px;

    box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
    -moz-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
    -webkit-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
}

form  input:hover, form  input:focus {
    border-color: #C9C9C9;

    box-shadow: rgba(0,0,0, 0.5) 0px 0px 8px;
    -moz-box-shadow: rgba(0,0,0, 0.5) 0px 0px 8px;
    -webkit-box-shadow: rgba(0,0,0, 0.5) 0px 0px 8px;
}
</pre><p>In our package you can find few more files:</p><h4>css/jquery.autocomplete.css + css/indicator.gif</h4><p>Both files I got from autocomplete jquery package (this is default files &#8211; don`t need to re-publish it in our article)</p><h3>Step 3. Javascript</h3><p>Its time to prepare JS:</p><h4>js/script.js</h4><pre class="brush:js">
$(function(){

    $('#month').autocomplete(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], {
        width: 200,
        max: 3
    });

    $('#year').autocomplete('data.php?mode=xml', {
        width: 200,
        max: 5
    });

    $('#country').autocomplete('data.php?mode=sql', {
        width: 200,
        max: 5
    });

});
</pre><p>As you can see &#8211; very easy syntax of using Autocomplete. In first case I hardcoded possible values directly in JS code. Second and third cases &#8211; through PHP file (using different way of obtaining data &#8211; XML and SQL). In package you can find two another JS files:</p><h4>js/jquery-1.5.2.min.js + js/jquery.autocomplete.pack.js</h4><p>This is jQuery library itself plus Autocomplete plugin</p><h3>Step 4. SQL</h3><p>Now, lets prepare our database &#8211; lets add 1 new table:</p><pre class="brush:sql">
CREATE TABLE `s85_countries` (
  `country_code` varchar(2) NOT NULL,
  `country_name` varchar(255) NOT NULL,
  PRIMARY KEY  (`country_code`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

INSERT INTO `s85_countries` (`country_code`, `country_name`) VALUES
('AR', 'Argentina'),
('AU', 'Australia'),
('BR', 'Brazil'),
('CA', 'Canada'),
('CN', 'China'),
('IN', 'India'),
('KZ', 'Kazakhstan'),
('RU', 'Russia'),
('SD', 'Sudan'),
('US', 'United States');
</pre><p>This small table contain several records &#8211; list of countries. I took that SQL code from one of our old tutorials.</p><h3>Step 5. PHP</h3><p>This step most important &#8211; now you will see how we returning data for Autocomplete:</p><h4>data.php</h4><pre class="brush:php">
&lt;?php

if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;)  == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE); 

require_once('classes/CMySQL.php');

$sParam = $GLOBALS['MySQL']-&gt;escape($_GET['q']); // escaping external data
if (! $sParam) exit;

switch ($_GET['mode']) {
    case 'xml': // using XML file as source of data
        $aValues = $aIndexes = array();
        $sFileData = file_get_contents('data.xml'); // reading file content
        $oXmlParser = xml_parser_create('UTF-8');
        xml_parse_into_struct($oXmlParser, $sFileData, $aValues, $aIndexes);
        xml_parser_free( $oXmlParser );

        $aTagIndexes = $aIndexes['ITEM'];
        if (count($aTagIndexes) &lt;= 0) exit;
        foreach($aTagIndexes as $iTagIndex) {
            $sValue = $aValues[$iTagIndex]['value'];
            if (strpos($sValue, $sParam) !== false) {
                echo $sValue . &quot;\n&quot;;
            }
        }
        break;
    case 'sql': // using database as source of data
        $sRequest = &quot;SELECT `country_name` FROM `s85_countries` WHERE `country_name` LIKE '%{$sParam}%' ORDER BY `country_code`&quot;;
        $aItemInfo = $GLOBALS['MySQL']-&gt;getAll($sRequest);
        foreach ($aItemInfo as $aValues) {
            echo $aValues['country_name'] . &quot;\n&quot;;
        }
        break;
}
</pre><p>We filter the resulting data by incoming parameter $_GET['q'] from the active text field (where we started typing something). The result &#8211; the script gives all matching records. Another one file which we using (as always):</p><h4>classes/CMySQL.php</h4><p>This is our usual class file to work with database (pretty comfortable). In its constructor you will able to set your own database configuration:</p><pre class="brush:php">
    $this->sDbName = '_DATABASE_NAME_';
    $this->sDbUser = '_DATABASE_USERNAME_';
    $this->sDbPass = '_DATABASE_USERPASS_';
</pre><h3>Step 6. XML</h3><p>Here are content of our XML data file:</p><h4>data.xml</h4><pre class="brush:xml">
<?xml version="1.0"?>
&lt;items&gt;
    &lt;item&gt;1991&lt;/item&gt;
    &lt;item&gt;1990&lt;/item&gt;
    &lt;item&gt;1991&lt;/item&gt;
    &lt;item&gt;1992&lt;/item&gt;
    &lt;item&gt;1993&lt;/item&gt;
    &lt;item&gt;1994&lt;/item&gt;
    &lt;item&gt;1995&lt;/item&gt;
    &lt;item&gt;1996&lt;/item&gt;
    &lt;item&gt;1997&lt;/item&gt;
    &lt;item&gt;1998&lt;/item&gt;
    &lt;item&gt;1999&lt;/item&gt;
    &lt;item&gt;2000&lt;/item&gt;
    &lt;item&gt;2001&lt;/item&gt;
    &lt;item&gt;2002&lt;/item&gt;
    &lt;item&gt;2003&lt;/item&gt;
    &lt;item&gt;2004&lt;/item&gt;
    &lt;item&gt;2005&lt;/item&gt;
    &lt;item&gt;2006&lt;/item&gt;
    &lt;item&gt;2007&lt;/item&gt;
    &lt;item&gt;2008&lt;/item&gt;
    &lt;item&gt;2009&lt;/item&gt;
    &lt;item&gt;2010&lt;/item&gt;
    &lt;item&gt;2011&lt;/item&gt;
    &lt;item&gt;2012&lt;/item&gt;
    &lt;item&gt;2013&lt;/item&gt;
    &lt;item&gt;2014&lt;/item&gt;
    &lt;item&gt;2015&lt;/item&gt;
&lt;/items&gt;
</pre><hr
/><h5 style="text-align: center;"><strong><a
title="Autocomplete with PHP - demo 160" href="http://www.script-tutorials.com/demos/160/index.html" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="Autocomplete with PHP - package" href="http://www.script-tutorials.com/demos/160/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>As a result, we see the pattern is obvious &#8211; the fastest way &#8211; when all possible values are hardcoded in JS. In case of XML and SQL &#8211; XML is clearly faster. Just because we even don`t need touch our slow database. I hope that you got interesting lesson for today. Good luck in your work!</p><div
class="shr-publisher-1094"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/easily-interact-between-server-and-client-using-these-jquery-with-ajax-snippets/" rel="bookmark"> <img
src="/ssimages/no_image.gif" alt="Easily Interact between Server and Client using these jQuery with Ajax Snippets" /> <br
/> Easily Interact between Server and Client using these jQuery with Ajax Snippets</a></li><li> <a
href="http://www.script-tutorials.com/php-guestbook/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/178/thumb.png" alt="Creating a Diary style PHP Guestbook" /> <br
/> Creating a Diary style PHP Guestbook</a></li><li> <a
href="http://www.script-tutorials.com/how-to-create-own-commenting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/163/thumb.png" alt="Creating Your Own Commenting System from Scratch" /> <br
/> Creating Your Own Commenting System from Scratch</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/autocomplete-with-php-jquery-mysql-and-xml/feed/</wfw:commentRss> <slash:comments>21</slash:comments> </item> <item><title>How to Create Your Own 5 Stars Voting System</title><link>http://www.script-tutorials.com/how-to-create-own-voting-system/</link> <comments>http://www.script-tutorials.com/how-to-create-own-voting-system/#comments</comments> <pubDate>Tue, 04 Oct 2011 17:20:52 +0000</pubDate> <dc:creator>admin</dc:creator> <category><![CDATA[HTML/CSS]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[creating]]></category> <category><![CDATA[css]]></category> <category><![CDATA[five stars]]></category> <category><![CDATA[html]]></category> <category><![CDATA[system]]></category> <category><![CDATA[tutorial]]></category> <category><![CDATA[voting]]></category><guid
isPermaLink="false">http://www.script-tutorials.com/?p=1072</guid> <description><![CDATA[How to create own voting system Today I prepared very interesting article &#8211; today I will tell you how you can create own voting system for your items (any units at your website) with PHP. I prepared two SQL tables: first table will keep our demo items. It contain several fields: title, description, time of [...]<div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-create-own-commenting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/163/thumb.png" alt="Creating Your Own Commenting System from Scratch" /> Creating Your Own Commenting System from Scratch</a></li><li> <a
href="http://www.script-tutorials.com/creating-own-ajax-poll-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/183/thumb.png" alt="Creating Your Own Ajax Poll System" /> Creating Your Own Ajax Poll System</a></li><li> <a
href="http://www.script-tutorials.com/how-to-create-photo-album-with-tn3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/146/thumb.png" alt="How to Create a Fantastic Photo Album with TN3" /> How to Create a Fantastic Photo Album with TN3</a></li></ol></div>]]></description> <content:encoded><![CDATA[<div
class="thumb"><img
width="128" height="128" class="aligncenter" title="How to create own voting system" alt="How to create own voting system" src="http://www.script-tutorials.com/demos/155/thumb.png"></div><p><strong>How to create own voting system</strong><br
/> <br
/>Today I prepared very interesting article &#8211; today I will tell you how you can create own voting system for your items (any units at your website) with PHP. I prepared two SQL tables: first table will keep our demo items. It contain several fields: title, description, time of adding, rate value and count of rates. Another table will keep records of voting (track). Of course &#8211; we will use jQuery too (for better behavior of interface). One of features will restriction to vote twice from one IP during 1 week!<br
/> <span
id="more-1072"></span></p><h5 style="text-align: center;"><strong><a
title="How to create own voting system - demo 155" href="http://www.script-tutorials.com/demos/155/index.php" target="_blank">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="How to create own voting system - package" href="http://www.script-tutorials.com/demos/155/source.zip" target="_blank">download in package</a></strong></h5><hr
/><p>Now &#8211; download the source files and lets start coding !</p><hr
/><h3>Step 1. SQL</h3><p>We will need to add 2 tables into our database:</p><pre class="brush:php">
CREATE TABLE IF NOT EXISTS `s155_items` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `title` varchar(255) default '',
  `description` text NOT NULL,
  `when` int(11) NOT NULL default '0',
  `rate` float NOT NULL,
  `rate_count` int(11) unsigned NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `s155_items` (`title`, `description`, `when`, `rate`, `rate_count`) VALUES
('Item #1', 'Here are you can put description of Item #1', UNIX_TIMESTAMP(), '0', '0'),
('Item #2', 'Here are you can put description of Item #2', UNIX_TIMESTAMP()+1, '0', '0'),
('Item #3', 'Here are you can put description of Item #3', UNIX_TIMESTAMP()+2, '0', '0'),
('Item #4', 'Here are you can put description of Item #4', UNIX_TIMESTAMP()+3, '0', '0'),
('Item #5', 'Here are you can put description of Item #5', UNIX_TIMESTAMP()+4, '0', '0');

CREATE TABLE `s155_items_vote_track` (
  `item_id` int(11) unsigned NOT NULL default '0',
  `ip` varchar(20) default NULL,
  `date` datetime default NULL,
  KEY `med_ip` (`ip`,`item_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</pre><p>This is simple tables: first for records of items, second one &#8211; voting tracker</p><h3>Step 2. PHP</h3><p>Here are source code of our main file:</p><h4>index.php</h4><pre class="brush:php">
&lt;?php

if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;)  == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE); 

require_once('classes/CMySQL.php'); // including service class to work with database

$sCode = '';
$iItemId = (int)$_GET['id'];
if ($iItemId) { // View item output
    $aItemInfo = $GLOBALS['MySQL']-&gt;getRow(&quot;SELECT * FROM `s155_items` WHERE `id` = '{$iItemId}'&quot;); // getting info about item from database
    $sCode .= '&lt;h1&gt;'.$aItemInfo['title'].'&lt;/h1&gt;';
    $sCode .= '&lt;h3&gt;'.date('F j, Y', $aItemInfo['when']).'&lt;/h3&gt;';
    $sCode .= '&lt;h2&gt;Description:&lt;/h2&gt;';
    $sCode .= '&lt;h3&gt;'.$aItemInfo['description'].'&lt;/h3&gt;';

    // draw voting element
    $iIconSize = 64;
    $iMax = 5;
    $iRate = $aItemInfo['rate'];
    $iRateCnt = $aItemInfo['rate_count'];
    $fRateAvg = ($iRate &amp;&amp; $iRateCnt) ? $iRate / $iRateCnt : 0;
    $iWidth = $iIconSize*$iMax;
    $iActiveWidth = round($fRateAvg*($iMax ? $iWidth/$iMax : 0));

    $sVot = '';
    for ($i=1 ; $i&lt;=$iMax ; $i++) {
        $sVot .= '&lt;a href=&quot;#&quot; id=&quot;'.$i.'&quot;&gt;&lt;img class=&quot;votes_button&quot; src=&quot;images/empty.gif&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;';
    }

    $sVoting = &lt;&lt;&lt;EOS
&lt;div class=&quot;votes_main&quot;&gt;
    &lt;div class=&quot;votes_gray&quot; style=&quot;width:{$iWidth}px;&quot;&gt;
        &lt;div class=&quot;votes_buttons&quot; id=&quot;{$iItemId}&quot; cnt=&quot;{$iRateCnt}&quot; val=&quot;{$fRateAvg}&quot;&gt;
            {$sVot}
        &lt;/div&gt;
        &lt;div class=&quot;votes_active&quot; style=&quot;width:{$iActiveWidth}px;&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;span&gt;&lt;b&gt;{$iRateCnt}&lt;/b&gt; votes&lt;/span&gt;
&lt;/div&gt;
EOS;

    $sCode .= $sVoting;
    $sCode .= '&lt;h3&gt;&lt;a href=&quot;'.$_SERVER['PHP_SELF'].'&quot;&gt;back&lt;/a&gt;&lt;/h3&gt;';
} else {
    $sCode .= '&lt;h1&gt;List of items:&lt;/h1&gt;';

    $aItems = $GLOBALS['MySQL']-&gt;getAll(&quot;SELECT * FROM `s155_items` ORDER by `when` ASC&quot;); // taking info about all items from database
    foreach ($aItems as $i =&gt; $aItemInfo) {
        $sCode .= '&lt;h2&gt;&lt;a href=&quot;'.$_SERVER['PHP_SELF'].'?id='.$aItemInfo['id'].'&quot;&gt;'.$aItemInfo['title'].' item&lt;/a&gt;&lt;/h2&gt;';
    }
}

?&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot; &gt;
    &lt;head&gt;
        &lt;meta charset=&quot;utf-8&quot; /&gt;
        &lt;title&gt;Creating own rate system | Script Tutorials&lt;/title&gt;

        &lt;link href=&quot;css/main.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.5.2.min.js&quot;&gt;&lt;/script&gt;
        &lt;script type=&quot;text/javascript&quot; src=&quot;js/script.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class=&quot;container&quot;&gt;
            &lt;?= $sCode ?&gt;
        &lt;/div&gt;
        &lt;footer&gt;
            &lt;h2&gt;Creating own rate system&lt;/h2&gt;
            &lt;a href=&quot;http://www.script-tutorials.com/how-to-create-own-voting-system/&quot; class=&quot;stuts&quot;&gt;Back to original tutorial on &lt;span&gt;Script Tutorials&lt;/span&gt;&lt;/a&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>This script will draw us list of items by default. And, when we will clicking to any item &#8211; this will link like: index.php?id=1 &#8211; it will drawing item page. I decided not make something difficult &#8211; I prepared just simple page. We will display item title, time of adding (&#8216;when&#8217; field), description, and, most important &#8211; our Voting element. This will looks like stars (5 stars). And we can select &#8211; how many stars we will give for our vote (from 1 till 5). I added my comments in most of places for better understanding. Ok, next PHP file is:</p><h4>vote.php</h4><pre class="brush:php">
&lt;?php

if (version_compare(phpversion(), &quot;5.3.0&quot;, &quot;&gt;=&quot;)  == 1)
  error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_DEPRECATED);
else
  error_reporting(E_ALL &amp; ~E_NOTICE); 

require_once('classes/CMySQL.php');

$iItemId = (int)$_POST['id'];
$iVote = (int)$_POST['vote'];
$sIp = getVisitorIP();

$iOldId = $GLOBALS['MySQL']-&gt;getOne(&quot;SELECT `item_id` FROM `s155_items_vote_track` WHERE `item_id` = '{$iItemId}' AND `ip` = '{$sIp}' AND (`date` &gt;= NOW() - INTERVAL 7 DAY) LIMIT 1&quot;);
if (! $iOldId) {
    $GLOBALS['MySQL']-&gt;res(&quot;INSERT INTO `s155_items_vote_track` SET `item_id` = '{$iItemId}', `ip` = '{$sIp}', `date` = NOW()&quot;);
    $GLOBALS['MySQL']-&gt;res(&quot;UPDATE `s155_items` SET `rate` = `rate` + {$iVote}, `rate_count` = `rate_count` + 1 WHERE `id` = '{$iItemId}'&quot;);
    echo 1;
}

function getVisitorIP() {
    $ip = &quot;0.0.0.0&quot;;
    if( ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) &amp;&amp; ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif( ( isset( $_SERVER['HTTP_CLIENT_IP'])) &amp;&amp; (!empty($_SERVER['HTTP_CLIENT_IP'] ) ) ) {
        $ip = explode(&quot;.&quot;,$_SERVER['HTTP_CLIENT_IP']);
        $ip = $ip[3].&quot;.&quot;.$ip[2].&quot;.&quot;.$ip[1].&quot;.&quot;.$ip[0];
    } elseif((!isset( $_SERVER['HTTP_X_FORWARDED_FOR'])) || (empty($_SERVER['HTTP_X_FORWARDED_FOR']))) {
        if ((!isset( $_SERVER['HTTP_CLIENT_IP'])) &amp;&amp; (empty($_SERVER['HTTP_CLIENT_IP']))) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    }
    return $ip;
}

?&gt;
</pre><p>This file we will using to accept visitors votes and saving its into database. In our project we have another one PHP file:</p><h4>classes/CMySQL.php</h4><p>This is service class to work with database prepared by me. This is nice class which you can use too. Database connection details located in this class in few variables, sure that you will able to configure this to your database. I don`t will publish its sources &#8211; this is not necessary for now. Available in package.</p><h3>Step 3. JS</h3><p>Here are small javascript code which we will using for changing voting element styles on mouse hover. And &#8211; for sending data in case of submitting our vote.</p><h4>js/script.js</h4><pre class="brush:javascript">
$(function(){
    var width = 0;

    $('.votes_buttons a').hover(
        function () {
            width = $(this).attr('id') * 64;
            $('.votes_active').width(width + 'px');
        },
        function () {
            width = $(this).parent().attr('val') * 64;
            $('.votes_active').width(width + 'px');
        }
    );

    $('.votes_buttons a').click(function () {
        var idVal = $(this).parent().attr('id');
        var iCnt = $(this).parent().attr('cnt');
        var voteVal = $(this).attr('id');
        var obj = $(this);
        var iSelWidth = voteVal * 64;

        $.post('vote.php', { id: idVal, vote: voteVal },
            function(data){
                if (data == 1) {
                    width = iSelWidth;
                    $('.votes_active').width(iSelWidth + 'px');
                    iCnt = parseInt(iCnt) + 1;
                    $('.votes_main span b').text(iCnt);
                    $('.votes_buttons').attr('val', voteVal);
                }
            }
        );
    });
});
</pre><h4>js/jquery-1.5.2.min.js</h4><p>This is just jQuery library. Available in package.</p><h3>Step 4. CSS</h3><p>Now &#8211; all used CSS styles:</p><h4>css/main.css</h4><pre class="brush:js">
/* general styles */
*{
    margin:0;
    padding:0;
}

body {
    background-repeat:no-repeat;
    background-color:#bababa;
    background-image: -webkit-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -moz-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: -o-radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    background-image: radial-gradient(600px 200px, circle, #eee, #bababa 40%);
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
    min-height:600px;
}

footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}

footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}

footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}

footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}

.container {
    border:3px #111 solid;
    color:#000;
    margin:20px auto;
    padding:15px;
    position:relative;
    text-align:center;
    width:500px;

    border-radius:15px;
    -moz-border-radius:15px;
    -webkit-border-radius:15px;
}

.votes_main {
    margin: 10px auto;
    overflow: hidden;
    width: 450px;
}
.votes_gray {
    background-image: url(&quot;../images/star_gray.png&quot;);
    float: left;
    height: 64px;
    position: relative;
}
.votes_active {
    background-image: url(&quot;../images/star.png&quot;);
    height: 64px;
    left: 0;
    position: absolute;
    top: 0;
    z-index: 1;
}
.votes_buttons {
    left: 0;
    position: absolute;
    top: 0;
    z-index: 2;
}
.votes_button {
    border: medium none;
    height: 64px;
    margin: 0;
    padding: 0;
    width: 64px;
}
.votes_main span {
    color: #333333;
    display: block;
    float: left;
    font-weight: bold;
    font-size: 18px;
    line-height: 64px;
    margin-left: 10px;
}
</pre><h3>Step 5. Images</h3><p>Last step &#8211; used images:</p><pre class="sources">
<img alt="star.png" src="http://www.script-tutorials.com/demos/155/images/star.png" />
<img alt="star_gray.png" src="http://www.script-tutorials.com/demos/155/images/star_gray.png" />
</pre><hr
/><h5 style="text-align: center;"><strong><a
title="How to create own voting system - demo 155" href="http://www.script-tutorials.com/demos/155/index.php" target="_blank" rel="nofollow">Live Demo</a></strong></h5><h5 style="text-align: center;"><strong><a
title="How to create own voting system - package" href="http://www.script-tutorials.com/demos/155/source.zip" target="_blank" rel="nofollow">download in archive</a></strong></h5><hr
/><h3>Conclusion</h3><p>Today we prepared great voting system for your website. Sure that this material will useful for your own projects. Good luck in your work!</p><div
class="shr-publisher-1072"></div><div
id="main-related"><h4>Related Stuff You Will Love!</h4><ol
class="related-posts"><li> <a
href="http://www.script-tutorials.com/how-to-create-own-commenting-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/163/thumb.png" alt="Creating Your Own Commenting System from Scratch" /> <br
/> Creating Your Own Commenting System from Scratch</a></li><li> <a
href="http://www.script-tutorials.com/creating-own-ajax-poll-system/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/183/thumb.png" alt="Creating Your Own Ajax Poll System" /> <br
/> Creating Your Own Ajax Poll System</a></li><li> <a
href="http://www.script-tutorials.com/how-to-create-photo-album-with-tn3/" rel="bookmark"> <img
src="http://www.script-tutorials.com/demos/146/thumb.png" alt="How to Create a Fantastic Photo Album with TN3" /> <br
/> How to Create a Fantastic Photo Album with TN3</a></li></ol></div>]]></content:encoded> <wfw:commentRss>http://www.script-tutorials.com/how-to-create-own-voting-system/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: basic (User agent is rejected)
Database Caching using disk: basic

Served from: www.script-tutorials.com @ 2012-02-04 21:44:27 -->
