Skip to content
Advertisement

How to calculate MD5 for a file using PHP before uploading to Google Cloud

I am using the code example found at https://zatackcoder.com/upload-file-to-google-cloud-storage-using-php/ to upload a file to Google Cloud. Everything works fine (I am new to this so I’m just psyched to have it running!), but I recently read a blurb where you can tell Google Cloud what the md5 of the file you are uploading is, and Google will validate that against the actual upload and will fail the upload if there is a transmission problem resulting in a different md5.

My question is 2 part:

  1. How to calculate the md5 in a format that Google Cloud will understand? I believe the calculation is actually the base64_encode() of the md5 returned from PHP’s file_md5() but when I do this the resulting string is actually quite a bit different from the resulting “md5Hash”: “TPmaCjp5uh1jxIQahhOAsQ==” that is returned from Google. I am using the Google Cloud STORAGE API to perform the upload (see link above and minor code snippet below).

  2. Once I have the properly calculated md5Hash, how do I specify that in the upload() function to pass that value as part of the upload? Has anyone done this and can share their expertise?

Many thanks!

Here is the snippet from the larger project in the link above. The upload works fine, I am just looking for how to generate the appropriate md5Hash and to include that hash in the upload.

function uploadFile($bucketName, $fileContent, $cloudPath) {
    $privateKeyFileContent = $GLOBALS['privateKeyFileContent'];
    // connect to Google Cloud Storage using private key as authentication
    try {
        $storage = new StorageClient([
            'keyFile' => json_decode($privateKeyFileContent, true)
        ]);
    } catch (Exception $e) {
        // maybe invalid private key ?
        print $e;
        return false;
    }

    // set which bucket to work in
    $bucket = $storage->bucket($bucketName);

    // upload/replace file 
    $storageObject = $bucket->upload(
            $fileContent,
            ['name' => $cloudPath]
            // if $cloudPath is existed then will be overwrite without confirmation
            // NOTE: 
            // a. do not put prefix '/', '/' is a separate folder name  !!
            // b. private key MUST have 'storage.objects.delete' permission if want to replace file !
    );

    // is it succeed ?
    return $storageObject != null;
}

Advertisement

Answer

According to the PHP client library for Cloud Storage documentation, in the upload method for the StorageObject object you can specify a metadata parameter.

This parameter is an array that allows you to pass the md5Hash. The full list of propierties that you can pass is stated here.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement