File Uploading Class

Codingox’s File Uploading Class permits files to be uploaded. You can set various preferences, restricting the type and size of the files.

The Process

Uploading a file involves the following general process:

  • An upload form is displayed, allowing a user to select a file and upload it.
  • When the form is submitted, the file is uploaded to the destination you specify.
  • Along the way, the file is validated to make sure it is allowed to be uploaded based on the preferences you set.
  • Once uploaded, the user will be shown a success message.

To demonstrate this process here is brief tutorial. Afterward you’ll find reference information.

Creating the Upload Form

Using a text editor, create a form called upload_form.php. In it, place this code and save it to your views/ directory:

<html>
<head>
<title>Upload Form</title>
</head>
<body>

<?php echo $this->media->upload_error(); ?>

<?php echo form_media('upload/do_upload');?>

<input type="file" name="userfile" size="20" />

<br /><br />

<input type="submit" value="upload" />

</form>

</body>
</html>

You’ll notice we are using a form helper to create the opening form tag. File uploads require a multipart form, so the helper creates the proper syntax for you. You’ll also notice we have an $this->media->upload_error(); method. This is so we can show error messages in the event the user does something wrong.

The Success Page

Using a text editor, create a form called upload_success.php. In it, place this code and save it to your views/ directory:

<html>
<head>
<title>Upload Form</title>
</head>
<body>

<h3>Your file was successfully uploaded!</h3>

<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>

<p><?php echo a_href('upload', 'Upload Another File!'); ?></p>

</body>
</html>

The Controller

Using a text editor, create a controller called Upload.php. In it, place this code and save it to your controllers/ directory:

<?php

class Upload extends Base_Controller {

        public function __construct()
        {
                parent::__construct();
                $this->helper(array('form', 'url'));
                $this->library('media');
        }

        public function index()
        {
                $this->render('upload_form');
        }

        public function do_upload()
        {
                $config['path'] = 'uploads/';
                $config['type'] = 'gif|jpg|png';
                $config['size'] = 100;
                
                $this->media->upload('userfile', $config);

                if ( ! $this->media->is_uploaded())
                {
                        $this->view('upload_form');
                }
                else
                {
                        $data = array('upload_data' => $this->media->file_data());

                        $this->view('upload_success', $data);
                }
        }
}
?>

The Upload Directory

You’ll need a destination directory for your uploaded images. Create a directory into web/ folder of your Codingox installation called uploads and set its file permissions to 777.

Try it!

To try your form, visit your site using a URL similar to this one:

example.com/index.php/upload/

You should see an upload form. Try uploading an image file (either a jpg, gif, or png). If the path in your controller is correct it should work.

Reference Guide

Initializing the Media Class

Like most other classes in Codingox, the Media class is initialized in your controller using the $this->library() method:

$this->library('media');

Once the Media class is loaded, the object will be available using: $this->media

Setting Preferences

Similar to other libraries, you’ll control what is allowed to be upload based on your preferences. In the controller you built above you set the following preferences:

$config['path'] = 'uploads/';
$config['type'] = 'gif|jpg|png';
$config['size'] = '100';

$this->library('media');

$this->media->upload('userfile', $config);

The above preferences should be fairly self-explanatory. Below is a table describing all available preferences.

Preferences

The following preferences are available. The default value indicates what will be used if you do not specify that preference.

Preference Default Value Options Description
path None None The path to the directory where the upload should be placed. The directory must be writable and the path can be absolute or relative.
type None None The mime types corresponding to the types of files you allow to be uploaded. Usually the file extension can be used as the mime type. Can be either an array or a pipe-separated string.
name None Desired file name If set Codingox will rename the uploaded file to this name. The extension provided in the file name must also be an allowed file type. If no extension is provided in the original file_name will be used.
size 0 None The maximum size (in kilobytes) that the file can be. Note: Most PHP installations have their own limit, as specified in the php.ini file. Usually 2 MB (or 2048 KB) by default.

Class Reference

class Media
upload($field = 'userfile', $config)
Parameters:
  • $field (string) – Name of the form field
  • $config (array) – Condition of the file Validation
Returns:

TRUE on success, FALSE on failure

Return type:

bool

Performs the upload based on the preferences you’ve set.

Note

By default the upload routine expects the file to come from a form field called userfile, and the form must be of type “multipart”.

<form method="post" action="some_action" enctype="multipart/form-data" />

If you would like to set your own field name simply pass its value to the upload() method:

$field_name = "some_field_name";
$this->media->upload($field_name, $config);
upload_error()
Returns:

Error message(s)

Return type:

string

Retrieves any error messages if the upload() method returned false. The method does not echo automatically, it returns the data so you can assign it however you need.

file_data()
Returns:

Information about the uploaded file

Return type:

mixed

This is a helper method that returns an array containing all of the data related to the file you uploaded. Here is the array prototype:

Array
(
        [file_name]       => mypic.jpg
        [file_type]       => image/jpeg
        [file_path]       => /path/to/your/upload/
        [file_exts]       => .jpg
        [file_size]       => 22.2
        [file_full_path]  => /path/to/your/upload/jpg.jpg
        [file_mime_type]  => jpeg
        [is_image_file]   => 1
)

To return all element from the array:

$this->media->file_data();       // Returns: array

Here’s a table explaining the above-displayed array items:

Item Description
file_name Name of the file that was uploaded, including the filename extension
file_type File MIME type identifier
file_path Absolute server path to the file
file_exts Filename extension, period included
file_size File size in kilobytes
file_full_path Absolute server path, including the file name
is_image_file Whether the file is an image or not. 1 = image. 0 = not.
file_mime_type File type (usually the file name extension without the period)