You need to enable JavaScript to run this app. PHP实现哈希桶碰撞解决并写入文本文件故障排查
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现哈希桶碰撞解决并写入文本文件故障排查

PHP固定容量桶哈希存储代码修复

现有代码问题列表

  • 文件名配置错误:当前打开的是Item.txt,不符合需求要求的Menu.txt
  • 空桶初始读取异常:首次写入对应哈希桶时,fgets()读取的是空内容,intval($line[0])转换后得到的值不可控,导致计数逻辑失效
  • 桶内偏移量计算错误:单条记录填充后长度为46字节,加上换行符共47字节,原代码偏移量+48、+95与实际存储长度不匹配,会出现写入内容覆盖问题
  • 桶满未终止写入:当桶计数为3时仅输出提示,没有跳出逻辑,仍会执行后续写入操作,覆盖已有有效数据
  • 哈希函数有强限制:要求传入的ID长度至少为6位,否则取下标3/4/5的字符会失败,哈希计算结果异常

修复后完整代码

<html>
<head>
<title>FOOD DELIVERY</title>
</head>
<body>
<form id="insert_item" action="hash_insert.php" method="post">
ID:<input type="text" name="id"><br><br>
Item Name:<input type="text" name="Item_name"><br><br>
Quantity:<input type="text" name="Quantity"><br><br>
Price:<input type="text" name="Price"><br><br>
<input type="submit">
</form>
<br>
<?php
if(isset($_POST['id'])&&isset($_POST['Item_name'])&&isset($_POST['Quantity'])&&isset($_POST['Price'])){
    $id=$_POST['id'];
    // 增加ID长度校验,避免哈希函数报错
    if(strlen($id) < 6){
        echo "ID长度不能小于6位";
        exit;
    }
    $i_name=$_POST['Item_name'];
    $quan=$_POST['Quantity'];
    $price=$_POST['Price'];
    // 修改文件名为需求指定的Menu.txt
    $file=fopen("Menu.txt","a+");

    function hash_fun($i){
        $t=((($i[3]-48)*100)+(($i[4]-48)*10)+($i[5]-48))%9;
        return $t*142;
    }

    $rec=$id."|".$i_name."|".$quan."|".$price;

    while(strlen($rec)<46){
        $rec=$rec."_";
    }
    // 记录加换行总长度固定为47字节
    $rec .= "\n";

    $pos=hash_fun($id);

    fseek($file,$pos,0);
    $cnt_char = fgetc($file);
    // 空桶默认计数为0
    $cnt = $cnt_char === false ? 0 : intval($cnt_char);

    if($cnt==3){
        echo "Max collision 3";
        fclose($file);
        // 桶满直接终止写入
        exit;
    }

    // 更新桶计数
    fseek($file,$pos,0);
    fwrite($file, strval($cnt+1));

    // 按实际存储长度计算偏移:计数位占1字节,每条记录占47字节
    $pos = $pos + 1 + 47 * $cnt;

    fseek($file,$pos,0);
    fwrite($file,$rec);
    fclose($file);
}
?>

</body>
</html>

内容的提问来源于stack exchange,提问作者Nirmala Shankar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 14:45:03