Home Backend Development PHP Tutorial Codeigniter file upload class code example in PHP_PHP tutorial

Codeigniter file upload class code example in PHP_PHP tutorial

Jul 13, 2016 am 10:29 AM
co codeigniter php upload code Example document kind

Codeigniter file upload class code example

File upload class

CodeIgniter’s file upload class allows files to be uploaded. You can set up to upload files of a certain type and size.

Processing process

Common process for uploading files:

A form for uploading files, allowing the user to select a file and upload it.

When this form is submitted, the file is uploaded to the specified directory.

At the same time, the document will be verified to see if it meets the requirements you set.

Once the file is uploaded successfully, a confirmation window indicating successful upload will be returned.

Here is a short tutorial showing the process. Hereafter you will find relevant reference information.

Create upload form

Use a text editor to create a file named upload_form.php, copy the following code and save it in the applications/views/ directory:

You will see that a form helper function is used here to create the start tag of the form. File upload requires a multipart form, because this form helper function creates an appropriate statement for you. You will also see that we use an $error variable, which will display relevant error information when the user submits the form and an error occurs.

Successfully uploaded page

Use a text editor to create a file named upload_success.php. Copy the following code and save it in the applications/views/ directory:

Your file was successfully uploaded!

 $value):?>

 :

Controller

Using a text editor, create a controller named upload.php. Copy the following code and save it to the applications/controllers/ directory:

Load->helper(array('form', 'url')); } function index() { $this->load->view('upload_form', array('error' => ' ' )); } function do_upload() { $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = '100'; $config['max_width'] = '1024'; $config['max_height'] = '768'; $this->load->library('upload', $config); if ( ! $this->upload->do_upload()) { $error = array('error' => $this->upload->display_errors()); $this->load->view( 'upload_form', $error); } else { $data = array('upload_data' => $this->upload->data()); $this->load->view('upload_success' , $data); } } } ?>

Upload file directory

You will also need a destination folder to store the uploaded images. Create a file named uploads in the root directory and set the file's attributes to 777. (i.e. read and write)

Submit form

To submit your form, enter a URL similar to the following:

Example.com/index.php/upload/

You will see an upload form, select any (jpg, gif, or png) image to submit. If the path you set in the controller is correct, it will start working.

Initialize file upload class

Similar to some other CodeIgniter classes, the file upload class is initialized in the controller using the $this->load->library function:

$this->load->library('upload');

Once the file upload class is loaded, the object will be referenced through the following method: $this->upload

Preferences

Similar to other libraries, you will control which files are uploaded based on your preferences. In the controller, you create the following preferences:

$config['upload_path'] = './uploads/';

$config['allowed_types'] = 'gif|jpg|png';

 $config['max_size'] = '100';

 $config['max_width'] = '1024';

 $config['max_height'] = '768';

$this->load->library('upload', $config);

// Alternately you can set preferences by calling the initialize function. Useful if you auto-load the class:

  //[If you automatically loaded the upload class in the autoload.php file in the config folder, or loaded it in the constructor, you can call the initialization function initialize to load the settings. ————This bracket is translated by IT Tumbler, with my own understanding added】

$this->upload->initialize($config);

The above preferences will be fully implemented. Below are descriptions of all preference parameters.

Preference parameters

The following preference parameters are available. When you don't specify a preference parameter, the default value is as follows:

Preferences Default Value Option Description

 upload_path None None File upload path. The path must be writable, both relative and absolute paths are acceptable.

 allowed_types None None MIME types that allow uploading files; usually file extensions can be used as MIME types. Multiple types are allowed to be separated by vertical bars ‘|’

File_name None The file name you want to use

If this parameter is set, CodeIgniter will rename the uploaded file according to the file name set here. The extension in the file name must also be an allowed file type.

overwrite FALSE TRUE/FALSE (boolean) Whether to overwrite. When this parameter is TRUE, if a file with the same name is encountered when uploading a file, the original file will be overwritten; if this parameter is FALSE, when a file with the same name is uploaded, CI will add a number after the file name of the new file.

max_size 0 None The maximum allowed upload file size (in K). If this parameter is 0, there is no limit. Note: Usually PHP also has this restriction, which can be specified in the php.ini file. Usually the default is 2MB.

max_width 0 None The maximum width of the uploaded file (in pixels). 0 means no limit.

max_height 0 None The maximum height of the uploaded file (in pixels). 0 means no limit.

max_filename 0 None The maximum length of the file name. 0 means no limit.

 encrypt_name FALSE TRUE/FALSE (boolean) Whether to rename the file. If this parameter is TRUE, the uploaded file will be renamed to a random encrypted string. This is very useful when you want the file uploader to be unable to distinguish the file names of the files they upload. This option only works when overwrite is FALSE.

 remove_spaces TRUE TRUE/FALSE (boolean) When the parameter is TRUE, spaces in the file name will be replaced with underscores. Recommended.

Set preference parameters in the configuration file

If you don’t want to use the above method to set preferences, you can use a configuration file instead. Simply create a file called upload.php, add the $config array to the file, then save the file to: config/upload.php and it will be loaded automatically. When you save configuration parameters to this file, you do not need to manually load them using the $this->upload->initialize function.

Functions used

The following functions are used

$this->upload->do_upload()

Perform operations based on your preferred configuration parameters. Note: By default, the uploaded file comes from the file field named userfile in the submission form, and the form must be of type "multipart":

If you want to customize your own file domain name before executing the do_upload function, you can do so through the following methods:

 $field_name = "some_field_name";

$this->upload->do_upload($field_name)

$this->upload->display_errors()

If do_upload() returns failure, an error message will be displayed. This function does not automatically output, but returns data, so you can arrange it however you want.

Formatting error

The above function uses

by default

Mark error messages. You can set your own separator like this.

$this->upload->display_errors('

 , '

 );

$this->upload->data()

This is a helper function that returns an array of all relevant information about the file you uploaded.

Array

 (

 [file_name] => mypic.jpg

 [file_type] => image/jpeg

 [file_path] => /path/to/your/upload/

 [full_path] => /path/to/your/upload/jpg.jpg

 [raw_name] => mypic

 [orig_name] => mypic.jpg

 [client_name] => mypic.jpg

 [file_ext] => .jpg

 [file_size] => 22.2

 [is_image] => 1

 [image_width] => 800

 [image_height] => 600

 [image_type] => jpeg

 [image_size_str] => width="800" height="200"

 )

Explanation

Here is an explanation of the above array items.

 Item Description

file_name The name of the uploaded file (including extension)

file_type Mime type of the file

file_path The absolute path of the file excluding the file name

full_path The absolute path of the file including the file name

raw_name The part of the file name excluding the extension

orig_name The initial file name of the uploaded file. This only works if upload file rename (encrypt_name) is set.

Client_name is the file name of the uploaded file on the client.

file_ext file extension (including ‘.’)

 file_size image size, unit is kb

Is_image whether it is an image. 1 = is an image. 0 = Not an image.

Image_width image width.

 image_height image height

Image_type file type, that is, file extension (excluding ‘.’)

Image_size_str A string containing width and height. Used in an img tag.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/769527.htmlTechArticlecodeigniter file upload class code example file upload class CodeIgniter's file upload class allows files to be uploaded. You can set up to upload files of a certain type and size. ...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles