How To Check if Request Has File in CodeIgniter 4 Tutorial

Reading Time: 4 minutes
1,206 Views

Determining whether a request contains an uploaded file is a common task in web applications, especially when handling file uploads. CodeIgniter 4, known for its simplicity and powerful features, provides convenient methods to check if a request includes files for processing.

In this tutorial, we’ll see the process of checking if a request has a file upload in CodeIgniter 4. This functionality is crucial for validating file uploads and ensuring proper handling of uploaded content.

Read More: CodeIgniter 4 Get All Application Routes Example Tutorial

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.

Create Controller

To create a controller, run this command.

php spark make:controller DataController

It will create DataController.php inside /app/Controllers folder.

Open DataController.php and write this complete code into it.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class DataController extends BaseController
{
	public function index()
	{
		return view("form");
	}

	public function formSubmit()
	{
		if ($this->request->getMethod() == "post") {

			$file = $this->request->getFile("photo");

			$fileName = $file->getName();

			if (!empty($fileName)) {

				echo "<pre>";
				print_r($file);
				exit();
			} else {

				echo "No file uploaded";
			}
		}
	}
}

Read More: CodeIgniter 4 How to get Random Database Records Tutorial

Create Template File

Go to /app/Views folder and create a file with name form.php

Open form.php and write this complete code into it.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How To Check if Request Has File in CodeIgniter 4 Tutorial</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

    <div class="container mt-5" style="max-width: 900px">

        <div class="alert alert-primary mb-4 text-center">
            <h4>How To Check if Request Has File in CodeIgniter 4 Tutorial</h4>
        </div>

        <form id="fileUploadForm" method="POST" action="<?php echo site_url('submit-form') ?>" enctype="multipart/form-data">
            <div class="form-group mb-3">
                <input name="photo" type="file" class="form-control">
            </div>

            <div class="d-grid mt-4">
                <input type="submit" value="Submit" class="btn btn-primary">
            </div>
        </form>
    </div>
</body>

</html>
              

Add Route

Open Routes.php from /app/Config folder and add these route into it.

//...

$routes->get("form", "DataController::index");
$routes->post("submit-form", "DataController::formSubmit");

//...

Application Testing

Open project terminal and start development server via command:

php spark serve

URL: http://localhost:8080/form

Once you select any file and upload, you should see the details of uploaded file as:

That’s it.

We hope this article helped you to learn How To Check if Request Has File in CodeIgniter 4 Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.