Creating The Upload Form (Codeidniter)
Creating The Upload Form (Codeidniter)
Using a text editor, create a form called upload_form.php. In it, place this code and
save it to your application/views/ directory:
<html>
<head>
<title>Upload Form</title>
</head>
<body>
</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 $error variable. This is so we can show error messages in the
event the user does something wrong.
Using a text editor, create a form called upload_success.php. In it, place this code
and save it to your application/views/ directory:
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
</body>
</html>
The Controller
Using a text editor, create a controller called Upload.php. In it, place this code and
save it to your application/controllers/ directory:
<?php
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$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);
}
}
}
?>
You’ll need a destination directory for your uploaded images. Create a directory at
the root of your CodeIgniter 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.