Добро пожаловать!
Здесь вы можете найти ответ на интересующий вас вопрос в отрасли сайтостроения, познакомится ближе с web технологиями и web стандартами.

Заметки

Чат на файлах

Чат расположен внутри плавающего фрейма - поэтому его можно вставить в любом месте страницы:

<!doctype html public "-//W3C//DTD HTML4.01 Frameset//EN">
<html>
<head>
<title>Мини Чат!</title>
</head>
<iframe src="index.php" width="640" height="480" hspace="10" vspace="10">
Ваш браузер не поддерживает плавающие фреймы!
</iframe>
</html>

Сам чат будет состоять из двух окошек - одно для добавления сообщений (и авторизации), другое - для показа сообщений:

<html>
<head>
<title>Мини Чат!</title>
</head>
<frameset rows="30%,70%">
    <frame name="addmsg" src="addmsg.php">
    <frame name="showmsg" src="showmsg.php">
</frameset>
</html>

Файл addmsg.php отвечает за добавление сообщений - т.е. запись их в файл messages.txt:

<?php 
  session_start
(); 
  
// Если пользователь не авторизован 
  
if ( !isset($_SESSION["login"]) ) { 
    
// Если форма для ввода логина и пароля была заполнена 
    
if ( isset($_POST["auth"]) ) { 
      
$logpass file"passwords.txt" );  
      foreach ( 
$logpass as $value ) {        
        list( 
$login$password ) = explode"|"trim$value ) );  
        if( (
$_POST['login']==$login) && ($_POST['password']==$password) ) {  
          
// авторизация прошла успешно 
          
$_SESSION['login'] = $_POST['login'];
          
header"Location: addmsg.php" );
        }  
      }
    }    
    echo 
'<form name="authForm" method="post" action="addmsg.php">'
    echo 
'Логин: <input type="text" name="login" value="" /><br/>'
    echo 
'Пароль: <input type="password" name="password" value="" />'
    echo 
'<input type="submit" name="auth" value="Вход" />'
    echo 
'</form>'
    die(); 
  }
?>

<html>
<head>
<script type="text/javascript">
function AddSmile(text) {
  document.forms["addMsg"].elements["message"].value+=text;
  document.forms["addMsg"].elements["message"].focus();
}

function PutSmiles() {
  var pointer = "onmouseover=this.style.cursor='pointer'";
  var smiles = ["smiley", "wink", "cheesy", "grin", "angry", "sad", "shocked", "cool", 
  "rolleyes", "tongue", "embarassed", "lipsrsealed", "undecided", "kiss", "cry"];
  var emb = [":)", ";)", ":cheesy:", ":grin:", ":angry:", ":(", ":o", ":cool:", "::)", 
  ":tongue:", ":embarassed:", ":lipsrsealed:", ":-/", ":kiss:", ":cry:"];
  for (i = 0;i < 15; i++) {
    document.write("<img src='images/" + smiles[i] + ".gif' onclick='javascript: AddSmile(\" " + 
    emb[i] + "\");' " + pointer + " alt='" + smiles[i] + "' width='15' height='15' />&nbsp;");
  }
}

function CheckMsg(frm)
{
  if(frm.elements["message"].value == "") {
    alert("Введите сообщение");
    return false;
  }
  else
    return true;  
}
</script>
</head>
<body>
<form method="POST" name="addMsg" onSubmit="CheckMsg(this);">
<input type="text" name="person" maxlength="30" 
value="<?php echo $_SESSION["login"]; ?>" readonly="readonly" />
&nbsp;&nbsp;&nbsp;<script type='text/javascript'>PutSmiles()</script><br/>
<textarea name="message" rows="2" cols='60'></textarea><br/>
<input type="submit" value='Добавить'>
<img width="15" height="15" src="./images/refresh.gif" 
OnMouseOver='this.style.cursor="pointer";' alt="Обновить Чат!" 
OnClick="parent.showmsg.location.href = parent.showmsg.location.href;" 
style="position:absolute; top: 5px; right:5px" />

<?php
if ( isset($_POST['message']) and !empty($_POST['message']) ) {
  if ( 
filesize"messages.txt" ) > $file file("messages.txt");
  
// Добавляем новую запись
  
$message substr$_POST["message"], 0250 );
  
$message htmlspecialcharstrim($message) );
  
$message preg_replace"#\r?\n#"'<br/>'$message );
  
$file[] = $_SESSION["login"]."¤".date("d-m-y H:i:s")."¤".$message."\n";
  
// Удаляем старые записи (оставляем только десять последних)
  
$cnt count$file );
  if ( 
$cnt 10 ) {
    for( 
$i 0$i < ($cnt-10); $i++ ) array_shift$file );
  }     
  
// Перезаписываем файл
  
if ( $fp fopen("messages.txt""w") ) {
    if (
flock($fpLOCK_EX)) {
      foreach ( 
$file as $msg fwrite($fp$msg);
      
flock($fpLOCK_UN);
    }
    
fclose($fp);
  }
  
// Обновляем файл, где хранится информация о пользователях on-line
  
$file file"online.txt" );
  
