title: Create a web-based chat box using AJAX, PHP, and SQL Long Polling?
body: <p>I'm creating an online chat box for me and my friends at college to use online. In the current configuration, the chat messages are stored in a plain text file on the host machine (mine) and are fetched via AJAX every second, however, sometimes it is slow and glitchy and doesn't always work.</p>
  
  <p>To send a message, it passes the message to a JavaScript function which passes the value to a PHP script, writing it to the file along with the user's unique color (stored in a local cookie). Here's the functions.js file (pastebin): <a href="http://pastebin.com/CpGxj5cP" rel="nofollow">http://pastebin.com/CpGxj5cP</a></p>
  
  <p>Here's the php file to send the message: </p>
  
  <pre><code>&lt;?php
  session_start();
  require_once('mysql_connect.php');
  date_default_timezone_set("EST");
  
  //Format the message
  $date = date('n/j g:i A');
  $username = $_SESSION['username'];
  $color = $_COOKIE[$username];
  
  $message  = "&lt;font color='" . $color . "'&gt;" . $username . "&lt;/font&gt; (" .  $date . "): ";
  $message .= $_GET['m'] . "\n";
  
  $file = '../messages.txt';
  
  $handle = fopen($file, 'a');
  fputs($handle, $message);
  
  fclose($handle);
  
  //Reset timeout
  //$_SESSION['timeout'] = 300;
  ?&gt;
  </code></pre>
  
  <p>As I said above, the issue is that it's very very slow. If there's a way to do it better than a textfile/AJAX, please let me know!</p>