蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PHPWindows x64、PHP 8.4 本地 CLI 环境。explore-ajax-poll.php
explore-ajax-poll.php138 行
<?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";
本例需在 Windows x64、PHP 8.4 本地 CLI 环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、PHP 8.4 本地 CLI 环境。

入口文件:projects/php-ajax-poll-lab/explore-ajax-poll.php

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-ajax-poll.php,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、PHP 8.4 本地 CLI 环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PHP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1226.zip

下载课程关联工程包:PHP

课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习