About Codeigniter, Tips & Tricks

Why to use CodeIgniter?

CodeIgniter is a php framework, with a small footprint, based on model-view-controller(MVC) architecture, but very flexible and permissive with regard to organizing the code.

How to create a custom Codeigniter 404 page not found?

As I explained in his articol, How to deal with 404 error pages, best practices is a good option to create a custom 404 error page not found.
1. In application/config/routes.php modify the field 404_override to point to your controller:

$route['404_override'] = 'my404'; (My404 is the controller).

2. Inside application/controllers create a new controller named My404

<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

class My404 extends CI_Controller 
{
 public function __construct() 
 {
    parent::__construct(); 
 } 

 public function index() 
 { 
    $this->output->set_status_header('404'); 
    $this->load->view('my404');//loading the custom error view
 } 
} 

3. In application/views create the custom error view file, my404.php

About Codeigniter folders

application/cache – If you enable caching, data is stored here.
application/hooks – Hooks are a way of controlling the way other files load.
application/logs – If you set the system to log errors, log files are created here by default.
application/libraries – Collections of your code, to use in the application.

How to update a site made in Codeigniter?

Upgrading From a Previous Version of Codeigniter – Read here

Getting Parameters to a Function

For example, an url like:
http://mysite/index.php/start/hello/john
start = controller
hello = function
john = parameter
The last segment of the URL is passed to the function as a parameter. You can add more segments of extra parameters if you need.

Be careful A malicious user could easily add his or her own parameter, just by sending a URL like: http://mysite/index.php/start/hello/my_malicious_parameter.

So, you might want to check that the variables you receive are within the range you expect before handling them.

How to pass data to a view?

For example, we have the function hello(), in the Start controller:
controller/Start.php

/**
 * @author Webpedia
 * @copyright 2019
 */

class Start extends CI_Controller {
	function __construct(){
    	parent::__construct();
    }
    
    function hello($name)
    {
        {
        $data['text'] = "Hello, {$name}!Welcome to my site!";
        $this->load->view('myview', $data);
        }
    }
}

views/myview.php

<!doctype html>
<html>
<head>
<title>Website title</title>
</head>
<body>
<h1><?php echo $text; ?> </h1>
</body>
</html>

Url: http://mysite/index.php/start/hello/john
Result: Hello, john!Welcome to my site!

The controller passes the $data array to View.
CI takes each value in the $data array from Controller and turns it into a new own variable in View.

Even if you can only pass one variable to a view, it doesn’t limit you in any way, because each value in the $data array can itself be another array,
and so on …

Calling the View

$this->load->view(‘myview’, $data);
The line above calls the view and pass the data.

How to call a function directly?

If you want to use code from libraries, models or helpers, you have to load them first, and then call the function you need, like:

//Load date helper
 $this->load->helper('date');

 //Takes a UNIX timestamp as input and returns it in a human readable
$now = time();
echo unix_to_human($now);

or

You can load the helper in config/autoload.php, without having to load it every time you use it, like:

$autoload['helper'] = array('html','form','url','date');

How to load a models in Controller?

$this->load->My_model;
$this->My_model->myfunction();

or directly:
$this->My_model->myfunction();

How to create a hyperlink to a URL?

$this->load->helper('url');
echo anchor('/start/hello/Mike', 'Hello');
// Prints: <a href="http://mysite.com/index.php/hello/Mike">Hello</a>

Besides the fact that you write less code, the big advantage is that the URL helper automatically looks up the site URL in the config files. So if you will change your site location, you only need to alter the config file once, you don’t have to manually replace the URLs in all places.

There are several other useful functions in the URL helper, you can find them all here.

Codeigniter pass value from controller to view with ajax request and json

For example a jQuery Read More link

Will add the value of the variable setted in the controller in a paragraph.

In View

<p><span id="texthere"></span><a href="#" id="clicker">Click me</a></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {
            $('#clicker').click(function() {
                $.ajax({
                    url: '<?php echo base_url()?>my_controller/function_name()',
                    type: 'POST',
                    dataType: 'json',
                    success: function ( data) {
			var text_to_add = data['text_to_add'];
                        $( "#texthere" ).text(text_to_add);
                    },
                });
            });
        }); 	
</script>

In controller

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class My_controller extends CI_Controller{
	public function function_name() {
		$data = array('text_to_add' => 'Lorem ipsum dolor sit amet, delectus detraxit partiendo eos ne, verterem consectetuer reprehendunt at has');
		echo json_encode($data);
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *