how to define the constants globally in CodeIgniter
Home » BLOG » Web development » How to define constants globally in CodeIgniter

How to define constants globally in CodeIgniter

category:  CodeIgniter, Web development

When you are developing the web application, you want to set the constants that you will use in the application globally. For example, you want to set the application name, application version or salt key for encrypt the password. In CodeIgniter, it provides the place for this purpose.

Constants.php

In application/config/constants.php, it is a file that you can define your constants globally. In the constants.php, you will see some constants in there. Go to the end of file and add your own constants. The constant variable should be the uppercase regarding the best practice for variable naming.

Below is an example of the constants that define in the constants.php.

// Password Salt
defined('PASSWORD_SALT') OR define('PASSWORD_SALT', 'YourSaltKey'); 

// Default send email from (TO:)
defined('SEND_EMAIL_FROM') OR define('SEND_EMAIL_FROM', '[email protected]'); 

CodeIgniter will load the constants that you define in the constants.php automatically. You can simply call your constants in your application right away.

<?php
class Users extends CI_Controller
{
    public function register()
    {
        // call PASSWORD_SALT variable that you define in the constants.php 
        $data['password'] = MD5( PASSWORD_SALT . $this->input->post('password') );
...

And that how easily define the constants globally and use them in CodeIgniter.

If you are new to CodeIgniter, you can read the CodeIgniter tutorial from here.

  •  
  •  
  •  
  •  
  •