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
Download Script Live Demo Live Demo New
Setup
Ubuntu
# git clone git://github.com/nicolasff/phpredis.git
# cd phpredis
# phpize
# ./configure
# make
# sudo -s make install
# 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
$ 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
Redis for windows(x64) 64bit
https://github.com/MSOpenTech/redis/releases
Redis for windows(x86) 32bit
http://ruilopes.com/redis-setup/ or Redis 2.8 Windows 32Bit Download
Download the appropriate version of the DLL, for thread safety check phpinfo(). Based on that use Thread Safety version otherwise use Non Thread Safety version.
Extract the ZIP and copy the .dll file in xampp/php/ext or php/extension folder.
Download php_redis.dll copy into PHP extension folder.
Add Extension on php.ini
extension php_redis.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);
?>
$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, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
//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" />
<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, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
//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);
?>
$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;
}
?>
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;
}
?>
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"],
......
......
]
["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);
}
?>
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.
HI its amazing chat software.
ReplyDeleteI 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
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
ReplyDeleteNice work srinivas..
ReplyDeleteGreat Work
ReplyDeletehttp://blog.cloudfoundry.com/2013/01/24/scaling-real-time-apps-on-cloud-foundry-using-node-js-and-redis/
ReplyDeleteIt 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!!!
ReplyDeletenice, i love chatting script, tks 9lessions team.
ReplyDeletei developed chatting module with Openfire server with XMPP protocol that is also amazing.
show error when key in '?'
ReplyDeletethrowing this error.
ReplyDeleteFatal 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.
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"
ReplyDeletei 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?
cool
ReplyDeleteVery Very Nice
ReplyDelete@anonymous: Thanks for your reply.
ReplyDeleteafter 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
nice post dear
ReplyDeletewe want asp.net mvc
ReplyDeleteis it working on linux
ReplyDeleteCan you give an example for android . as how to subscribe for the message.
ReplyDeleteand also can these messages be retrieved via socket ? how do a android app get messages without call webservice.
Thanks & regards
i am getting this error while running the script "index.php" - "Error In Connecting".
ReplyDeletehow to fix this??
Hello Admin
ReplyDeleteNice Work here, but i dont know how to install it. Pls make video tutorial for me
hhhhh
ReplyDeleteThis is a nice post. Thank you.
ReplyDeletenic post thanks
ReplyDeleteOne of the many great articles shared by 9Lessons. I was just wondering if this is possible to share a file using AJAX techniques?
ReplyDeleteThanks,
Ahmad.
$key="Key_Name"
ReplyDeletePlease add " ; ".
Sometime people are in hurry and they will not notice a silly mistake from a traffic repositories.
"error in connectiong"
ReplyDeleteDemos are UP now.
Delete