PHP code example of hernol / uploadthing-php

1. Go to this page and download the library: Download hernol/uploadthing-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/ */

    

hernol / uploadthing-php example snippets




use UploadThing\Resources\Uploads;

$uploads = new Uploads();
$file = $uploads->uploadFile('/path/to/file.jpg');

if ($file) {
    echo "File uploaded: {$file->name}\n";
    echo "File URL: {$file->url}\n";
    echo "File ID: {$file->id}\n";
}



use UploadThing\Resources\Uploads;

$uploads = new Uploads();
$file = $uploads->uploadFile(
    '/path/to/image.jpg',
    'my-custom-name.jpg',
    'image/jpeg'
);



use UploadThing\Resources\Webhooks;

$webhooks = new Webhooks();

// Handle webhook from Laravel request
$event = $webhooks->handleWebhook(
    $request->getContent(),
    $request->headers->all(),
    env('UPLOADTHING_WEBHOOK_SECRET')
);

echo "Event type: {$event->type}\n";
echo "Event data: " . json_encode($event->data) . "\n";



use UploadThing\Resources\Webhooks;

$webhooks = new Webhooks();
$event = $webhooks->handleWebhookFromGlobals(
    env('UPLOADTHING_WEBHOOK_SECRET')
);



use UploadThing\Exceptions\ApiException;
use UploadThing\Exceptions\AuthenticationException;
use UploadThing\Exceptions\RateLimitException;
use UploadThing\Exceptions\ValidationException;

try {
    $file = $uploads->uploadFile('/path/to/file.jpg');
} catch (AuthenticationException $e) {
    echo "Invalid API key: " . $e->getMessage();
} catch (RateLimitException $e) {
    echo "Rate limited, retry after: " . $e->getRetryAfter() . "s";
} catch (ValidationException $e) {
    echo "Validation error: " . $e->getMessage();
} catch (ApiException $e) {
    echo "API Error: " . $e->getMessage();
    echo "Error Code: " . $e->getErrorCode();
}



namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use UploadThing\Resources\Uploads;
use UploadThing\Resources\Webhooks;

class UploadThingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(Uploads::class, function () {
            return new Uploads();
        });

        $this->app->singleton(Webhooks::class, function () {
            return new Webhooks();
        });
    }
}



namespace App\Http\Controllers;

use UploadThing\Resources\Uploads;
use Illuminate\Http\Request;

class FileController extends Controller
{
    public function upload(Request $request, Uploads $uploads)
    {
        $file = $request->file('file');
        $uploaded = $uploads->uploadFile(
            $file->getPathname(),
            $file->getClientOriginalName(),
            $file->getMimeType()
        );

        return response()->json(['file' => $uploaded]);
    }
}
bash
composer