-
Notifications
You must be signed in to change notification settings - Fork 0
/
vote.php
69 lines (57 loc) · 1.67 KB
/
vote.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
68
69
<?php
global $url, $connection;
header('Content-type: application/json');
if (empty($_POST) || empty($_POST['question'])) {
redirect('404');
}
$response = array(
'success' => false,
'double' => false,
'message' => 'Something went wrong when trying to process your vote.'
);
// get existing votes
$votes = array();
if (isset($_COOKIE['votes'])) {
$votes = unserialize($_COOKIE['votes']);
}
if ($votes[$_POST['question']]) {
$response = array(
'success' => true,
'double' => true,
'message' => 'You already voted for that question!'
);
echo json_encode($response);
return;
}
// make sure this is a valid poll
$query = $connection->prepare("SELECT `poll_id` FROM `questions` WHERE `rowid` = {$_POST['question']} LIMIT 1;");
if (!$query->execute()) {
echo json_encode($response);
return;
}
$question = $query->fetchObject();
$query = $connection->prepare("SELECT * FROM `polls` WHERE `rowid` = $question->poll_id LIMIT 1;");
if (!$query->execute()) {
echo json_encode($response);
return;
}
$poll = $query->fetchObject();
$expired = $poll->expires && (strtotime($poll->expires) - strtotime() <= 0);
if (!$poll->enabled || $expired) {
$response['message'] = 'Invalid poll!';
echo json_encode($response);
return;
}
$query = $connection->prepare("UPDATE `questions` SET `votes` = (`votes` + 1) WHERE `rowid` = {$_POST['question']};");
if ($query->execute()) {
$response = array(
'success' => true,
'double' => false,
'message' => 'Thanks for voting!'
);
$votes[$_POST['question']] = true;
setcookie('votes', serialize($votes), strtotime('+20 years'));
} else {
$response['message'] = 'Something went wrong when trying to process your vote.';
}
echo json_encode($response);