Professional CodeIgniter

(singke) #1

Chapter 3: A 10,000 - Foot View of CodeIgniter


59


$data = array(
‘name’ = > $_POST[‘name’] ,
‘gender’ = > $_POST[‘gender’],
‘age’ = > $_POST[‘age’]
);

$this- > db- > insert(‘persons’, $data);

Below you learn how to use the update() and delete() methods and a larger set of more specialized
tools, but for now, you get the idea. The Database library offers a powerful feature set that lets you work
with queries and result sets. You can use the Active Record patterns for their conciseness and power, or
you can stick to more flexible SQL queries.

The Session Library


You may be familiar with PHP sessions already. CodeIgniter sessions are similar to PHP sessions (at least
in the way they behave) but are separate from them altogether. For example, CodeIgniter stores session
data in a cookie (by default, but it can also work with database tables) as opposed to PHP sessions,
which save their session data on the server. You also have the option of saving CodeIgniter sessions in a
database.

Here ’ s a very important note if you are security conscious. Even if you choose to save CodeIgniter
sessions in a database table, the same data are stored in a client - side cookie. That means that it is
available to the end - user. Even if you use encryption, it is possible to tamper with the cookie and thereby
cause problems. Therefore, in this book (and in your foreseeable CodeIgniter career), only use
CodeIgniter sessions (and flashdata) to store data that are unimportant. If you need to have secure
logins and authentication, use PHP sessions instead.

By default, CodeIgniter sessions track a session ID, the user ’ s IP address and user agent, and time
stamps for the last activity and the last visit. For performance reasons, the time stamps are only updated
every 5 minutes, so robots and multiple reloads of a page won ’ t cause runaway load on your server.

One more thing to note — once the Session library has been initialized (or autoloaded), you don ’ t have
to take any further steps to start working with CodeIgniter session data.

Retrieving data from a CodeIgniter session is as easy as invoking that library ’ s userdata() method. For
example, to retrieve a CodeIgniter session ’ s session_id, do it this way:

$sess_id = $this- > session- > userdata(‘session_id’);

The userdata() function returns FALSE if the item you ’ re trying to access doesn ’ t exist.

A very useful function of CodeIgniter sessions is to save data about a user and then access it at a later
date. For example, you could create a login verification process that upon successful login adds the
user ’ s e - mail address to the CodeIgniter session:
Free download pdf