我正在尝试在php中使用bucket作为冲突解决技术来实现哈希.我正在尝试将散列后的数据插入到文本文件中



在这段代码中,我正在创建一个哈希函数,并尝试使用bucket来解决冲突。我把水桶的尺寸定为3号。我正在尝试将散列后的值插入到文本文件中。插入正在进行,但冲突尚未解决。

<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'];
$i_name=$_POST['Item_name'];
$quan=$_POST['Quantity'];
$price=$_POST['Price'];
$file=fopen("Item.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."_";
}
$pos=hash_fun($id);
fseek($file,$pos,0);
$line=fgets($file);
$cnt=intval($line[0]);
if($cnt==3){
echo "Max collision 3";
}
if($cnt==0){
fseek($file,$pos,0);
fwrite($file,'1');
$pos=$pos+1;
}
else if($cnt==1){
fseek($file,$pos,0);
fwrite($file,'2');
$pos=$pos+48;
}
else if($cnt==2){
fseek($file,$pos,0);
fwrite($file,'3');
$pos=$pos+95;
}
fseek($file,$pos,0);
fwrite($file,$rec);
fwrite($file,"n");
fclose($file);
}
?>
</body>
</html>

总之,我已经将上下文放入一个名为Menu.txt的文本文件中,并且我正在使用bucket实现哈希。但冲突没有得到解决,但插入正在发生。

这里有几个东西:

  1. 创建一个安全的哈希函数真的很难
  2. 使用分隔符进行序列化是不安全的$rec=$id."|".$i_name."|".$quan."|".$price。如果名称包含管道字符怎么办
  3. 为了避免竞争条件,需要原子操作。如果两个请求或多或少同时尝试处理同一个散列,那么两个请求都会成功。数据库将为此提供机制,但您也可以使用文件系统。例如,制作目录是原子操作,如果多个进程试图创建一个,那么只有一个会成功
  4. 净化用户输入。如果用户发送换行字符或大量有效载荷,该怎么办

总之,请不要为了用户的利益在生产中使用该代码。

最新更新