php对文件进行hash运算的方法
本文实例讲述了php对文件进行hash运算的方法。分享给大家供大家参考。具体如下:
这段代码非常有用,如果你下载了一个文件,网站提供了hash结果,你可以对你下载下来的文件进行hash运算,以验证下载的文件是否正确。
<html> <head> <title>Hash(Check)Files</title> <styletype='text/css'> #ok{color:green;} #nono{color:red;} </style> </head> <body> <?php if(!empty($_FILES)){ if($_FILES["file"]["error"]>0){ switch($_FILES["file"]["error"]){ case1: echo"<bid='nono'>Error:Theuploadedfileexceedstheupload_max_filesizedirectiveinphp.ini</b><br>"; break; case2: echo"<bid='nono'>Error:TheuploadedfileexceedstheMAX_FILE_SIZEdirectivethatwasspecifiedintheHTMLform.</b><br>"; break; case3: echo"<bid='nono'>Error:Theuploadedfilewasonlypartiallyuploaded.</b><br>"; break; case4: echo"<bid='nono'>Error:Nofilewasuploaded.</b><br>"; break; case6: echo"<bid='nono'>Error:Missingatemporaryfolder.</b><br>"; break; case7: echo"<bid='nono'>Error:Failedtowritefiletodisk.</b><br>"; break; case8: echo"<bid='nono'>Error:APHPextensionstoppedthefileupload.</b><br>"; break; default: echo"<bid='nono'>Unknownerroroccured.</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'Unknownhashingalgorithmrequested.<br>'; }else{ echo'HashingAlgorithm:'.$_POST['algo'].'<br>'; $hash=hash_file($_POST['algo'],$_FILES['file']['tmp_name']); echo'Calculatedhash:'.$hash.'<br>'; if($_POST['exphash']!=='none'&&!empty($_POST['exphash'])){ echo'Expectedhash: '.$_POST['exphash'].'<br><br>'; echo($hash==$_POST['exphash'])?'<bid="ok">Hashmatchedexpectedvalue.</b>':'<bid="nono">Hashdidnotmatchexpectedvalue.</b>'; echo'<br>'; } } } ?> <br> <buttononClick="document.location.reload(true)">Again</button> <?php }else{ ?> <formaction=""method="post"enctype="multipart/form-data"> <inputtype="hidden"name="exphash"value="none"> <labelfor="file">Filename:</label> <inputtype="file"name="file"id="file"> <inputtype="submit"name="submit"value="Submit"/><br> <label>Expectedhash(optional):<inputtype="text"name="exphash"size="100"></label> <br><br>Chooseanalgorithm(Thisisthelistofalltheavailablealgorithmsinyourphpinstallation)<br> <?php foreach(hash_algos()as$algo){ if($algo=='md5'){ echo"<label><inputtype='radio'name='algo'value='$algo'checked='checked'>$algo</label><br>"; }else{ echo"<label><inputtype='radio'name='algo'value='$algo'>$algo</label><br>"; } } ?> </form> <?php } ?> </body> </html>
希望本文所述对大家的php程序设计有所帮助。