post.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. function getSetup($key = null) {
  3. $arr = parse_ini_file('setup.ini');
  4. return isset($key) ? $arr[$key] : $arr;
  5. }
  6. //$_POST['text'] = 'abc';
  7. session_start();
  8. if (!isset($_SESSION['name'])) return;
  9. $text = isset($_POST['text']) ? $_POST['text'] : '';
  10. if ($text === '') return;
  11. $isApc = extension_loaded('apc');
  12. $setup = getSetup();
  13. $time = time();
  14. $date = date('Y-m-d', $time);
  15. $uniqid = uniqid();
  16. $id = $time.'-'.$uniqid;
  17. $tmpDir = './tmp/';
  18. $historyDir = './history/';
  19. $tmpFile = $tmpDir.'cache';
  20. $historyFile = $historyDir.$date;
  21. $fh = @fopen($historyFile, 'a');
  22. if ($fh === false) {
  23. mkdir($historyDir);
  24. if (!is_dir($tmpDir)) mkdir($tmpDir);
  25. $fh = @fopen($historyFile, 'a');
  26. }
  27. /* start semafore */
  28. flock($fh, LOCK_EX);
  29. // data
  30. $data = array($id, $_SESSION['name'], stripslashes(htmlspecialchars($text)));
  31. // write history
  32. fwrite($fh, implode('&', $data)."\n");
  33. // cache
  34. if ($isApc) {
  35. $cache = apc_fetch('chat');
  36. if ($cache === false) {
  37. $cache = array();
  38. }
  39. } else {
  40. $cache = @file_get_contents($tmpFile);
  41. if ($cache === false) {
  42. $cache = array();
  43. } else {
  44. $cache = unserialize($cache);
  45. }
  46. }
  47. array_unshift($cache, $data);
  48. // delete expired cache
  49. $expireTime = floor($time - $setup['interval']/1000 - $setup['expire_cache']);
  50. foreach (array_reverse($cache,true) as $k => $e) {
  51. if ($e[0] < $expireTime) {
  52. unset($cache[$k]);
  53. } else {
  54. break;
  55. }
  56. }
  57. if ($isApc) {
  58. apc_store('chat', $cache);
  59. } else {
  60. file_put_contents($tmpFile, serialize($cache));
  61. }
  62. /* end semafore */
  63. flock($fh, LOCK_UN);
  64. fclose($fh);