PHP code example of bahirul / yii2-simple-s3

1. Go to this page and download the library: Download bahirul/yii2-simple-s3 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/ */

    

bahirul / yii2-simple-s3 example snippets


return [
    //...
    'components' => [
        //...
        's3' => [
            'class' => 'bahirul\yii2\SimpleS3',
            'endpoint' => 'YOUR_S3_URL',
            'key'    => 'YOUR_S3_KEY',
            'secret' => 'YOUR_S3_SECRET',
            'bucket' => 'YOUR_S3_BUCKET',
            //'region' => 'YOUR_S3_REGION', // Optional
            //'version' => 'YOUR_S3_VERSION', // Optional
        ],
    ],
];

// s3 custom init
$s3 = Yii::$app->s3;

// your requested file
$fileRequest = 'example_file_image.jpg';

// read file on S3
$readFile = $s3->readFile($fileRequest);

// init web response
$response = Yii::$app->response;
$response->headers->set('Content-Type', $readFile['mimetype']);
$response->format = \yii\web\Response::FORMAT_RAW;
$response->stream = $readFile['stream'];

return $response->send();

// s3 custom init
$s3 = Yii::$app->s3;

// your requested file
$fileRequest = 'example_file_image.jpg';

// read file on S3
$readFile = $s3->readFile($fileRequest);

// init web response
$response = Yii::$app->response;

return $response->sendStreamAsFile($readFile['stream'], $fileRequest ,['mimeType' => $readFile['mimetype']]);

// your file upload instance
$fileModel = UploadedFile::getInstance($model, 'attributeName');

$s3 = Yii::$app->s3;

// generate random filename
$filename = time() . '.jpg';

if($model->load($post) && $model->validate()){
    // upload file to s3
    $s3->writeFile($fileModel, $filename);
}

$s3 = Yii::$app->s3;

$fileRequest = 'example_file_image.jpg';

$s3->deleteFile($fileRequest);