Menu:

Sponsor

Discover Master of Alchemy, our first iPad/iPhone and iPod touch game!

 

Forum's topics

Latest Files

Archives

Top Rated

Categories

Photo Gallery


Basic Flash MX/MySQL chat

1. Introduction

Welcome to my first tutorial regarding Flash MX and PHP. Here, we will try to set up a simple Flash chat in order to implement it into your web pages without using any socket connection. Only simple HTTP requests from Flash to PHP and viceversa will be used.
N.B. If you are looking for a high performance chat, please go to http://www.moock.org/ or use a Server Application which communicates with Flash through a socket protocol.

To study with this tutorial, you will need: Web server with PHP, MySQL database and Flash MX

2. Configure MySQL

2.1 Open your preferred PHP Editor (mine is TextPad) and create a new document. Save it as config.inc.php
In this file, we will define the MySQL variables to make PHP connection. Therefore, write the following lines into that file:

          
<?php
// -------------------
// configuration file
// insert here
// you MySQL variables
// -------------------
$table 'flash_chat';
$user 'flash_chat_useronline';

// ---------------
// flash chat vars
// ---------------
// how many old messages the firs time enters
$first_run 50;
// max users online
$max_users 5;
// After how much time user is disconnected (in ms)
$active 20000;


// --------------------
// pass microtime
// --------------------
function getmicrotime()
{
    
$time microtime();
    
$time explode(" ",$time);
    return (
$time[1] . substr($time[0],2,3));
}
?>



In the last lines, there is a function getmicrotime() which we will use it in the future to receive the actual datetime in microtime format, unix_timestamp. It gets the microtime value and splits it into an array, then join the two values removing the decimal dot separator and the last 2 numbers in order to convert a 13 chars value.

2.2 Now, we have to create the two tables (in MySQL) which allows us to run the chat. You can simply create these tables by running these queries from your MySQL client:

          
#
# Table structure for table `flash_chat`
#

DROP TABLE IF EXISTS flash_chat;
CREATE TABLE flash_chat (
  user_id varchar(37) NOT NULL default '0',
  chat_data double NOT NULL default '0',
  chat_message text NOT NULL,
  KEY user_id(user_id)
) TYPE=MyISAM;
# --------------------------------------------------------

#
# Table structure for table `flash_chat_useronline`
#

DROP TABLE IF EXISTS flash_chat_useronline;
CREATE TABLE flash_chat_useronline (
  user_id char(37) NOT NULL default '0',
  user_name char(15) NOT NULL default '',
  user_date double NOT NULL default '0',
  KEY user_id(user_id)
) TYPE=MyISAM;

3. Writing the PHP side:

Note that, we have to add the following header to the beginnings of each PHP file that we are creating:

error_reporting(E_ERROR);
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// always modified
header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); // HTTP/1.0


these lines will allow us to prevent browser caching.

3.1 first_access.php

Let's start with the first PHP file which communicates with Flash. This file will be called by Flash when user presses the login button and it should register the new user into the database by assigning him a personal and unique id number. Here is the complete code for this file:

            
<?
include_once ('config.inc.php');
// -----------------------
// First check how many
// active users are online
// -----------------------
$time_start getmicrotime();
$query "SELECT user_name FROM $user WHERE ($time_start - user_date) < $active";
$sql mysql_query($query,$db) or die("output=false");
$total_users mysql_num_rows($sql);
if(
$total_users >= $max_users)
{
   die(
"output=false"); // access denied
}
// ---------------------
// FIRST ACCESS
// return its unique id
// ---------------------
if(isset($_GET['submit']) && isset($_GET['username']))
{
   
$uid md5(uniqid(microtime(), 1)) . getmypid();
   
$username $_GET['username'];
   
$query "INSERT INTO $user (user_id, user_name, user_date) VALUES ('$uid', '$username', '$time_start')";
   if(
$sql mysql_query($query,$db))
   {
      print 
"uniqid=$uid";
   } else {
      print 
"output=false";
   }
}
?>


At first, we will get the actual time $time_start = getmicrotime(); and then we will check the database whether how many users are online. The reason for this is that, if there are more than $max_users (in the config file) whose last update is < than $active time, then the new client will be denied to access the chat by sending it this output: output=false.

If http_get_var 'username' and 'submit' are defined (both passed by flash), then the code will insert user into database and return him with its unique id value.
$uid = md5(uniqid(microtime(), 1)) . getmypid();
This is the line which generates the unique id number. It makes an md5 encryption of the microtime value plus the current PHP processing ID. We are quite sure that this is a real random unique number.