Learning to Use CodeIgniter

CodeIgniter is a PHP framework for webpages. PHP uses a Model, View, Controller (MVC) approach. When a user lands on the webpage’s URL, Codeigniter will route the request to a Controller. The Controller will load the necessary data and appropriate View (HTML). The controller may make API calls or make database queries (SQL) using functions defined in the Model.

Out of the box, in the app folder, the main folders you will work with are: /config, /controllers, /models, and /views.

Running your app: Download a web server, such as Xampp (https://www.apachefriends.org/download.html), to run your application on your local computer. Start your webserver, then start download CodeIgniter (https://codeigniter.com/download).

.htaccess: In the root folder, there is a file called .htaccess which is a configuration file. The .htaccess file is placed in a directory on the web server. When this is done it will be executed by the Apache web server when a request is made from that directory.

index.php: index.php is the root file that is served when the user navigates to your webpage. At the bottom of your index.php file, you will configure your database access. You will likely need to write some logic to detect if the request is coming from the localhost or from the live server. You will likely need to create a database in phpmyadmin by going to localhost/yourApp/phpmyadmin.

$port = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $port == 443) ? "https://" : "http://";
$host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : "";
if($host == "yourliveserver.com"){
define("base_url", $protocol . "yourliveserver.com/");
define("db_host", "localhost");
define("db_username", "root");
define("db_password", "yourPassword");
define("db_database", "yourDatabaseName");
} else if($host == "localhost"){
define("base_url", $protocol . "localhost:443/yourAppName");
define("db_host", "localhost");
define("db_username", "root");
define("db_password", "yourPassword");
define("db_database", "yourDatabaseName");
}

routes.php: The /config folder contains the routes.php file where you determine which controller is used when the user lands a given URL. The code below will call the Home.php controller.

$route['home'] = '/home';

The code below will call the users() method inside the Home.php controller.

$route['home/joe'] = '/home/users';

You may also use Regex in your redirects to dynamically call a method. In the code below, if the user navigates to home/login, the login() method of the Home.php controller will be called.

$route['home/(:any)'] = '/home/$1';

autoload.php: The /config folder contains an autoload.php file where you can define which packages you want CodeIgniter to load.

Controllers: You can create Controller files in the Controllers folder. The Controller is a class that will load the necessary data and appropriate View (HTML). The controller may make API calls or make database queries (SQL) using functions defined in the Model. The name of the Controller file and class should be one word and the first word must be capitalized. If not, your app may run locally but webservers may not read your controller.

In the example below, we create a controller called “Users.” When the controller is called, the __constructor() and index() function are automatically called. Within the index() function, we call $this->load->view(‘home’, $data) to load the HTML template and passes in $data to the template.

//Yourcontroller.phpclass Users extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$data = array(
key => value,
key2 => value2,
key3 => value3,
)
$this->load->view('home', $data);
}
}

View: A view is the webpage that contains HTML code and Javascript code. When your application gets large enough, you may have a separate file for your Javascript code. You may also implement native PHP code as it is a PHP file. As you can see, in the controller above, this->load->view(‘home’, $data) to load the HTML template and passes in $data to the template.

//home.php
<div>
<p>
<?php
echo "Home Page";
?>
</p>
</div>

Model: The model contains functions for API calls and database queries. This is an example of a function that will make a POST API request. The code below looks daunting but it’s just syntax to make a CURL POST request. Now that we’ve defined a function in our Model, we can call this function in our Controller.

function sampleCURL($data = array())
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "yourURLString",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "Name=yourName",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/x-www-form-urlencoded"),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
$result['err'] = json_decode($err, TRUE);
$result['error_message'] = '';
$tmp = json_decode($response, TRUE);
if ($tmp['succeeded']) {
$result['success'] = TRUE;
} else {
$result['success'] = FALSE;
$result['error_message'] = isset($tmp['errors'][0]['description']) ? $tmp['errors'][0]['description'] : 'Error sending code.';
}
return $result;
}

Updated Controller

//Yourcontroller.php
class Users extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$data = array(
key => value,
key2 => value2,
key3 => value3,
)
$this->load->view('home', $data);
$response = $this->api_model->sampleCURL($data);
}
}

--

--

--

HTML, JavaScript, and CSS Tutorials

Recommended from Medium

#002 新增GitHub帳號 — Xcode

Early praise for Release It! Second Edition

HIMO World Airdrop

2/28/2020 — Update — Unmask employee bank account information

The Value of Focused, Single-Purpose Tests

images/aside-icons/tip.png

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Lance Watanabe

Lance Watanabe

More from Medium

PHP -> A funny thing about copying & referencing objects.

pre_fetch_count in common cases in PHP

What is Ory Hydra?

INTRODUCTION TO PHP