Home >Backend Development >PHP Tutorial >PHP performs hash operation on files

PHP performs hash operation on files

WBOY
WBOYOriginal
2016-07-25 08:43:181043browse

This code is very useful. If you download a file and the website provides a hash result, you can perform a hash operation on the file you downloaded to verify whether the downloaded file is correct.

  1. Hash (Check) Files
  2. if(!empty($_FILES)){
  3. if ($_FILES["file"]["error"] > 0){
  4. switch($_FILES["file"]["error"]){
  5. case 1:
  6. echo "Error: The uploaded file exceeds the upload_max_filesize directive in php.ini
    ";
  7. break;
  8. case 2:
  9. echo "Error: The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
    ";
  10. break;
  11. case 3:
  12. echo "Error: The uploaded file was only partially uploaded.
    ";
  13. break;
  14. case 4:
  15. echo "Error: No file was uploaded.
    ";
  16. break;
  17. case 6:
  18. echo "Error: Missing a temporary folder.
    ";
  19. break;
  20. case 7:
  21. echo "Error: Failed to write file to disk.
    ";
  22. break;
  23. case 8:
  24. echo "Error: A PHP extension stopped the file upload.
    ";
  25. break;
  26. default:
  27. echo "Unknown error occured.
    ";
  28. }
  29. } else {
  30. echo 'Upload: ' . $_FILES['file']['name'] . '
    ';
  31. echo 'Type: ' . $_FILES['file']['type'] . '
    ';
  32. echo 'Size: ' . (round($_FILES['file']['size'] / 1024, 2)) . ' Kb

    ';
  33. if(array_search($_POST['algo'], hash_algos())===false){
  34. echo 'Unknown hashing algorithm requested.
    ';
  35. } else {
  36. echo 'Hashing Algorithm: '. $_POST['algo'] . '
    ';
  37. $hash = hash_file($_POST['algo'], $_FILES['file']['tmp_name']);
  38. echo 'Calculated hash: ' . $hash . '
    ';
  39. if($_POST['exphash']!=='none' && !empty($_POST['exphash'])){
  40. echo 'Expected hash:   ' . $_POST['exphash'] . '

    ';
  41. echo ($hash==$_POST['exphash'])? 'Hash matched expected value.' : 'Hash did not match expected value.';
  42. echo '
    ';
  43. }
  44. }
  45. }
  46. ?>

  47. }else {
  48. ?>



  49. Choose an algorithm (This is the list of all the available algorithms in your php installation)
  50. foreach(hash_algos() as $algo){
  51. if($algo=='md5'){
  52. echo "
    ";
  53. } else {
  54. echo "
    ";
  55. }
  56. }
  57. ?>
  58. }
  59. ?>
复制代码

php, hash


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn