<?php
namespace MyApp;
use Ratchet\ConnectionInterface;
use Ratchet\MessageComponentInterface;
require "../db/users.php";
require "../db/chatrooms.php";
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
echo "Server Started.";
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
$data = json_decode($msg, true);
$objChatroom = new \chatrooms;
$objChatroom->setUserId($data['userId']);
$objChatroom->setMsg($data['msg']);
$objChatroom->setCreatedOn(date("Y-m-d h:i:s"));
if ($objChatroom->saveChatRoom()) {
$objUser = new \users;
$objUser->setId($data['userId']);
$user = $objUser->getUserById();
$data['from'] = $user['name'];
$data['msg'] = $data['msg'];
$data['dt'] = date("d-m-Y h:i:s");
}
foreach ($this->clients as $client) {
if ($from == $client) {
$data['from'] = "Me";
} else {
$data['from'] = $user['name'];
}
$client->send(json_encode($data));
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
<?php
class chatrooms {
private $id;
private $userId;
private $msg;
private $createdOn;
protected $dbConn;
function setId($id) {$this->id = $id;}
function getId() {return $this->id;}
function setUserId($userId) {$this->userId = $userId;}
function getUserId() {return $this->userId;}
function setMsg($msg) {$this->msg = $msg;}
function getMsg() {return $this->msg;}
function setCreatedOn($createdOn) {$this->createdOn = $createdOn;}
function getCreatedOn() {return $this->createdOn;}
public function __construct() {
require_once 'DbConnect.php';
$db = new DbConnect();
$this->dbConn = $db->connect();
}
public function saveChatRoom() {
$stmt = $this->dbConn->prepare('INSERT INTO chatrooms VALUES(null, :userid, :msg, :createdOn)');
$stmt->bindParam(':userid', $this->userId);
$stmt->bindParam(':msg', $this->msg);
$stmt->bindParam(':createdOn', $this->createdOn);
if ($stmt->execute()) {
return true;
} else {
return false;
}
}
public function getAllChatRooms() {
$stmt = $this->dbConn->prepare("SELECT c.*, u.name FROM chatrooms c JOIN users u ON(c.userid = u.id) ORDER BY c.id DESC");
$stmt->execute();
$chatrooms = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $chatrooms;
}
}
?>
<?php
class users {
private $id;
private $name;
private $email;
private $loginStatus;
private $lastLogin;
public $dbConn;
function setId($id) { $this->id = $id; }
function getId() { return $this->id; }
function setName($name) { $this->name = $name; }
function getName() { return $this->name; }
function setEmail($email) { $this->email = $email; }
function getEmail() { return $this->email; }
function setLoginStatus($loginStatus) { $this->loginStatus = $loginStatus; }
function getLoginStatus() { return $this->loginStatus; }
function setLastLogin($lastLogin) { $this->lastLogin = $lastLogin; }
function getLastLogin() { return $this->lastLogin; }
public function __construct() {
require_once("DbConnect.php");
$db = new DbConnect();
$this->dbConn = $db->connect();
}
public function save() {
$sql = "INSERT INTO `users`(`id`, `name`, `email`, `login_status`, `last_login`) VALUES (null, :name, :email, :loginStatus, :lastLogin)";
$stmt = $this->dbConn->prepare($sql);
$stmt->bindParam(":name", $this->name);
$stmt->bindParam(":email", $this->email);
$stmt->bindParam(":loginStatus", $this->loginStatus);
$stmt->bindParam(":lastLogin", $this->lastLogin);
try {
if($stmt->execute()) {
return true;
} else {
return false;
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
public function getUserByEmail() {
$stmt = $this->dbConn->prepare('SELECT * FROM users WHERE email = :email');
$stmt->bindParam(':email', $this->email);
try {
if($stmt->execute()) {
$user = $stmt->fetch(PDO::FETCH_ASSOC);
}
} catch (Exception $e) {
echo $e->getMessage();
}
return $user;
}
public function getUserById() {
$stmt = $this->dbConn->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $this->id);
try {
if($stmt->execute()) {
$user = $stmt->fetch(PDO::FETCH_ASSOC);
}
} catch (Exception $e) {
echo $e->getMessage();
}
return $user;
}
public function updateLoginStatus() {
$stmt = $this->dbConn->prepare('UPDATE users SET login_status = :loginStatus, last_login = :lastLogin WHERE id = :id');
$stmt->bindParam(':loginStatus', $this->loginStatus);
$stmt->bindParam(':lastLogin', $this->lastLogin);
$stmt->bindParam(':id', $this->id);
try {
if($stmt->execute()) {
return true;
} else {
return false;
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
public function getAllUsers() {
$stmt = $this->dbConn->prepare("SELECT * FROM users");
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $users;
}
}
<?php
use MyApp\Chat;
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();