Codeigniter 4 AWS S3 integration allows you to upload and manage files effortlessly using Amazon's cloud storage. In this tutorial, we'll show how to use AWS S3 Bucket in Codeigniter 4 to store and manage files effectively.
Table Of Content
1 Prerequisites
1.) PHP version of 8.2
2.) Composer
3.) AWS Account
2 Introduction
Typically, web applications store uploaded files on a local web server. However, you can upload files to Amazon S3 bucket folder in PHP Codeigniter 4 with the help of aws-sdk-php for more scalable, secure cloud storage
3 Create / Install a Codeigniter 4 Project
3.1 Install Codeigniter 4 Project
First, make sure your computer has a composer.
Use the following command to install new Codeigniter Project.
composer create-project codeigniter4/appstarter ci-4-amazon-s3-app
Then, navigate to your project directory:
cd ci-4-amazon-s3-app
When we install CodeIgniter 4, we will have env file at root. To use the environment variables, we need to rename
env to
.env
Also we can do this in command Line.
Open project in Command Line
sudo cp env .env
Above command will create a copy of
env file to
.env file. Now we are ready to set environment variables.
Configure Development Mode
CodeIgniter starts up in production mode by default. You need to make it in development mode to debug or check any error if you are working with application.
Open
.env file from root.
# CI_ENVIRONMENT = production
CI_ENVIRONMENT = development
Now application is in development mode.
4 Create / Login into AWS Account
You need to create or Login into
AWS account
After Sign into the account, In the top bar and Search for the S3 service and go to the S3 Management Console.
In S3 Management Console create a New Bucket to store files.
Get AWS Access Key ID and AWS Secret Access Key:
Search
"IAM Console" and go to the IAM Console.
From the left navigation menu, select Users under the Access management section.
Create a user with AmazonS3FullAccess permission.
Once User Created Succefully, the Access Key ID and Secret Access Key will be generated.
5 Install AWS SDK for PHP
First, make sure your computer has a composer.
Use the following command to install PHP AWS SDK.
composer require aws/aws-sdk-php
In the .env file, AWS configuration variables are defined.
AWS_ACCESS_KEY_ID=xxxxxx
AWS_SECRET_ACCESS_KEY=xxxxxx
AWS_ENDPOINT=xxxxxx
AWS_REGION=xxxxxx
AWS_BUCKET=xxxxxx
7 Create an S3 Service Class
This class interacts with S3 to upload images to S3 bucket Codeigniter 4. It handles uploading, downloading, and managing files within your application.
app/Services/S3Service.php
<?php
namespace App\Services;
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
class S3Service
{
protected $s3;
protected $bucket;
public function __construct()
{
$this->s3 = new S3Client([
'endpoint' => getenv('AWS_ENDPOINT'),
'version' => 'latest',
'region' => getenv('AWS_REGION'),
'credentials' => [
'key' => getenv('AWS_ACCESS_KEY_ID'),
'secret' => getenv('AWS_SECRET_ACCESS_KEY'),
],
]);
$this->bucket = getenv('AWS_BUCKET');
}
public function uploadFile($filePath, $key)
{
try {
$result = $this->s3->putObject([
'Bucket' => $this->bucket,
'Key' => $key,
'SourceFile' => $filePath,
'ACL' => 'private', // or other ACL as required
]);
return $result->get('ObjectURL');
} catch (AwsException $e) {
return $e->getMessage();
}
}
public function getFileUrl($key)
{
return $this->s3->getObjectUrl($this->bucket, $key);
}
public function listFiles()
{
$objects = $this->s3->getIterator('ListObjects', array(
'Bucket' => $this->bucket,
'Prefix' => ''
));
return $objects;
}
public function deleteFile($key)
{
try {
$this->s3->deleteObject([
'Bucket' => $this->bucket,
'Key' => $key,
]);
return true;
} catch (AwsException $e) {
return $e->getMessage();
}
}
}
?>
8 Create New Controller - UploadController
This controller will manage the upload and listing of files using Codeigniter AWS S3 integration library.
Use the following artisan command to Create Controller.
php spark make:controller UploadController
app/Controllers/UploadController.php
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Services\S3Service;
class UploadController extends BaseController
{
public function index()
{
return view('index');
}
public function upload()
{
$file = $this->request->getFile('file');
if ($file->isValid() && !$file->hasMoved()) {
$filePath = $file->getTempName();
$fileName = $file->getName();
$s3Service = new S3Service();
$fileUrl = $s3Service->uploadFile($filePath, $fileName);
// return $this->response->setJSON(['url' => $fileUrl]);
return redirect()->to('list')->with('message',' File Uploaded Successfully!');
}
return redirect()->to('list')->with('message','Invalid file');
}
public function list()
{
$s3Service = new S3Service();
$objects = $s3Service->listFiles();
$data['objects']=$objects;
return view('list',$data);
}
public function download($fileName)
{
$s3Service = new S3Service();
$fileUrl = $s3Service->getFileUrl($fileName);
return redirect()->to($fileUrl);
}
public function delete($fileName)
{
$s3Service = new S3Service();
$result = $s3Service->deleteFile($fileName);
if ($result === true) {
return $this->response->setJSON(['message' => 'File deleted successfully']);
}
return $this->response->setStatusCode(400)->setJSON(['error' => $result]);
}
}
?>
9 Create Index View File
Create View "index.php" File to Show Form
app/Views/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta http-equiv="Content-Security-Policy" content="default-src * self blob: data: gap:; style-src * self 'unsafe-inline' blob: data: gap:; script-src * 'self' 'unsafe-eval' 'unsafe-inline' blob: data: gap:; object-src * 'self' blob: data: gap:; img-src * self 'unsafe-inline' blob: data: gap:; connect-src self * 'unsafe-inline' blob: data: gap:; frame-src * self blob: data: gap:;">
<title>Codeigniter Posts | GetSampleCode.com</title>
<meta name="title" content="Codeigniter Posts | GetSampleCode.com">
<meta name="description" content="GetSampleCode.com provides Sample Code and tutorials for all web language and frameworks, PHP, Laravel, Codeigniter, API, MySQL, AJAX, jQuery">
<meta name="keywords" content="Programming Blog, Sample Web Development Code, PHP Code, CodeIgniter, Laravel 11, jQuery, MySQL, AJAX, bootstrap, HTML, CSS, JavaScript, Live Demo">
<meta name="robots" content="index, follow">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="language" content="English">
<link rel="canonical" href="https://getsamplecode.com/category/codeigniter">
<!-- Open Graph / Facebook Meta Tags -->
<meta property="og:type" content="website">
<meta property="og:url" content="https://www.getsamplecode.com">
<meta property="og:title" content="Codeigniter Posts | GetSampleCode.com">
<meta property="og:description" content="GetSampleCode.com provides Sample Code and tutorials for all web language and frameworks, PHP, Laravel, Codeigniter, API, MySQL, AJAX, jQuery">
<meta property="og:image" content="https://www.getsamplecode.com/get_sample_code_logo.jpg">
<!-- Twitter Meta Tags -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:url" content="https://www.getsamplecode.com">
<meta name="twitter:title" content="Codeigniter Posts | GetSampleCode.com">
<meta name="twitter:description" content="GetSampleCode.com provides Sample Code and tutorials for all web language and frameworks, PHP, Laravel, Codeigniter, API, MySQL, AJAX, jQuery">
<meta name="twitter:image" content="https://www.getsamplecode.com/get_sample_code_logo.jpg">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="icon" sizes="16x16" href="https://getsamplecode.com/fassets/img/fav_icon.png">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/bootstrap.min.css">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/line-awesome.css">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/style.css">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/custom.css">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/toc.css">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/prism/prism.css">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/folder.css">
<style>
.form--control
{
padding-left:15px;
}
</style>
</head>
<body>
<div class="preloader">
<div class="loader">
<svg class="spinner" viewBox="0 0 50 50">
<circle class="path" cx="25" cy="25" r="20" fill="none" stroke-width="5"></circle>
</svg>
</div>
</div>
<header class="header-menu-area bg-white">
<!-- end header-top -->
<div class="header-menu-content pr-150px pl-150px bg-white" style="padding:15px">
<div class="container-fluid">
<div class="main-menu-content">
<div class="row align-items-center">
<div class="col-lg-9">
<div class="logo-box">
<a href="https://getsamplecode.com" class="logo"><img src="https://getsamplecode.com/fassets/img/get_sample_code_logo.png" alt="logo"></a>
<div class="user-btn-action">
<div class="search-menu-toggle icon-element icon-element-sm shadow-sm mr-2" data-toggle="tooltip" data-placement="top" title="Search">
<i class="la la-search"></i>
</div>
<div class="off-canvas-menu-toggle main-menu-toggle icon-element icon-element-sm shadow-sm" data-toggle="tooltip" data-placement="top" title="Main menu">
<i class="la la-bars"></i>
</div>
</div>
</div>
</div><!-- end col-lg-2 -->
<!-- end col-lg-10 -->
</div><!-- end row -->
</div>
</div><!-- end container-fluid -->
</div><!-- end header-menu-content -->
<!-- end off-canvas-menu -->
<div class="body-overlay"></div>
</header><!-- end header-menu-area -->
<!--======================================
END HEADER AREA
======================================-->
<section class="breadcrumb-area pt-50px pb-50px bg-white pattern-bg">
<div class="container">
<div class="col-lg-12 me-auto">
<div class="breadcrumb-content">
<div class="section-heading">
<h2 class="section__title">
Live Demo: How to Use AWS S3 Bucket in Codeingiter 4 to Store and Manage files
</h2>
</div>
</div>
</div>
</div>
</section>
<section class="blog-area" style="padding-top:30px;">
<div class="container-fluid">
<!-- end filter-bar -->
<div class="row">
<div class="col-lg-3 mb-5"></div>
<div class="col-lg-6 mb-5">
<div class="card card-item">
<div class="card-body">
<form method="post" class="pt-4" action="<?php echo base_url();?>upload" enctype="multipart/form-data">
<div class="input-box">
<label class="label-text">Select File to Upload: </label>
<div class="form-group">
<input type="file" name="file" required>
</div>
</div>
<div class="btn-box" style="text-align:center">
<button class="btn theme-btn" type="submit" name="upload">Upload
</button>
</div>
</form>
</div>
</div>
</div>
<div class="col-lg-3 mb-5"></div>
</div>
</div>
</section>
<div class="toggle"></div>
<section class="footer-area bg-gray" style="background-color:#eee !important">
<div class="section-block"></div>
<div class="copyright-content" style="padding:10px">
<div class="container">
<div class="row align-items-center">
<div class="col-lg-6">
<p class="copy-desc">© 2024 Get Sample Code. All Rights Reserved. </p>
</div><!-- end col-lg-6 -->
<div class="col-lg-6">
<div class="d-flex flex-wrap align-items-center justify-content-end">
<ul class="generic-list-item d-flex flex-wrap align-items-center fs-14">
<li class="mr-3"><a href="https://getsamplecode.com/terms-and-conditions">Terms & Conditions</a></li>
<li class="mr-3"><a href="https://getsamplecode.com/privacy-policy">Privacy Policy</a></li>
<li class="mr-3"><a href="https://getsamplecode.com/disclaimer">Disclaimer</a></li>
</ul>
</div>
</div><!-- end col-lg-6 -->
</div><!-- end row -->
</div><!-- end container -->
</div><!-- end copyright-content -->
</section><!-- end footer-area -->
<div id="scroll-top">
<i class="la la-arrow-up" title="Go top"></i>
</div>
<script src="https://getsamplecode.com/fassets/js/jquery-3.4.1.min.js"></script>
<script src="https://getsamplecode.com/fassets/js/bootstrap.bundle.min.js"></script>
<script src="https://getsamplecode.com/fassets/js/jquery.lazy.min.js"></script>
<script src="https://getsamplecode.com/fassets/js/main.js"></script>
<script src="https://getsamplecode.com/fassets/js/prism/prism.js"></script>
<script src="https://getsamplecode.com/fassets/js/folder.js"></script>
</body>
</html>
10 Create List View File
Create View "list.php" File to Show Form
app/Views/list.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta http-equiv="Content-Security-Policy" content="default-src * self blob: data: gap:; style-src * self 'unsafe-inline' blob: data: gap:; script-src * 'self' 'unsafe-eval' 'unsafe-inline' blob: data: gap:; object-src * 'self' blob: data: gap:; img-src * self 'unsafe-inline' blob: data: gap:; connect-src self * 'unsafe-inline' blob: data: gap:; frame-src * self blob: data: gap:;">
<title>Codeigniter Posts | GetSampleCode.com</title>
<meta name="title" content="Codeigniter Posts | GetSampleCode.com">
<meta name="description" content="GetSampleCode.com provides Sample Code and tutorials for all web language and frameworks, PHP, Laravel, Codeigniter, API, MySQL, AJAX, jQuery">
<meta name="keywords" content="Programming Blog, Sample Web Development Code, PHP Code, CodeIgniter, Laravel 11, jQuery, MySQL, AJAX, bootstrap, HTML, CSS, JavaScript, Live Demo">
<meta name="robots" content="index, follow">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="language" content="English">
<link rel="canonical" href="https://getsamplecode.com/category/codeigniter">
<!-- Open Graph / Facebook Meta Tags -->
<meta property="og:type" content="website">
<meta property="og:url" content="https://www.getsamplecode.com">
<meta property="og:title" content="Codeigniter Posts | GetSampleCode.com">
<meta property="og:description" content="GetSampleCode.com provides Sample Code and tutorials for all web language and frameworks, PHP, Laravel, Codeigniter, API, MySQL, AJAX, jQuery">
<meta property="og:image" content="https://www.getsamplecode.com/get_sample_code_logo.jpg">
<!-- Twitter Meta Tags -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:url" content="https://www.getsamplecode.com">
<meta name="twitter:title" content="Codeigniter Posts | GetSampleCode.com">
<meta name="twitter:description" content="GetSampleCode.com provides Sample Code and tutorials for all web language and frameworks, PHP, Laravel, Codeigniter, API, MySQL, AJAX, jQuery">
<meta name="twitter:image" content="https://www.getsamplecode.com/get_sample_code_logo.jpg">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="icon" sizes="16x16" href="https://getsamplecode.com/fassets/img/fav_icon.png">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/bootstrap.min.css">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/line-awesome.css">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/style.css">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/custom.css">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/toc.css">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/prism/prism.css">
<link rel="stylesheet" href="https://getsamplecode.com/fassets/css/folder.css">
<style>
.form--control
{
padding-left:15px;
}
</style>
</head>
<body>
<div class="preloader">
<div class="loader">
<svg class="spinner" viewBox="0 0 50 50">
<circle class="path" cx="25" cy="25" r="20" fill="none" stroke-width="5"></circle>
</svg>
</div>
</div>
<header class="header-menu-area bg-white">
<!-- end header-top -->
<div class="header-menu-content pr-150px pl-150px bg-white" style="padding:15px">
<div class="container-fluid">
<div class="main-menu-content">
<div class="row align-items-center">
<div class="col-lg-9">
<div class="logo-box">
<a href="https://getsamplecode.com" class="logo"><img src="https://getsamplecode.com/fassets/img/get_sample_code_logo.png" alt="logo"></a>
<div class="user-btn-action">
<div class="search-menu-toggle icon-element icon-element-sm shadow-sm mr-2" data-toggle="tooltip" data-placement="top" title="Search">
<i class="la la-search"></i>
</div>
<div class="off-canvas-menu-toggle main-menu-toggle icon-element icon-element-sm shadow-sm" data-toggle="tooltip" data-placement="top" title="Main menu">
<i class="la la-bars"></i>
</div>
</div>
</div>
</div><!-- end col-lg-2 -->
<!-- end col-lg-10 -->
</div><!-- end row -->
</div>
</div><!-- end container-fluid -->
</div><!-- end header-menu-content -->
<!-- end off-canvas-menu -->
<div class="body-overlay"></div>
</header><!-- end header-menu-area -->
<!--======================================
END HEADER AREA
======================================-->
<section class="breadcrumb-area pt-50px pb-50px bg-white pattern-bg">
<div class="container">
<div class="col-lg-12 me-auto">
<div class="breadcrumb-content">
<div class="section-heading">
<h2 class="section__title">
Live Demo: How to Use AWS S3 Bucket in Codeingiter 4 to Store and Manage files
</h2>
</div>
</div>
</div>
</div>
</section>
<section class="blog-area" style="padding-top:30px;">
<div class="container-fluid">
<!-- end filter-bar -->
<div class="row">
<div class="col-lg-3 mb-5"></div>
<div class="col-lg-6 mb-5">
<div class="card card-item">
<div class="card-body">
<?php if (session()->getFlashdata('message')) : ?>
<div style="color: green;border: 2px green solid;text-align: center;padding: 5px;margin-bottom: 10px;">
File Uploaded Successfully!
</div>
<?php endif ?>
<table border="1px" class="table">
<thead>
<tr>
<th>Filename</th>
</tr>
</thead>
<tr>
<?php foreach ($objects as $object): ?>
<tr>
<td>
<?php echo $object['Key']; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div>
</div>
<div class="col-lg-3 mb-5"></div>
</div>
</div>
</section>
<div class="toggle"></div>
<section class="footer-area bg-gray" style="background-color:#eee !important">
<div class="section-block"></div>
<div class="copyright-content" style="padding:10px">
<div class="container">
<div class="row align-items-center">
<div class="col-lg-6">
<p class="copy-desc">© 2024 Get Sample Code. All Rights Reserved. </p>
</div><!-- end col-lg-6 -->
<div class="col-lg-6">
<div class="d-flex flex-wrap align-items-center justify-content-end">
<ul class="generic-list-item d-flex flex-wrap align-items-center fs-14">
<li class="mr-3"><a href="https://getsamplecode.com/terms-and-conditions">Terms & Conditions</a></li>
<li class="mr-3"><a href="https://getsamplecode.com/privacy-policy">Privacy Policy</a></li>
<li class="mr-3"><a href="https://getsamplecode.com/disclaimer">Disclaimer</a></li>
</ul>
</div>
</div><!-- end col-lg-6 -->
</div><!-- end row -->
</div><!-- end container -->
</div><!-- end copyright-content -->
</section><!-- end footer-area -->
<div id="scroll-top">
<i class="la la-arrow-up" title="Go top"></i>
</div>
<script src="https://getsamplecode.com/fassets/js/jquery-3.4.1.min.js"></script>
<script src="https://getsamplecode.com/fassets/js/bootstrap.bundle.min.js"></script>
<script src="https://getsamplecode.com/fassets/js/jquery.lazy.min.js"></script>
<script src="https://getsamplecode.com/fassets/js/main.js"></script>
<script src="https://getsamplecode.com/fassets/js/prism/prism.js"></script>
<script src="https://getsamplecode.com/fassets/js/folder.js"></script>
<script type="text/javascript">
const toggle = document.querySelector(".toggle");
const nav_bar = document.querySelector(".table-of-contents");
const list = document.querySelector(".table__list");
toggle.addEventListener("click", ()=>{
if (toggle.textContent === "hide") {
toggle.textContent = "show";
}
else {
toggle.textContent = "hide";
}
list.classList.toggle("list-invisible");
nav_bar.classList.toggle("table-narrow");
});
function search_form()
{
$("#search_form").submit();
}
function search_form_mobile()
{
$("#search_form_mobile").submit();
}
function search_form_sidepanel()
{
$("#search_form_sidepanel").submit();
}
</script>
</body>
</html>
11 Define a Route
Define routes for your Codeigniter AWS S3 integration in
app/Config/Routes.php
use CodeIgniter\Router\RouteCollection;
$routes->get('/', 'Home::index');
$routes->get('s3', 'UploadController::index');
$routes->get('list', 'UploadController::list');
$routes->post('upload', 'UploadController::upload');
$routes->get('download/(:any)', 'UploadController::download/$1');
$routes->delete('delete/(:any)', 'UploadController::delete/$1');
12 Folder Structure
13 Run Web Server to Test the App
Use the following command to Test the App.
php spark serve
Visit the URL
http://localhost:8080/index.php/s3
14 Conclusion
Using AWS S3 in Codeigniter 4, you can easily manage file uploads to cloud storage, ensuring scalability and security for your web applications.
Tags