Getting Started with Redis, Chatting Application
Wall Script
Follow Me:
Sunday, January 05, 2014

Getting Started with Redis, Chatting Application

Most of my readers are expecting a better chatting system from 9lessons, I have been working with different technologies like Node, Socket.io and etc. Finally I found Redis, it is an open source advanced key-value database storage system, works like NoSQL database. Redis operations can be executed on the server side and reduce the client's workload. It is used for caches to speed up web applications

Getting Started with Redis, Chatting Application


Download Script     Live Demo

Setup

Ubuntu
git clone git://github.com/nicolasff/phpredis.git
# cd phpredis
# phpize
./configure
make
# sudo -s make install

Add Extension on php.ini
extension=redis.so

Copy extension files into php extensions folder
# cp /home/ubuntu/phpredis/modules/redis.so /opt/lampp/lib/php/extensions/no-debug-non-zts-20090626/redis.so

Mac
$ wget http://download.redis.io/releases/redis-2.8.3.tar.gz
$ tar xzf redis-2.8.3.tar.gz
$ cd redis-2.8.3
$ make

The binaries that are now compiled are available in the src directory. Run Redis with:
$ src/redis-server

Windows
Download unofficial version click here, go to bin directory then releases and extract redisbin.zip run redis-server.exe file

Download php_redis.dll copy into PHP extension folder.

Add Extension on php.ini
extension php_redis-2.1.3-5.3-ts.dll


Redis Sample Code
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$key="Key_Name"
$redis->set($key, 'Key Value');
echo $redis->get($key);
?>

I have tried a Chatting Application for demo use.

