Overview
Plan database, uploads, configuration, and rollback backups.
Backup & Restore is part of CodeIgniter's PHP framework workflow. CodeIgniter keeps the request lifecycle lightweight and clear with routes, controllers, models, views, services, filters, validation, migrations, and configuration you can understand quickly.
Core Ideas
- Use Backup & Restore to understand CodeIgniter's route, controller, model, view, filter, and service flow.
- Prefer simple framework features before adding heavy abstractions.
- Validate request data, escape output, and keep database writes behind models or services.
- Use Spark, migrations, seeders, logs, and environment files to keep projects repeatable.
Step by Step
- Start Backup & Restore by identifying the route and controller method.
- Read request data through CodeIgniter request helpers and validate it early.
- Use models, entities, query builder, services, or helpers for reusable work.
- Return a view, redirect, JSON response, or error response with clear intent.
Beginner Explanation
Backup & Restore prepares CodeIgniter for real hosting.
Production work includes environment settings, document root, writable permissions, logs, backups, database migrations, and safe debug settings.
Beginners should keep the public document root pointed at public, not the whole project folder.
Before You Start
- Before practicing Backup & Restore, run php spark routes or php spark --version so you know the app is booting.
- Confirm .env has the correct CI_ENVIRONMENT, app.baseURL, database, and security values.
- Check writable/logs when a page or command fails.
- Use migrations and seeders for practice data instead of changing production tables by hand.
- Keep one small feature goal in mind: route, controller, validation, model or service, response, and test idea.
Key CodeIgniter Concepts
- Production should not expose system, app, vendor, or writable as public folders.
- CI_ENVIRONMENT should be production on live sites.
- writable must be writable by the server user.
- Backups should include database, uploads, and environment configuration notes.
Plain-English Glossary
- Route: a URL and HTTP method mapped to controller code.
- Controller: a class that handles a request and returns a response.
- Filter: code that runs before or after a controller.
- View: a PHP template that renders output.
- Model: a database-facing class with allowed fields and query helpers.
- Migration: a repeatable database schema change.
- Seeder: a class that inserts starter or test data.
- Service: a shared reusable object returned by the service locator.
What You Will Learn
- Explain where Backup & Restore belongs in the CodeIgniter request lifecycle.
- Name the main file, folder, command, or class used for this topic.
- Write a small CodeIgniter example that follows framework conventions.
- Identify one validation, escaping, database, security, or deployment risk for the topic.
Where You Use This in Real Projects
You use Backup & Restore in admin panels, CMS pages, forms, APIs, uploads, dashboards, reports, login flows, imports, exports, and deployment checks.
CodeIgniter is productive because the flow stays explicit: route to controller, controller to model or service, then response through a view or JSON.
A reliable CodeIgniter workflow is: define the route, validate input, call a model or service, escape output, return a response, and check logs or tests.
CodeIgniter Safety Notes
- Validate request data before saving or using it.
- Escape output with esc() when rendering user-controlled content in views.
- Use allowedFields on models to protect mass assignment.
- Use CSRF protection, filters, password hashing, prepared query builder calls, and secure environment settings.
- Keep writable logs, cache, uploads, and sessions out of public access.
Beginner Mental Model
Think of Backup & Restore as one part of CodeIgniter's explicit route-to-response path.
The route chooses the controller, filters can guard the request, the controller coordinates validation and models, then a view, redirect, file, or JSON response is returned.
When a controller becomes hard to read, move reusable work into models, services, helpers, libraries, or config classes.
Framework Flow
- A request for Backup & Restore enters CodeIgniter through public/index.php and the framework bootstrap.
- Routes map the URL and method to a controller method, and filters can run before or after the controller.
- The controller reads request data, validates it, calls models, services, helpers, or libraries, and prepares a response.
- CodeIgniter returns a view, redirect, JSON response, file response, or error response.
Key Files and Commands
- app/Config/Routes.php maps URLs to controllers.
- app/Controllers, app/Models, and app/Views hold request logic, data logic, and output templates.
- app/Config, app/Filters, app/Database/Migrations, and app/Database/Seeds organize framework behavior and database changes.
- writable/logs is the first place to inspect runtime errors.
- php spark routes, migrate, db:seed, make:controller, make:model, test, and serve are daily commands.
Security and Project Notes
- Validate all request input before saving or using it.
- Escape output with esc() when rendering user content in views.
- Use model allowedFields to prevent unwanted mass assignment.
- Use filters, CSRF protection, password hashing, prepared query builder calls, and environment variables for sensitive configuration.
Code Example
php spark migrate --all
php spark cache:clear
# Production checks
# CI_ENVIRONMENT = production
# public document root points to /public
# writable/logs and writable/cache are writable
Another Example
php spark migrate --all
php spark cache:clear
# Confirm writable/logs and writable/cache are writable by the web server user.
More Practice Examples
Example 1: Route to controller
$routes->get('courses', 'CourseController::index', ['as' => 'courses.index']);
public function index(): string
{
return view('courses/index', [
'courses' => model(CourseModel::class)->orderBy('created_at', 'DESC')->paginate(10),
]);
}
- The route name keeps URL generation maintainable.
- The controller returns one view response.
- Pagination prevents loading every row at once.
Example 2: Validate and save
$rules = [
'title' => 'required|min_length[3]|max_length[120]',
'slug' => 'required|alpha_dash|max_length[160]|is_unique[lessons.slug]',
];
if (! $this->validate($rules)) {
return redirect()->back()->withInput();
}
model(LessonModel::class)->insert($this->validator->getValidated());
- Validation runs before database writes.
- withInput keeps form values after an error.
- allowedFields on the model must allow only expected columns.
Example 3: Feature test
$result = $this->post('/lessons', [
'title' => 'CodeIgniter Practice',
'slug' => 'codeigniter-practice',
]);
$result->assertRedirect();
$this->seeInDatabase('lessons', ['slug' => 'codeigniter-practice']);
- The test checks the HTTP response and database effect.
- Database assertions catch save failures.
- A focused test makes future refactors safer.
Real-World Feature Pattern
// app/Config/Routes.php
$routes->post('lessons', 'LessonController::store', ['as' => 'lessons.store', 'filter' => 'csrf']);
// app/Controllers/LessonController.php
public function store()
{
$rules = ['title' => 'required|min_length[3]|max_length[120]'];
if (! $this->validate($rules)) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
$lesson = model(LessonModel::class)->insert($this->validator->getValidated());
return redirect()->route('lessons.show', [$lesson])->with('status', 'Lesson saved.');
}
- This Backup & Restore pattern shows the CodeIgniter habit of splitting route, filter, validation, model work, and response.
- The controller coordinates the feature but keeps database rules in the model and route protection in filters.
- The redirect and flash message create a clear browser workflow after a successful POST.
Example Explained
- The Backup & Restore example follows CodeIgniter conventions so routes, controllers, models, views, config, and logs stay easy to locate.
- The route points to a controller method that handles the request.
- Validation and filtering happen before records are changed.
- Models, services, helpers, or libraries do reusable data and business work.
- The final line returns a view, redirect, JSON response, file response, or error response.
How to Read This Example
- Start with app/Config/Routes.php so you know the URL, method, filters, and controller.
- Read the controller method to see request input, validation, model calls, and response type.
- Check model allowedFields before inserts or updates.
- Check views for esc() when output contains user or database values.
- For Backup & Restore, change one CodeIgniter layer at a time and inspect writable/logs if it fails.
Checklist
- Use routes, controllers, models, validation, filters, migrations, and views in their intended roles.
- Protect forms with CSRF, escape output, use allowed fields, and keep secrets in environment config.
- Check logs, Spark commands, and debug toolbar output while developing.
Common Mistakes
- Putting queries, validation, and HTML output into one controller method.
- Forgetting allowedFields, validation rules, CSRF checks, escaping, or filters.
- Editing system files instead of using app, config, services, helpers, or libraries.
Do and Don't
- Do: practice Backup & Restore with a tiny route-to-response feature.
- Do: use CodeIgniter conventions for routes, controllers, models, views, config, filters, and logs.
- Do: validate input, escape output, protect allowedFields, and check writable/logs.
- Don't: put queries, validation, and HTML output all in one controller method.
- Don't: expose app, system, vendor, writable, .env, or logs as public web files.
Practice Challenge
Create a small CodeIgniter note, product, or lesson feature for Backup & Restore. Write the route, controller method, validation, model or migration, view or JSON response, and one debugging check.
Try These Changes
- Add a named route and generate its URL instead of hard-coding the path.
- Move repeated controller logic into a model, service, helper, or library.
- Add validation and show errors with old input after a redirect.
- Write one feature test for the success path and one validation failure.
- For Backup & Restore, identify which CodeIgniter file owns each part of the feature.
Quick Check
- Question: What file usually maps URLs to controllers? Answer: app/Config/Routes.php.
- Question: Where do runtime logs live? Answer: writable/logs.
- Question: Why use allowedFields? Answer: To prevent unsafe mass assignment.
- Question: Why use esc() in views? Answer: To safely output user-controlled content.
- Question: What should Backup & Restore return? Answer: A clear response such as a view, redirect, JSON response, file, or error.
Debugging Checks
- Run php spark routes to confirm the URL, method, filters, and controller.
- Check writable/logs for the current day log file and first useful error.
- Confirm .env values for CI_ENVIRONMENT, app.baseURL, database, sessions, security, and logging.
- Use debug toolbar, tests, and temporary dumps carefully in development, then remove noisy debug output.
- For Backup & Restore, write a small feature test so the behavior can be checked again after changes.
Mini Project
Build a deployment checklist for Backup & Restore: env values, public document root, writable permissions, migrate command, backups, logs, and rollback note.
Mastery Check
- You can explain where Backup & Restore belongs in a CodeIgniter project and why.
- You can connect a route, controller, validation rule, model, view, filter, and migration.
- You can keep a CodeIgniter feature small, clear, secure, and easy to debug.