First, we need to install aws-sdk for PHP in the CakePHP project. To install it we can run the below command:
composer require aws/aws-sdk-php
Code to upload a file:
Template Code:
<?= $this->Form->create($product, ['enctype' => 'multipart/form-data']) ?>
<fieldset>
<legend>= __('Add Product') ?></legend>
<?php
echo $this->Form->control('name');
echo $this->Form->control('file_url', ['type' => 'file']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
Controller Code:
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
public function uploadFile() {
if ($this->request->is('post')) {
$s3Client = new S3Client([
'credentials' => [
'key' => env('AWS_ACCESS_KEY_ID', ''),
'secret' => env('AWS_SECRET_ACCESS_KEY', ''),
],
'region' => 'ap-south-1',
'version' => 'latest'
]);
if (!empty($_FILES['file_url']['name'])) {
$upload = $s3Client->upload('jutties', $_FILES['file_url']['name'], fopen($_FILES['img_url']['tmp_name'], 'r+'), 'public-read');
$s3FileUrl = $upload->get('ObjectURL');
}
}
}