index.php
Contains JavaScript and PHP code.
<script src="js/jquery.1.9.1.min.js"></script>
<script src="js/jquery.timeago.js"></script>
<script src="js/jquery.livequery.js"></script>
<script src="js/jquery-linkify.min.js" ></script>
<script type="text/javascript">
//HTML encoding. 
function htmlEscape(str) {
return String(str).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

//Jquery ajax call. 
function ajax_data(typeMethod,url,dataString,success){
$.ajax({
type:typeMethod,
url:url,
data :dataString,
dataType:"json",
cache:false,
timeout:20000,
beforeSend :function(data) { },
success:function(data){
success.call(this, data);
},
error:function(data){
alert("Error In Connecting");
}
});
}

// Appending values in ol#update tag
function Action(json){
$("ol#update").empty();
var b="";
for (var i = 0, len = json.length; i < len; i++)
{
var msg=htmlEscape(json[i][2]);
var time=htmlEscape(json[i][1]);
var name=htmlEscape(json[i][0]);        
b='<li><b>'+name+': </b>'+msg+' - <a href="#" class="timeago" title="'+time+'"></a></li>';
$("ol#update").prepend(b);
}
$(".timeago").timeago();
}


// Inserting records into chat table
$(document).ready(function()
{
// Text to link
$("#update li").livequery(function()
{
$(this).linkify({
target: "_blank"
});
});

var user='<?php echo $user_sessions;?>';
// Requesting to chat_get.php every 2 seconds
if(user.length>0)
{
var auto_refresh = setInterval(function ()
{
var dataString = 'user='+ user;
ajax_data("POST","chat_get.php",dataString, function(data) {
Action(data);
});
}, 2000);
}

$('#post').click(function()
{
var content = $("#content").val();
var dataString = 'user='+ user + '&content=' + content;
if(boxval.length > 0)
{
ajax_data("POST","chat.php",dataString, function(data) {
Action(data);
});
$('#content').val('').focus();
}
return false;
});


});
</script>
// HTML Code
<ol id="update" > </ol>
<input type="text" name="content" id="content" autocomplete="off" maxlength="250"/>
<input type="submit" value="Post" id="post" />

$("#post").click(function(){}- post is the ID name of the submit input button. Using $("#content").val() calling input text value.


redis_config.php
Redis server configuration file.
<?php
$key="Key_Name"; // Redis Key Name
$redis = new Redis();
$redis->connect('127.0.0.1',6379);
?>

chat.php
Insert user update record into Redis key.
<?php
include 'redis_config.php';
include 'arrayToJSON.php';
if(isset($_POST['content']) && isset($_POST['user']) )
{
if($redis && !empty($_POST['content']) &&  !empty($_POST['user']))
{
$message=$_POST['content']; //Message
$user=$_POST['user']; //Username 
$time=date("c", time()); //Timestamp 
$redis->lpush($key, serialize(array($user,$time, $message)));
}
$data=$redis->LRANGE($key,0,30);
$newData = arrayToJSON($data);
echo $newData;
}
?>

chat_get.php
Contains PHP code. Get records from Redis server.
<?php
include 'redis_config.php';
include 'arrayToJSON.php';
if(isset($_POST['user']))
{
$data=$redis->LRANGE($key,0,30);
$newData = arrayToJSON($data);
echo $newData;
}
?>

JSON Output
[
["User One","2013-12-30T09:18:37+01:00","Hi"],
["User Two","2013-12-30T08:57:00+01:00","Hello"],
["User One","2013-12-28T18:46:41+01:00","Hi Everyone"],
......
......
]

arrayToJson.php
PHP code converts array to JSON format.
<?php
function arrayToJSON($arr)
{
if(count($arr) > 0)
{
for($i=0; $i<count($arr); $i++)
{
$data = @unserialize($arr[$i]);
if($data !== false )
{
$arr[$i] = unserialize($arr[$i]);
}
}
}
return json_encode($arr);
}
?>

We are working on Redis and MySQL backup system, soon I will publish this.
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


26 comments:

  1. HI its amazing chat software.

    I have one question , like its public chat software, do you have any private chat software means account to account chat, please share if you have.

    Thanks

    ReplyDelete
  2. ive tried this before while its ok for maybe 50 users anything above that causes stress on the server but still well done nice post

    ReplyDelete
  3. http://blog.cloudfoundry.com/2013/01/24/scaling-real-time-apps-on-cloud-foundry-using-node-js-and-redis/

    ReplyDelete
  4. It seems a nice chat software.... but sending request to the server every second, could be really a trouble if user increases to 1000 at a time!!!

    ReplyDelete
  5. nice, i love chatting script, tks 9lessions team.
    i developed chatting module with Openfire server with XMPP protocol that is also amazing.

    ReplyDelete
  6. show error when key in '?'

    ReplyDelete
  7. throwing this error.
    Fatal error: Class 'Redis' not found in C:\xampp\htdocs\Chat-App\test.php on line 2

    redis.io is installed as directed for a 32 bit Win OS.

    ReplyDelete
  8. show me "Error In Connecting" also run "redis_config.php" and show me " Fatal error: Class 'Redis' not found in C:\wamp\www\redis_config.php on line 3"
    i am using "WAMP SERVER" and i had installed "php_redis.dll" but when i run a "phpinfo();" this not appears in modules, is this normal?

    ReplyDelete
  9. @anonymous: Thanks for your reply.

    after installation of redis .. i ran the redis sample script:


    connect('127.0.0.1', 6379);
    $key="Key_Name"
    $redis->set($key, 'Key Value');
    echo $redis->get($key);
    ?>


    and insted of echoing "$Key", it gave me follwing error:

    Fatal error: Class 'Redis' not found in C:\xampp\htdocs\Chat-App\test.php on line 2

    ReplyDelete
  10. But it is sending requests to sever every second....

    ReplyDelete
  11. we want asp.net mvc

    ReplyDelete
  12. Can you give an example for android . as how to subscribe for the message.
    and also can these messages be retrieved via socket ? how do a android app get messages without call webservice.

    Thanks & regards

    ReplyDelete
  13. i am getting this error while running the script "index.php" - "Error In Connecting".
    how to fix this??

    ReplyDelete
  14. Hello Admin

    Nice Work here, but i dont know how to install it. Pls make video tutorial for me

    ReplyDelete
  15. One of the many great articles shared by 9Lessons. I was just wondering if this is possible to share a file using AJAX techniques?

    Thanks,
    Ahmad.

    ReplyDelete
  16. $key="Key_Name"
    Please add " ; ".
    Sometime people are in hurry and they will not notice a silly mistake from a traffic repositories.

    ReplyDelete
  17. "error in connectiong"

    ReplyDelete

Make in India