File Upload in codeigniter


File Uploading Class

CodeIgniter’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 applications/views/
folder:

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.

The Success Page

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

The Controller

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

The Upload Folder

You’ll need a destination folder for your uploaded images. Create a folder 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.

Reference Guide

Initializing the Upload Class

Like most other classes in CodeIgniter, the Upload class is initialized in your controller using the $this->load->library function:

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

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

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['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:

$this->upload->initialize($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
upload_path None None The path to the folder where the upload should be placed. The folder must be writable and the path can be absolute or relative.
allowed_types 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. Separate multiple types with a pipe.
file_name None Desired file name If set CodeIgniter will rename the uploaded file to this name. The extension provided in the file name must also be an allowed file type.
overwrite FALSE TRUE/FALSE (boolean) If set to true, if a file with the same name as the one you are uploading exists, it will be overwritten. If set to false, a number will be appended to the filename if another with the same name exists.
max_size 0 None The maximum size (in kilobytes) that the file can be. Set to zero for no limit. Note: Most PHP installations have their own limit, as specified in the php.ini file. Usually 2 MB (or 2048 KB) by default.
max_width 0 None The maximum width (in pixels) that the file can be. Set to zero for no limit.
max_height 0 None The maximum height (in pixels) that the file can be. Set to zero for no limit.
max_filename 0 None The maximum length that a file name can be. Set to zero for no limit.
encrypt_name FALSE TRUE/FALSE (boolean) If set to TRUE the file name will be converted to a random encrypted string. This can be useful if you would like the file saved with a name that can not be discerned by the person uploading it.
remove_spaces TRUE TRUE/FALSE (boolean) If set to TRUE, any spaces in the file name will be converted to underscores. This is recommended.

Setting preferences in a config file

If you prefer not to set preferences using the above method, you can instead put them into a config file.
Simply create a new file called the upload.php, add the $config
array in that file. Then save the file in: config/upload.php and it will be used automatically. You
will NOT need to use the $this->upload->initialize function if you save your preferences in a config file.

Function Reference

The following functions are available

$this->upload->do_upload()

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 a “multipart type:

<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 do_upload function:


$field_name = "some_field_name";
$this->upload->do_upload($field_name)

$this->upload->display_errors()

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

Formatting Errors

By default the above function wraps any errors within <p> tags. You can set your own delimiters like this:

$this->upload->display_errors('<p>', '</p>');

$this->upload->data()

This is a helper function 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/

[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 file that was uploaded including the file extension.
file_type The file’s Mime type
file_path The absolute server path to the file
full_path The absolute server path including the file name
raw_name The file name without the extension
orig_name The original file name. This is only useful if you use the encrypted name option.
client_name The file name as supplied by the client user agent, prior to any file name preparation or incrementing.
file_ext The file extension with period
file_size The file size in kilobytes
is_image Whether the file is an image or not. 1 = image. 0 = not.
image_width Image width.
image_height Image height
image_type Image type. Typically the file extension without the period.
image_size_str A string containing the width and height. Useful to put into an image tag.
Advertisements

URL Helper in codeigniter


The URL Helper file contains functions that assist in working with URLs.

Loading this Helper

This helper is loaded using the following code:

$this->load->helper('url');

The following functions are available:

site_url()

Returns your site URL, as specified in your config file. The index.php file (or whatever you have set as your
site index_page in your config file) will be added to the URL, as will any URI segments you pass to the function.

You are encouraged to use this function any time you need to generate a local URL so that your pages become more portable
in the event your URL changes.

Segments can be optionally passed to the function as a string or an array. Here is a string example:

echo site_url("news/local/123");

The above example would return something like: http://example.com/index.php/news/local/123

Here is an example of segments passed as an array:


$segments = array('news', 'local', '123');

echo site_url($segments);

base_url()

Returns your site base URL, as specified in your config file. Example:

echo base_url();

current_url()

Returns the full URL (including segments) of the page being currently viewed.

uri_string()

Returns the URI segments of any page that contains this function. For example, if your URL was this:

http://some-site.com/blog/comments/123

The function would return:

/blog/comments/123

index_page()

Returns your site “index” page, as specified in your config file. Example:

echo index_page();

anchor()

Creates a standard HTML anchor link based on your local site URL:

<a href="http://example.com">Click Here</a>

The tag has three optional parameters:

anchor(uri segments, text, attributes)

The first parameter can contain any segments you wish appended to the URL. As with the site_url() function above,
segments can be a string or an array.

Note: If you are building links that are internal to your application do not include the base URL (http://&#8230;). This
will be added automatically from the information specified in your config file. Include only the URI segments you wish appended to the URL.

The second segment is the text you would like the link to say. If you leave it blank, the URL will be used.

The third parameter can contain a list of attributes you would like added to the link. The attributes can be a simple string or an associative array.

Here are some examples:

echo anchor('news/local/123', 'My News', 'title="News title"');

Would produce: <a href=”http://example.com/index.php/news/local/123&#8243; title=”News title”>My News</a>

echo anchor('news/local/123', 'My News', array('title' => 'The best news!'));

Would produce: <a href=”http://example.com/index.php/news/local/123&#8243; title=”The best news!”>My News</a>

anchor_popup()

Nearly identical to the anchor() function except that it opens the URL in a new window.

You can specify JavaScript window attributes in the third parameter to control how the window is opened. If
the third parameter is not set it will simply open a new window with your own browser settings. Here is an example
with attributes:

$atts = array(

‘width’      => ‘800’,

‘height’     => ‘600’,

‘scrollbars’ => ‘yes’,

‘status’     => ‘yes’,

‘resizable’  => ‘yes’,

‘screenx’    => ‘0’,

‘screeny’    => ‘0’

);

echo anchor_popup(‘news/local/123’, ‘Click Me!’, $atts);

Note: The above attributes are the function defaults so you only need to set the ones that are different from what you need.
If you want the function to use all of its defaults simply pass an empty array in the third parameter:

echo anchor_popup('news/local/123', 'Click Me!', array());

mailto()

Creates a standard HTML email link. Usage example:

echo mailto('me@my-site.com', 'Click Here to Contact Me');

As with the anchor() tab above, you can set attributes using the third parameter.

safe_mailto()

Identical to the above function except it writes an obfuscated version of the mailto tag using ordinal numbers
written with JavaScript to help prevent the email address from being harvested by spam bots.

auto_link()

Automatically turns URLs and email addresses contained in a string into links. Example:

$string = auto_link($string);

The second parameter determines whether URLs and emails are converted or just one or the other. Default behavior is both
if the parameter is not specified. Email links are encoded as safe_mailto() as shown above.

Converts only URLs:

$string = auto_link($string, 'url');

Converts only Email addresses:

$string = auto_link($string, 'email');

The third parameter determines whether links are shown in a new window. The value can be TRUE or FALSE (boolean):

$string = auto_link($string, 'both', TRUE);

url_title()

Takes a string as input and creates a human-friendly URL string. This is useful if, for example, you have a blog
in which you’d like to use the title of your entries in the URL. Example:

$title = "What's wrong with CSS?";

$url_title = url_title($title);

// Produces: Whats-wrong-with-CSS

The second parameter determines the word delimiter. By default dashes are used. Options are: dash, or underscore:

$title = "What's wrong with CSS?";

$url_title = url_title($title, ‘underscore’);

// Produces: Whats_wrong_with_CSS

The third parameter determines whether or not lowercase characters are forced. By default they are not. Options are boolean TRUE/FALSE:

$title = "What's wrong with CSS?";

$url_title = url_title($title, ‘underscore’, TRUE);

// Produces: whats_wrong_with_css

prep_url()

This function will add http:// in the event that a scheme is missing from a URL. Pass the URL string to the function like this:


$url = "example.com";

$url = prep_url($url);

redirect()

Does a “header redirect” to the URI specified. If you specify the full site URL that link will be build, but for local links simply providing the URI segments
to the controller you want to direct to will create the link. The function will build the URL based on your config file values.

The optional second parameter allows you to choose between the “location”
method (default) or the “refresh” method. Location is faster, but on Windows servers it can sometimes be a problem. The optional third parameter allows you to send a specific HTTP Response Code – this could be used for example to create 301 redirects for search engine purposes. The default Response Code is 302. The third parameter is only available with ‘location’ redirects, and not ‘refresh’. Examples:

if ($logged_in == FALSE)

{

redirect(‘/login/form/’, ‘refresh’);

}

// with 301 redirect

redirect(‘/article/13’, ‘location’, 301);

Note: In order for this function to work it must be used before anything is outputted
to the browser since it utilizes server headers.

Note: For very fine grained control over headers, you should use the Output Library‘s set_header() function.

CodeIgniter Helpers class library ( anchor function )


Remark : To use CodeIgniter Helpers class library ..you must add this line in autoupdate.php file

$autoload[‘helper’] = array(‘url’, ‘file’);

Example

views/blogview.php

<html>
<head>
<title>Demo</title>
</head>
<body>

<ul>
<?php
foreach ($navlist as $row)
{
echo “<li>”.$row->id.” “.anchor(‘news/local/123’, $row->NAME, ‘title=”‘.$row->NAME.'”‘).”</li/>”;
}
?>
</ul>
</body>
</html>

 

controllers/blog.php

<?php
class Blog extends CI_Controller {

function index()
{

$data[‘title’] = “Welcome to Claudia’s Kids”;
$data[‘navlist’] = $this->blog_model->getAllCategories();
$this->load->vars($data);
$this->load->view(‘blogview’);
}

}
?>

models/blog_model.php

<?php
class Blog_model extends CI_Model {

function __construct()
{
parent::__construct();
}
function getCategory($id)
{
$data = array();
$options = array(‘id’ => $id);
$Q = $this->db->getwhere(‘categories’,$options,1);
if ($Q->num_rows() > 0)
{
$data = $Q->row_array();
}
$Q->free_result();
return $data;
}
function getAllCategories()
{
$sql = “select * from categories where 1=1”;
$Q = $this->db->query($sql);
return $Q->result();
}
}
?>

<?php
class Blog_model extends CI_Model {

function __construct()
{
parent::__construct();
}
function getCategory($id)
{
$data = array();
$options = array(‘id’ => $id);
$Q = $this->db->getwhere(‘categories’,$options,1);
if ($Q->num_rows() > 0)
{
$data = $Q->row_array();
}
$Q->free_result();
return $data;
}
function getAllCategories()
{
$sql = “select * from categories where 1=1”;
$Q = $this->db->query($sql);
return $Q->result();
}
}
?>

Session Class library in codeigniter


Session Class

The Session class permits you maintain a user’s “state” and track their activity while they browse your site.
The Session class stores session information for each user as serialized (and optionally encrypted) data in a cookie.
It can also store the session data in a database table for added security, as this permits the session ID in the
user’s cookie to be matched against the stored session ID. By default only the cookie is saved. If you choose to
use the database option you’ll need to create the session table as indicated below.

Note: The Session class does not utilize native PHP sessions. It
generates its own session data, offering more flexibility for developers.

Note: Even if you are not using encrypted sessions, you must set
an encryption key in your config file which is used to aid in preventing session data manipulation.

Initializing a Session

Sessions will typically run globally with each page load, so the session class must either be
initialized in your
controller constructors, or it can be

auto-loaded by the system.
For the most part the session class will run unattended in the background, so simply initializing the class
will cause it to read, create, and update sessions.

To initialize the Session class manually in your controller constructor, use the $this->load->library function:

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

Once loaded, the Sessions library object will be available using: $this->session

How do Sessions work?

When a page is loaded, the session class will check to see if valid session data exists in the user’s session cookie.
If sessions data does not exist (or if it has expired) a new session will be created and saved in the cookie.
If a session does exist, its information will be updated and the cookie will be updated. With each update, the session_id will be regenerated.

It’s important for you to understand that once initialized, the Session class runs automatically. There is nothing
you need to do to cause the above behavior to happen. You can, as you’ll see below, work with session data or
even add your own data to a user’s session, but the process of reading, writing, and updating a session is automatic.

What is Session Data?

A session, as far as CodeIgniter is concerned, is simply an array containing the following information:

  • The user’s unique Session ID (this is a statistically random string with very strong entropy, hashed with MD5 for portability, and regenerated (by default) every five minutes)
  • The user’s IP Address
  • The user’s User Agent data (the first 50 characters of the browser data string)
  • The “last activity” time stamp.

The above data is stored in a cookie as a serialized array with this prototype:

[array]

(

'session_id'    => random hash,

'ip_address'    => 'string - user IP address',

‘user_agent’    => ‘string – user agent data’,

‘last_activity’ => timestamp

)

If you have the encryption option enabled, the serialized array will be encrypted before being stored in the cookie,
making the data highly secure and impervious to being read or altered by someone. More info regarding encryption
can be found here, although the Session class will take care of initializing
and encrypting the data automatically.

Note: Session cookies are only updated every five minutes by default to reduce processor load. If you repeatedly reload a page
you’ll notice that the “last activity” time only updates if five minutes or more has passed since the last time
the cookie was written. This time is configurable by changing the $config[‘sess_time_to_update’] line in your system/config/config.php file.

Retrieving Session Data

Any piece of information from the session array is available using the following function:

$this->session->userdata('item');

Where item is the array index corresponding to the item you wish to fetch. For example, to fetch the session ID you
will do this:

$session_id = $this->session->userdata('session_id');

Note: The function returns FALSE (boolean) if the item you are trying to access does not exist.

Adding Custom Session Data

A useful aspect of the session array is that you can add your own data to it and it will be stored in the user’s cookie.
Why would you want to do this? Here’s one example:

Let’s say a particular user logs into your site. Once authenticated,
you could add their username and email address to the session cookie, making that data globally available to you without
having to run a database query when you need it.

To add your data to the session array involves passing an array containing your new data to this function:

$this->session->set_userdata($array);

Where $array is an associative array containing your new data. Here’s an example:

$newdata = array(

'username'  => 'johndoe',

'email'     => 'johndoe@some-site.com',

‘logged_in’ => TRUE

);

$this->session->set_userdata($newdata);

If you want to add userdata one value at a time, set_userdata() also supports this syntax.

$this->session->set_userdata('some_name', 'some_value');

Note: Cookies can only hold 4KB of data, so be careful not to exceed the capacity. The
encryption process in particular produces a longer data string than the original so keep careful track of how much data you are storing.

Removing Session Data

Just as set_userdata() can be used to add information into a session, unset_userdata() can be used to remove it, by passing the session key. For example, if you wanted to remove ‘some_name’ from your session information:

$this->session->unset_userdata('some_name');

This function can also be passed an associative array of items to unset.

$array_items = array('username' => '', 'email' => '');

$this->session->unset_userdata($array_items);

Flashdata

CodeIgniter supports “flashdata”, or session data that will only be available for the next server request, and are then automatically cleared. These can be very useful, and are typically used for informational or status messages (for example: “record 2 deleted”).

Note: Flash variables are prefaced with “flash_” so avoid this prefix in your own session names.

To add flashdata:

$this->session->set_flashdata('item', 'value');

You can also pass an array to set_flashdata(), in the same manner as set_userdata().

To read a flashdata variable:

$this->session->flashdata('item');

If you find that you need to preserve a flashdata variable through an additional request, you can do so using the keep_flashdata() function.

$this->session->keep_flashdata('item');

Saving Session Data to a Database

While the session data array stored in the user’s cookie contains a Session ID,
unless you store session data in a database there is no way to validate it. For some applications that require little or no
security, session ID validation may not be needed, but if your application requires security, validation is mandatory. Otherwise, an old session
could be restored by a user modifying their cookies.

When session data is available in a database, every time a valid session is found in the user’s cookie, a database
query is performed to match it. If the session ID does not match, the session is destroyed. Session IDs can never
be updated, they can only be generated when a new session is created.

In order to store sessions, you must first create a database table for this purpose. Here is the basic
prototype (for MySQL) required by the session class:

Note: By default the table is called ci_sessions, but you can name it anything you want
as long as you update the application/config/config.php file so that it contains the name you have chosen.
Once you have created your database table you can enable the database option in your config.php file as follows:

$config['sess_use_database'] = TRUE;

Once enabled, the Session class will store session data in the DB.

Make sure you’ve specified the table name in your config file as well:

$config['sess_table_name'] = 'ci_sessions';

Note: The Session class has built-in garbage collection which clears out expired sessions so you
do not need to write your own routine to do it.

Destroying a Session

To clear the current session:

$this->session->sess_destroy();

Note: This function should be the last one called, and even flash variables will no longer be available. If you only want some items destroyed and not all, use unset_userdata().

Session Preferences

You’ll find the following Session related preferences in your application/config/config.php file:

Preference Default Options Description
sess_cookie_name ci_session None The name you want the session cookie saved as.
sess_expiration 7200 None The number of seconds you would like the session to last. The default value is 2 hours (7200 seconds). If you would like a non-expiring session set the value to zero: 0
sess_expire_on_close FALSE TRUE/FALSE (boolean) Whether to cause the session to expire automatically when the browser window is closed.
sess_encrypt_cookie FALSE TRUE/FALSE (boolean) Whether to encrypt the session data.
sess_use_database FALSE TRUE/FALSE (boolean) Whether to save the session data to a database. You must create the table before enabling this option.
sess_table_name ci_sessions Any valid SQL table name The name of the session database table.
sess_time_to_update 300 Time in seconds This options controls how often the session class will regenerate itself and create a new session id.
sess_match_ip FALSE TRUE/FALSE (boolean) Whether to match the user’s IP address when reading the session data. Note that some ISPs dynamically
changes the IP, so if you want a non-expiring session you will likely set this to FALSE.
sess_match_useragent TRUE TRUE/FALSE (boolean) Whether to match the User Agent when reading the session data.

select query in codeigniter


$this- > db- > select(‘id, name’);
$this- > db- > from(‘persons’);
$this- > db- > where(‘id > =’, 3);
$Q = $this- > db- > get();
//query becomes:
//select id, name from persons where id > = 3

 

or

 

$this- > db- > select(‘id, name’);
$this- > db- > from(‘persons’);
$this- > db- > where(“name=’Tom’ and id > 3”);
$Q = $this- > db- > get();