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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| <?php
$options = ['选项一', '选项二', '选项三', '选项四']; $dataFile = __DIR__ . '/voteresult.txt';
if (!file_exists($dataFile)) { $zeros = implode('|', array_fill(0, count($options), '0')) . "\n"; file_put_contents($dataFile, $zeros, LOCK_EX); }
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['option'])) { $choice = (int)$_POST['option']; if ($choice >= 0 && $choice < count($options)) { $fp = fopen($dataFile, 'c+'); if ($fp) { if (flock($fp, LOCK_EX)) { $contents = stream_get_contents($fp); $contents = trim($contents); $parts = $contents === '' ? array_fill(0, count($options), 0) : explode('|', $contents); $counts = array_map('intval', array_pad($parts, count($options), 0)); $counts[$choice]++; rewind($fp); ftruncate($fp, 0); fwrite($fp, implode('|', $counts) . "\n"); fflush($fp); flock($fp, LOCK_UN); } fclose($fp); } } header('Location: ' . $_SERVER['PHP_SELF']); exit; }
$counts = array_fill(0, count($options), 0); $fp = fopen($dataFile, 'r'); if ($fp) { if (flock($fp, LOCK_SH)) { $contents = stream_get_contents($fp); flock($fp, LOCK_UN); } fclose($fp); $contents = trim($contents); if ($contents !== '') { $parts = explode('|', $contents); $counts = array_map('intval', array_pad($parts, count($options), 0)); } } $total = array_sum($counts); ?> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <title>投票页</title> <style> body{font-family: Arial, sans-serif; max-width:640px;margin:2em auto;padding:1em;border:1px solid .option{margin:0.5em 0;padding:0.5em;border:1px solid .bar{display:inline-block;height:14px;background: .count{margin-left:0.6em;color: </style> </head> <body> <h2>请选择一个选项并投票</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>"> <?php foreach ($options as $i => $label): ?> <div class="option"> <label> <input type="radio" name="option" value="<?php echo $i; ?>" <?php echo $i === 0 ? 'checked' : ''; ?>> <?php echo htmlspecialchars($label); ?> </label> <span class="count"><?php echo $counts[$i]; ?> 票(<?php echo $total ? round($counts[$i] * 100 / $total, 1) : 0; ?>%)</span> <div style="margin-top:6px;background:#f1f1f1;height:14px;"> <div class="bar" style="width:<?php echo $total ? round($counts[$i] * 100 / $total, 1) : 0; ?>%"></div> </div> </div> <?php endforeach; ?> <p><button type="submit">投票</button></p> </form> <h3>统计</h3> <p>总票数:<?php echo $total; ?></p> </body> </html>
|