Masoud Haghbin
Masoud Haghbin

Reputation: 883

hashing content of uploaded file in php

I have a upload form and also a Dropzone file uploader beside it where users can upload their .csv files .

I want to check whether the file is new or not. the check should contain if the contents of file are new or not

I store the file names in database for checking new files, but the problem is when the user rename the same file and upload it again.

My solution is hashing the content of each file and store it beside its name in database.

but I don't know how to hash content of .csv file in php , Laravel. I've tried using

hash_file('md5' , Request::file('myFileName')->getClientOriginalName());

but it results in file or stream not found.

What is the correct way of checking the new file regardless of its name?

Thanks in advance.

Upvotes: 4

Views: 3802

Answers (1)

Bostjan
Bostjan

Reputation: 814

Calculating hash of a file is a correct way to go.

Do something like this:

public function uploadFile() {
    // check if upload is valid file (example: request()->file('myFileName')->isValid() )

    // calculate hash of a file
    $fileHash = sha1_file( request()->file('myFileName')->path() );

    //search for file in database and block same file upload (Files is Elequent model)
    if( Files::where('hash', $fileHash)->firstOrNull() != null) {
        abort(400); // abort upload
    }

    // do something with file and save hash to DB
}

Upvotes: 3

Related Questions