How to create a cookie which never expire using Codeigniter

Maximum value of cookie expiration time is 2147483647 (2^31 – 1 = 2147483647 = 2038-01-19 04:14:07) [see: RFC 2616, 14.6 Age]

So the example code snippet:

// substracting current time from last exp. time because CI adds current time to the value
$unexpired_cookie_exp_time = 2147483647 - time();

$cookie = array(
	'name' => 'cookie_name',
	'value' => 'cookie_value',
	'expire'=> $unexpired_cookie_exp_time
);

$CI->input->set_cookie($cookie);

 

Form validation example using CodeIgniter

Example is about simply user creation.

Controller file(user.php)

<?php

/**
 * User controller class
 */
class User extends CI_Controller
{

	public function create()
	{
		$data=['title'=>'Create New User'];
		$this->load->library('form_validation');

		// validation rules
		$rules=array(
			array(
				'field'=>'username',
				'label'=>'Username',
				'rules'=>'required|min_length[6]',
			),
			array(
				'field'=>'password',
				'label'=>'Password',
				// user-defined validation rule via method
				'rules'=>'required|callback_checkPasswordStrength',
			),
			array(
				'field'=>'passwordConfirm',
				'label'=>'Password Confirm',
				'rules'=>'required|matches[password]',
			),
		);
		$this->form_validation->set_rules($rules);

		// failed
		if ($this->form_validation->run() === FALSE)
		{
			$this->load->view('user/create',$data);
		}
		// successfull
		else
		{
			$attrs=$this->input->post(null,true);
			$this->load->view('user/success');
		}
	}

	// user-defined validation rule via method
	public function checkPasswordStrength($password)
	{
		if (strlen($password)<5) {
			$this->form_validation->set_message('checkPasswordStrength','Password length cant be less than 5 characters');
			return false;
		}
		else if (!preg_match('/[[:punct:]]/',$password)) {
			$this->form_validation->set_message('checkPasswordStrength','Password must contain at least 1 special character');
			return false;
		}
		return true;
	}
}

View file(create.php)

<ul>
	<?php echo validation_errors('<li class="error">','</li>'); ?>
</ul>

<form action="/index.php/user/create" method="post">
	<label>Username:</label>
	<input type="text" name="username" value="<?php echo set_value('username'); ?>" />
	<?php echo form_error('username','<div class="error">','</div>'); ?>
	<br />

	<label for="">Password:</label>
	<input type="password" name="password" value="<?php echo set_value('password'); ?>" />
	<?php echo form_error('password','<div class="error">','</div>'); ?>
	<br />

	<label for="">Password Confirm:</label>
	<input type="password" name="passwordConfirm" value="<?php echo set_value('passwordConfirm'); ?>" />
	<?php echo form_error('passwordConfirm','<div class="error">','</div>'); ?>
	<br />

	<input type="submit" name="submit" value="Create" />
</form>