Programmatically using file hash to compare an external (temp) file (documentation)

Created on 25 June 2024, 2 months ago
Updated 10 July 2024, about 2 months ago

Problem/Motivation

What would I need to do if I wanted to programatically check the checksum of a temporary file (before attempting to add it to files). Basically I need to check if an image is identical before replacing the managed file. Any help much appreciated.

Also thanks for a great module.

πŸ’¬ Support request
Status

Fixed

Version

3.0

Component

Documentation

Created by

πŸ‡¬πŸ‡§United Kingdom mistergroove

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @mistergroove
  • Status changed to Fixed 2 months ago
  • πŸ‡ΊπŸ‡ΈUnited States mfb San Francisco

    something like this should work?

    $file = \Drupal\file\Entity\File::create(['uri' => 'temporary://my-image.png']);
    $violations = \Drupal::service('file.validator')->validate($file, ['FileHashDedupe' => []]);
    
  • πŸ‡¬πŸ‡§United Kingdom mistergroove

    Great. Thanks @mbf I'll give that a go and report back.

  • πŸ‡¬πŸ‡§United Kingdom mistergroove

    OK well that worked great to know it's a duplicated file.. I need to get the file id of the 'already uploaded' file... is there currently a way to just get a list id's of the duplicate existing files?

    Or would the only way be to parse the -messageTemplate field?

    Symfony\Component\Validator\ConstraintViolationList {#1284 β–Ό
      -violations: array:1 [β–Ό
        0 => 
    Symfony\Component\Validator
    \
    ConstraintViolation {#1596 β–Ό
          -message: 
    Drupal\Core\StringTranslation
    \
    TranslatableMarkup {#1594 β–Ά}
          -messageTemplate: "This file has already been uploaded as <em class="placeholder"><a href="/admin/content/files/usage/171" target="_blank">17238.jpg</a></em>."
          -parameters: []
          -plural: null
          -root: 
    Drupal\Core\Entity\Plugin\DataType
    \
    EntityAdapter {#671 β–Ά}
          -propertyPath: ""
          -invalidValue: 
    Drupal\file\Entity
    \
    File {#1033 β–Ά}
          -constraint: 
    Drupal\filehash\Plugin\Validation\Constraint
    \
    FileHashDedupe {#1494 β–Ά}
          -code: null
          -cause: null
        }
      ]
    }
    
  • πŸ‡ΊπŸ‡ΈUnited States mfb San Francisco

    Howabout calling the File Hash duplicateLookup() method directly?

    $fid = \Drupal::service('filehash')->duplicateLookup('sha256', $file);
    

    You'll need to replace 'sha256' with whatever hash algorithm you've enabled.

  • πŸ‡¬πŸ‡§United Kingdom mistergroove

    Works perfectly. Thanks so much.

    • mfb β†’ committed fc499be7 on 3.x
      Issue #3457133 by mfb, mistergroove: Programatically using file hash to...
  • πŸ‡ΊπŸ‡ΈUnited States mfb San Francisco
  • Automatically closed - issue fixed for 2 weeks with no activity.

Production build 0.71.5 2024