$cnt count$file );
  
$id session_id();
  for ( 
$i 0$i $cnt$i++ ) {
    
$tmp explode"|"$file[$i] );
    
// была ли запись об этом пользователе?
    
if ( $tmp[0] == $id $on $i;      
  }
  if ( isset(
$on) ) {
    
// запись уже была - надо обновить время
    
$file[$on] = $id."|".time()."\n";
  } else {
    
// записи еще не было, значит добавляем
    
$file[] = $id."|".time()."\n";
  }
  if ( 
$fp fopen("online.txt""w") ) {
    if (
flock($fpLOCK_EX)) {
      
$c count($file);
      for ( 
$i 0$i $c$i++) fwrite($fp$file[$i]);
      
flock($fpLOCK_UN);
    }
    
fclose($fp);
  }
}
?>

</body>
</html>

Файл messages.txt имеет вид:

Masha¤22-01-08 10:48:57¤Привет всем!!!
Masha¤22-01-08 10:49:22¤Вот такой простенький чат на файлах  :)
Sasha¤22-01-08 10:59:47¤Это первое сообщение от Саши  :cheesy:

Файл showmsg.php отвечает за показ сообщений:

<html>
<head>
<meta http-equiv="refresh" content="5; url=showmsg.php">
</head>
<body>
<?php
  session_start
();
  
$id session_id();
  include 
"functions.php";
  echo 
"<div style='color:red; border:1px solid red; padding:0.5em; margin:0.5em'>On-line ".onLine()." человек(а)</div>\n";
  
$file file("messages.txt");
  if ( 
count$file ) > ) {
    
$file array_reverse$file );
    
$messages "";
    foreach(
$file as $value) {
      
$record explode("¤"trim($value));
      
$messages $messages."<div>Добавил(а): <b>".$record[0]."</b> <span style='color:green'>".
      
$record[1]."</span><br/>".$record[2]."<hr></div>";
    }
    
$messages make_smiles($messages);
  } else {
    
$messages "<div>Нет сообщений</div>\n";
  }
  echo 
$messages
?>
</body>
</html>

Файл functions.php содержит пару вспомогательных функций:

<?php
function make_smiles($str) {
  
$smiles[0] = "rolleyes";
  
$smiles[1] = "wink";
  
$smiles[2] = "cheesy";
  
$smiles[3] = "grin";
  
$smiles[4] = "angry";
  
$smiles[5] = "sad";
  
$smiles[6] = "shocked";
  
$smiles[7] = "cool";
  
$smiles[8] = "smiley";
  
$smiles[9] = "tongue";
  
$smiles[10] = "embarassed";
  
$smiles[11] = "lipsrsealed";
  
$smiles[12] = "undecided";
  
$smiles[13] = "kiss";
  
$smiles[14] = "cry";
  
$emb[0] = "::)";
  
$emb[1] = ";)";
  
$emb[2] = ":cheesy:";
  
$emb[3] = ":grin:";
  
$emb[4] = ":angry:";
  
$emb[5] = ":(";
  
$emb[6] = ":o";
  
$emb[7] = ":cool:";
  
$emb[8] = ":)";
  
$emb[9] = ":tongue:";
  
$emb[10] = ":embarassed:";
  
$emb[11] = ":lipsrsealed:";
  
$emb[12] = ":-/";
  
$emb[13] = ":kiss:";
  
$emb[14] = ":cry:";
  for (
$i=0$i<15$i++) { 
    
$str str_replace($emb[$i], '<img src="./images/'.$smiles[$i].'.gif" width="15" height="15">'$str);
  }
  return 
$str;
}

function 
onLine() {
  
$currentTime time();
  
// Если пользователь 30 секунд не подает признаков 
  // жизни, считаем, что он покинул чат
  
$offLine time() - 30
  
$file file("online.txt");
  
// Если файл online.txt пустой, значит в чате никого нет
  
if ( count$file ) > ) {
    
$res "";
    
// количество пользователей on-line
    
$onLine 0;
    foreach (
$file as $value) { 
      
$line explode("|"trim($value)); 
      if (
$line[1] > $offLine) {
        
$res $res.$value;
        
$onLine $onLine 1;
      }    
    } 
    
// перезаписываем файл
    
if ( $fp fopen("online.txt""w") ) {
      if (
flock($fpLOCK_EX)) {
        
fwrite($fp$res);
        
flock($fpLOCK_UN);
      }
      
fclose($fp);
    }
  }
  else {
    
$onLine 0;
  }
  return 
$onLine;
}
?>

Файл online.txt имеет вид:

c5vbg4tntep57br228nt87nfs3|1200990926
umoi35vr0soqr299clh7p2v280|1200990930

Файл passwords.txt имеет вид:

Masha|qwerty
Sasha|123456

Чат на файлах

Скачать скрипт чата