本文实例讲述了php对文件进行hash运算的方法。分享给大家供大家参考。具体如下:
这段代码非常有用,如果你下载了一个文件,网站提供了hash结果,你可以对你下载下来的文件进行hash运算,以验证下载的文件是否正确。
<html>
<head>
<title>hash (check) files</title>
<style type='text/css'>
#ok{color:green;}
#nono{color:red;}
</style>
</head>
<body>
<?php
if(!empty($_files)){
if ($_files["file"]["error"] > 0){
switch($_files["file"]["error"]){
case 1:
echo "<b id='nono'>error: the uploaded file exceeds the upload_max_filesize directive in php.ini</b><br>";
break;
case 2:
echo "<b id='nono'>error: the uploaded file exceeds the max_file_size directive that was specified in the html form.</b><br>";
break;
case 3:
echo "<b id='nono'>error: the uploaded file was only partially uploaded.</b><br>";
break;
case 4:
echo "<b id='nono'>error: no file was uploaded.</b><br>";
break;
case 6:
echo "<b id='nono'>error: missing a temporary folder.</b><br>";
break;
case 7:
echo "<b id='nono'>error: failed to write file to disk.</b><br>";
break;
case 8:
echo "<b id='nono'>error: a php extension stopped the file upload.</b><br>";
break;
default:
echo "<b id='nono'>unknown error occured.</b><br>";
}
} else {
echo 'upload: ' . $_files['file']['name'] . '<br>';
echo 'type: ' . $_files['file']['type'] . '<br>';
echo 'size: ' . (round($_files['file']['size'] / 1024, 2)) . ' kb<br><br>';
if(array_search($_post['algo'], hash_algos())===false){
echo 'unknown hashing algorithm requested.<br>';
} else {
echo 'hashing algorithm: '. $_post['algo'] . '<br>';
$hash = hash_file($_post['algo'], $_files['file']['tmp_name']);
echo 'calculated hash: ' . $hash . '<br>';
if($_post['exphash']!=='none' && !empty($_post['exphash'])){
echo 'expected hash: ' . $_post['exphash'] . '<br><br>';
echo ($hash==$_post['exphash'])? '<b id="ok">hash matched expected value.</b>' : '<b id="nono">hash did not match expected value.</b>';
echo '<br>';
}
}
}
?>
<br>
<button onclick="document.location.reload(true)">again</button>
<?php
} else {
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="exphash" value="none">
<label for="file">filename:</label>
<input type="file" name="file" id="file">
<input type="submit" name="submit" value="submit" /><br>
<label>expected hash(optional): <input type="text" name="exphash" size="100"></label>
<br><br>choose an algorithm (this is the list of all the available algorithms in your php installation)<br>
<?php
foreach(hash_algos() as $algo){
if($algo=='md5'){
echo "<label><input type='radio' name='algo' value='$algo' checked='checked'>$algo</label><br>";
} else {
echo "<label><input type='radio' name='algo' value='$algo'>$algo</label><br>";
}
}
?>
</form>
<?php
}
?>
</body>
</html>
希望本文所述对大家的php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!