PHP code example of filehutch / filehutch-php

1. Go to this page and download the library: Download filehutch/filehutch-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

filehutch / filehutch-php example snippets


use FileHutch\Client;

$hutch = new Client(apiKey: getenv('FILE_HUTCH_API_KEY'));

$file = $hutch->upload(fopen('me.png', 'rb'), policy: 'avatars', filename: 'me.png');

// An MD5 goes with the request, so FileHutch refuses the upload if what arrives is
// not what left. It is read in chunks, so the file is never held in memory to digest
// it. Pass `verify: false` to skip it and check only the byte count.
$file->id;                   // "file_8fK2…"  ← the only thing you store
$file->transforms['avatar']; // a 200×200 URL, if the project defines "avatar"

$hutch = new Client(apiKey: $key, url: $url, timeout: 30, httpClient: $psr18, userAgent: 'acme/2.0');

$hutch->project();                        // storage status, policies, transforms
$hutch->transforms();                     // the project's named image sizes
$hutch->file('file_…');
$hutch->signedUrl('file_…', expiresIn: 3600, disposition: 'attachment');
$hutch->transformUrl('file_…', 'avatar', expiresIn: 600);
$hutch->deleteFile('file_…');             // true; the id then reads as status "deleted"

// One call: request, PUT to storage, complete.
$hutch->upload($source, policy: 'documents', filename: 'report.pdf', metadata: ['order_id' => 'ord_1']);

// Or the three steps, explicit:
$created = $hutch->createUpload(policy: 'avatars', filename: 'me.png', contentType: 'image/png', byteSize: strlen($bytes));
$hutch->putToStorage($created->upload, $bytes);
$ready = $hutch->completeUpload($created->upload->fileId);

$file = $hutch->file($id);
$file->transforms['avatar'];                 // public images: already on the payload
$hutch->transformUrl($id, 'avatar')->url;    // private images: signed, expires

use FileHutch\Laravel\Facades\FileHutch;

FileHutch::upload($request->file('report'), policy: 'documents');
app(FileHutch\Client::class)->project();   // or inject FileHutch\Client anywhere

Schema::table('users', fn (Blueprint $table) => $table->string('avatar_file_id')->nullable());

use FileHutch\Laravel\HasHutch;

class User extends Model
{
    use HasHutch;

    protected function hutches(): array
    {
        return [
            'avatar' => 'avatars',
            'contract' => ['policy' => 'documents', 'dependent' => false],
        ];
    }
}

$user->avatar = $request->file('avatar');  // uploaded file → uploaded to storage on save
$user->avatar = 'file_…';                  // id from a browser direct upload → verified on save
$user->avatar;                             // FileHutch\Resources\File or null (fetched lazily, cached)
$user->hutchAttached('avatar');            // id present, no request
$user->avatar_url;                         // public URL (public policies only)
$user->avatarSignedUrl(expiresIn: 600);    // any file
$user->avatarTransformUrl('thumb');        // a named transform
$user->purgeAvatar();                      // delete remotely, clear the column

use FileHutch\Laravel\DirectUploads;
use Illuminate\Http\Request;

DirectUploads::authorize(fn (Request $request, string $policy) =>
    $request->user() !== null && in_array($policy, ['avatars', 'documents'], true));

if ($request->filled('avatar')) {
    $request->user()->update(['avatar' => $request->input('avatar')]);
}

$config = $hutch->config();
$config['uploads']['exports'] = ['types' => ['text/csv'], 'max_size' => '1MB'];

$plan = $hutch->planConfig($config);            // a read-only key can do this
$result = $hutch->applyConfig($config);         // needs a write key; prune: true also deletes

use FileHutch\Exceptions\SignatureVerificationError;
use FileHutch\Webhook;

Route::post('/webhooks/filehutch', function (Request $request) {
    try {
        $event = Webhook::constructEvent(
            $request->getContent(), $request->header('FileHutch-Signature'), config('filehutch.webhook_secret'),
        );
    } catch (SignatureVerificationError) {
        abort(400);
    }

    if ($event['type'] === 'file.deleted') {
        User::where('avatar_file_id', $event['data']['file']['id'])->update(['avatar_file_id' => null]);
    }

    return response()->noContent();
})->withoutMiddleware(\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class);

use FileHutch\Exceptions\PolicyError;

try {
    $hutch->upload($bytes, policy: 'avatars', filename: 'huge.png');
} catch (PolicyError $e) {
    return response()->json(['message' => $e->getMessage()], 422);
}
sh
php artisan vendor:publish --tag=filehutch-config
blade
<meta name="csrf-token" content="{{ csrf_token() }}">

<form action="{{ route('profile.update') }}" method="post">
  @csrf
  <filehutch-upload policy="avatars" name="avatar" accept="image/*"></filehutch-upload>
  <button>Save</button>
</form>