蓝色天空网mbsky.com · 知识 · 实践 · 创造PHP · 本地阅读预览
教程 / 后端开发 / PHP

AJAX 投票

核对无刷新投票的前端单选触发、PHP 读写 poll_result.txt 计数文件、百分比进度条计算、文件锁并发保护与权限约束。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

无刷新投票交互与 poll.html 流程

AJAX 投票允许用户在单选按钮上点击“是”或“否”后即时看到图形化统计结果,无需刷新整张页面。`poll.html` 为两个 `<input type="radio">` 绑定 `onclick="getVote(this.value)"`(选项值分别为 `0` 与 `1`);触发后 `getVote()` 创建 `XMLHttpRequest` 对象、注册回调将服务端返回的统计表格替换写入 `#poll` 容器,并向 `poll_vote.php?vote=` 发送异步请求(注意原始示例说明误写参数名为 `q`,实际代码中传递的查询参数为 `vote`)。来源页嵌入式 `<script>`、`<form>` 与 2 个 `<input>` 均已静态登记且不执行。

PHP 计票、百分比条渲染与文本文件存储

服务端 `poll_vote.php` 接收投票值后按四步处理:读取 `poll_result.txt`、用 `explode("||", ...)` 拆分“是/否”计数并按投票值(`0` 或 `1`)将对应计数加 1、把更新后的 `yes||no` 写回文件、最后按 `100 * round($yes / ($no + $yes), 2)` 计算百分比并渲染带绿/红宽度条的 HTML 表格。工程实践中应使用 `flock($fp, LOCK_EX)` 防止并发投票丢票、显式防范总票数为 `0` 时的除零异常,并忽略非 `0`/`1` 的非法输入。

`poll_result.txt` 采用 `3||4` 格式保存两项累计票数,首数字代表“是(Yes)”票数,次数字代表“否(No)”票数;服务器上必须严格限制该文件权限,仅允许 Web 服务器(PHP 进程)读写,避免被外部用户直接篡改或通过 Web 路径裸露访问。本站 PHP 8.4.27 实测加锁读写临时计数文件:从 `3||4` 投“是”变为 `4||4`(`50% / 50%`),再投“否”变为 `4||5`(`44% / 56%`),生成的进度条含精确 `width:44px`(绿)与 `width:56px`(红);从 `0||0` 起投安全防护除零并变为 `1||0`(`100% / 0%`);非法值 `2` 与 `<script>` 均被忽略且文件内容维持 `3||4` 不变。

运行 PHP 8.4 加锁投票计数、零票防护、非法值过滤与进度条宽度实测

php · 阅读源码
<?php
declare(strict_types=1);

$cases = [];

function add_case(array &$cases, string $name, mixed $expected, mixed $actual): void {
    $cases[] = [
        'name' => $name,
        'passed' => ($actual === $expected),
        'expected' => $expected,
        'actual' => $actual,
    ];
}

$castVote = static function (string $filePath, string $rawVote): array {
    $fp = fopen($filePath, 'c+');
    if ($fp === false) {
        throw new RuntimeException('Cannot open poll file');
    }
    flock($fp, LOCK_EX);
    rewind($fp);
    $line = trim((string) stream_get_contents($fp));
    $parts = explode('||', $line !== '' ? $line : '0||0');
    $yes = (int) ($parts[0] ?? 0);
    $no = (int) ($parts[1] ?? 0);

    $updated = false;
    if ($rawVote === '0') {
        $yes++;
        $updated = true;
    } elseif ($rawVote === '1') {
        $no++;
        $updated = true;
    }

    if ($updated) {
        rewind($fp);
        ftruncate($fp, 0);
        fwrite($fp, "{$yes}||{$no}");
        fflush($fp);
    }
    flock($fp, LOCK_UN);
    fclose($fp);

    $total = $yes + $no;
    $yesPct = $total > 0 ? (int) (100 * round($yes / $total, 2)) : 0;
    $noPct = $total > 0 ? (int) (100 * round($no / $total, 2)) : 0;

    $html = "<h2>结果:</h2><table>"
        . "<tr><td>是:</td><td><span style=\"display: inline-block; background-color:green; width:{$yesPct}px; height:20px;\"></span> {$yesPct}%</td></tr>"
        . "<tr><td>否:</td><td><span style=\"display: inline-block; background-color:red; width:{$noPct}px; height:20px;\"></span> {$noPct}%</td></tr>"
        . "</table>";

    return [
        'raw' => "{$yes}||{$no}",
        'yes' => $yes,
        'no' => $no,
        'yes_pct' => $yesPct,
        'no_pct' => $noPct,
        'updated' => $updated,
        'html' => $html,
    ];
};

$tmpFile = tempnam(sys_get_temp_dir(), 'poll_res_');
if ($tmpFile === false) {
    throw new RuntimeException('Failed to create temp file');
}

try {
    // Case 1: Start from "3||4", vote Yes (0) -> "4||4" (50/50), then vote No (1) -> "4||5" (44/56)
    file_put_contents($tmpFile, '3||4');
    $r1 = $castVote($tmpFile, '0');
    $r2 = $castVote($tmpFile, '1');
    add_case(
        $cases,
        'poll_vote_yes_and_no_increment',
        [
            'after_yes' => ['raw' => '4||4', 'yes_pct' => 50, 'no_pct' => 50],
            'after_no' => ['raw' => '4||5', 'yes_pct' => 44, 'no_pct' => 56],
        ],
        [
            'after_yes' => ['raw' => $r1['raw'], 'yes_pct' => $r1['yes_pct'], 'no_pct' => $r1['no_pct']],
            'after_no' => ['raw' => $r2['raw'], 'yes_pct' => $r2['yes_pct'], 'no_pct' => $r2['no_pct']],
        ]
    );

    // Case 2: Initial "0||0" with vote Yes (0) -> "1||0" (100% / 0%) and zero-total guard
    file_put_contents($tmpFile, '0||0');
    $zeroRead = $castVote($tmpFile, '');
    $firstVote = $castVote($tmpFile, '0');
    add_case(
        $cases,
        'poll_initial_zero_votes_guard',
        [
            'zero_total_pct' => [0, 0],
            'first_yes' => ['raw' => '1||0', 'yes_pct' => 100, 'no_pct' => 0],
        ],
        [
            'zero_total_pct' => [$zeroRead['yes_pct'], $zeroRead['no_pct']],
            'first_yes' => ['raw' => $firstVote['raw'], 'yes_pct' => $firstVote['yes_pct'], 'no_pct' => $firstVote['no_pct']],
        ]
    );

    // Case 3: Invalid vote parameters ignored without corrupting poll_result.txt
    file_put_contents($tmpFile, '3||4');
    $inv1 = $castVote($tmpFile, '2');
    $inv2 = $castVote($tmpFile, '<script>');
    add_case(
        $cases,
        'poll_invalid_vote_ignored',
        ['updated_2' => false, 'updated_xss' => false, 'persisted' => '3||4'],
        ['updated_2' => $inv1['updated'], 'updated_xss' => $inv2['updated'], 'persisted' => trim((string) file_get_contents($tmpFile))]
    );

    // Case 4: Rendered HTML progress bars match computed percentages
    add_case(
        $cases,
        'poll_html_bar_width_rendering',
        [
            'has_green_44px' => true,
            'has_red_56px' => true,
            'has_56_pct' => true,
        ],
        [
            'has_green_44px' => str_contains($r2['html'], 'background-color:green; width:44px;'),
            'has_red_56px' => str_contains($r2['html'], 'background-color:red; width:56px;'),
            'has_56_pct' => str_contains($r2['html'], '56%'),
        ]
    );
} finally {
    if (is_file($tmpFile)) {
        unlink($tmpFile);
    }
}

echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
预期结果 · 待实际运行核验
  • 验证 3||4 依次投是/否变为 4||4(50%/50%) 与 4||5(44%/56%)、0||0 防除零、非法参数不篡改文件以及绿 44px/红 56px 表格输出。
运行 PHP 8.4 加锁投票计数、零票防护、非法值过滤与进度条宽度实测

所需环境:Windows x64、PHP 8.4 本地 CLI 环境。

当前源码 SHA256:4873d3155f0c41c316d3dbba479b7c61a79670c0792d81429628df1e0ba98b98

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载AJAX 投票实验

所需环境:Windows x64、PHP 8.4 本地 CLI 环境。

ZIP SHA256:0a15ff3ab574680e4ec3de001676cf1478f5c2fb5f2752ab0d1e8f033087a3f7

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

多用户同时点击投票时,直接用 file() 读取再用 fopen(..., 'w') 写回 poll_result.txt 会出现什么问题?如何解决?

展开参考解答

不加锁的先读后写会产生竞态条件(race condition),后写入的进程可能覆盖先写入的票数甚至把文件截断为空;应以读写模式打开并配合 flock($fp, LOCK_EX) 加独占锁,或改用数据库原子自增(UPDATE ... SET count = count + 1)。

规范与官方依据