-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.php
67 lines (56 loc) · 1.47 KB
/
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
try{
$db = new PDO('sqlite:test.db');
}
catch(PDOException $e){
die('Failed to connect:'. $e->getMessage());
}
//check to see if the ajax call was to update db
if (isset($_POST['text'])){
session_start();
//if user has logged in use his name, else use "guest"
$us='Guest';
if (isset($_SESSION['username']))
$us=$_SESSION['username'];
session_write_close();
$msg=$_POST['text'];
$sql ="INSERT INTO MESSAGES (USER,MESSAGE) VALUES(?, ?)";
try{
$ret = $db->prepare($sql);
$ret->execute([$us,$msg]);
}
catch(PDOException $e){
console.log('Failed to update db:'. $e->getMessage());
}
}
else{
//the script will run for 20 seconds after the initial ajax call
$time=time()+20;
while(time()<$time){
if ($_POST['time']){
$prevtime=$_POST['time'];
}
else {
$prevtime=0;
}
//query to see if there are new messages
$sql ="SELECT TIME,USER,MESSAGE FROM MESSAGES WHERE TIME>? ORDER BY TIME ASC";
try{
$ret = $db->prepare($sql);
$ret->execute([$prevtime]);
$resarr = $ret->fetchAll(PDO::FETCH_ASSOC);
//if there are no new messages in the db, sleep for half a second and then run loop again
if (!$resarr)
sleep(0.5);
else{
echo json_encode($resarr);
break;
}
}
catch(PDOException $e){
console.log('Failed to get messages:'. $e->getMessage());
}
}
}
$db=null;
?>