9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Sunday, January 5, 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.
Comments
{ 24 comments }
vikas said...

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

Anonymous said...

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

Karthik said...

Nice work srinivas..

Waqas Ahmed said...

Great Work

shashank saxena said...

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

salman said...

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!!!

Vijay lathiya said...

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

Anonymous said...

show error when key in '?'

shashank saxena said...

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.

Anonymous said...

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?

fabrice bede said...

cool

Balaji Jadhav said...

Very Very Nice

shashank saxena said...

@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

Anonymous said...

nice post dear

Mukesh Yadav said...

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

Anonymous said...

we want asp.net mvc

abdul wakeel said...

is it working on linux

Anonymous said...

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

partha said...

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

Mohd Afendie said...

Hello Admin

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

Anonymous said...

hhhhh

Anand Roshan said...

This is a nice post. Thank you.

shingate ganesh said...

nic post thanks

Ahmad Rasheed said...

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.

Post a Comment