PHP Doku:: Berechnet den SHA1-Hash einer Datei - function.sha1-file.html

Verlauf / Chronik / History: (17) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzTextverarbeitungZeichenkettenString-Funktionensha1_file

Ein Service von Reinhard Neidl - Webprogrammierung.

String-Funktionen

<<setlocale

sha1>>

sha1_file

(PHP 4 >= 4.3.0, PHP 5)

sha1_fileBerechnet den SHA1-Hash einer Datei

Beschreibung

string sha1_file ( string $filename [, bool $raw_output = false ] )

Berechnet den SHA1-Hash von filename unter Verwendung des » US Secure Hash Algorithmus 1 und gibt den Hashwert zurück. Der Hash ist ein 40 Zeichen langer Hexadezimalwert.

Parameter-Liste

filename

Der Dateiname

raw_output

Falls TRUE, wird der SHA1-Extrakt im Raw-Binary-Format mit einer Länge von 20 Zeichen zurückgegeben.

Rückgabewerte

Gibt bei Erfolg einen String zurück, ansonsten FALSE.

Beispiele

Beispiel #1 sha1_file()-Beispiel

<?php
foreach(glob('/home/kalle/meinprojekt/*.php') as $ent)
{
    if(
is_dir($ent))
    {
        continue;
    }

    echo 
$ent ' (SHA1: ' sha1_file($ent) . ')'PHP_EOL;
}
?>

Changelog

Version Beschreibung
5.0.0 Einführung des raw_output Parameters
5.1.0 Die Funktion verwendet jetzt die Streams API. Das bedeutet, dass Sie die Funktion mit Wrappern wie sha1_file('http://example.com/..') nutzen können.

Siehe auch

  • sha1() - Berechnet den SHA1-Hash eines Strings
  • md5_file() - Berechnet den MD5-Code einer Datei
  • crc32() - Berechnet den polynomischen CRC32-Wert eines Strings


5 BenutzerBeiträge:
- Beiträge aktualisieren...
Goodlookinguy at NRG's RPG dot com
26.11.2008 4:01
In php 5.1.2 and above, the alternative to using this could be this little bit I wrote.  It can be used for other hashes as well.

<?php
/*        $by   : Nicholas
        $date : 11/25/08
        $site : http://nrgsrpg.com
    $copyright: This can be redistributed at will.
*///    $des  : For Hashing Files in all sorts of ways
class hashing {
    public static function
filehash($file,$hash) {
        if (
file_exists($file)) {
            return
hash($hash,file_get_contents($file));
        }
        else {
            return
"Error Occurred: File Does Not Exist";
        }
    }
}

echo
hashing::filehash("index.php","sha1")."<br />";
echo
hashing::filehash("index.php","whirlpool")."<br />";
echo
hashing::filehash("index.php","sha512");
?>

Have fun!
vista_ at live dot se
23.11.2008 13:05
<?php
    
if(!function_exists('sha1_file'))
     {
          function
sha1_file($file = null)
          {
               if(
is_null($file) || !file_exists($file))
               {
                    return
trigger_error('File is null or does not exists');
               }

               return
sha1(file_get_contents($file));
          }
     }
?>

Remember, it's important to write a corret url like this:
/home/snackzon/public_html/php/sha1.php
schiros at invisihosting dot com
6.09.2007 16:02
If you've got a script that allows user file upload, and you want to prevent multiple uploads of the same file:

    <?
        session_start
();
       
$isDuplicate = false;
        if(isset(
$_FILES["filename"]["tmp_name"]) && file_exists($_FILES["filename"]["tmp_name"])) {
           
$fileHash = sha1_file($_FILES["filename"]["tmp_name"]);
            if(!isset(
$_SESSION["check_filelist"])) {
               
$_SESSION["check_filelist"] = array($fileHash);
            }
            elseif(
in_array($fileHash,$_SESSION["check_filelist"])) {
               
$isDuplicate = true;   
            }
            else {
               
$_SESSION["check_filelist"][] = $fileHash;   
            }
           
            if(
$isDuplicate) {
                echo
"You've already uploaded that file";   
            }
            else{
               
// do some stuff   
           
}
        }
       
   
?>
admin at cmsrevolution dot com
5.08.2006 5:02
checking the sha1 of the file. ideal for download scripts making sure the file the user is downloading is not currupt
by checking the sha1 key

<?php
$filename
= './Path/To/Your/File.zip';

if (
file_exists($filename)) {
echo
"i see the file";
} else {
echo
"recheck the link file maybe broken";
}
$file = sha1_file('./Path/To/Your/File.zip');

echo
"<br>is file hash valid?";
echo
"hash = add the hash here<br>";
echo
"hash of file :";
print(
$file);
?>
gubatron at gmail dot com
10.02.2006 16:02
P2P programs like LimeWire utilize sha1 to identify files. However they do it in base32. Here's an utility class if you want to write a Gnutella client in PHP5

/**
Utility base32 SHA1 class for PHP5
Copyright (C) 2006  Karl Magdsick (original author for Python)
                    Angel Leon (ported to PHP5)
                    Lime Wire LLC

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
class SHA1 {
  static $BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';

  /** Given a file it creates a magnetmix */
  static function fileSHA1($file) {
    $raw = sha1_file($file,true);
    return SHA1::base32encode($raw);
  } //fileSHA1

  /** Takes raw input and converts it to base32 */
  static function base32encode($input) {
    $output = '';
    $position = 0;
    $storedData = 0;
    $storedBitCount = 0;
    $index = 0;

    while ($index < strlen($input)) {
      $storedData <<= 8;
      $storedData += ord($input[$index]);
      $storedBitCount += 8;
      $index += 1;

      //take as much data as possible out of storedData
      while ($storedBitCount >= 5) {
        $storedBitCount -= 5;
        $output .= SHA1::$BASE32_ALPHABET[$storedData >> $storedBitCount];
        $storedData &= ((1 << $storedBitCount) - 1);
      }
    } //while

    //deal with leftover data
    if ($storedBitCount > 0) {
      $storedData <<= (5-$storedBitCount);
      $output .= SHA1::$BASE32_ALPHABET[$storedData];
    }

    return $output;
  } //base32encode

}



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)