CodeIgniter Part 1: Initial Setup
Repository
CodeIgniter Github Repository
CodeIgniter is a PHP framework which follows the MVC (model view controller ) approach which provides developers an elegant toolkit to build full featured web applications. Through this tutorial series we will be moving from the very basics up to building full featured web applications using this framework.
Level of Difficulty
Basic
What you will learn:
- Setting up a basic CI-project from scratch
- Setting up the folder structure for both development and production environments
- Configuring the database and environment variables for development and production
Requirements: - A good knowledge of PHP OOP Programming.
- Basic knowledge of MVC pattern, this is not compulsory as it will be covered in this tutorial series
Getting started
- Download codeigniter
you can download it here https://codeigniter.com/download
once you are on the download page click on the link Download CodIgniter V N0
As at this tutorial the most stable version is 3 as 4 is still under development, so click on Download CodIgniter 3 which will be downloaded in zip format as follows CodeIgniter-3.1.8.zip
Add the downloaded project to your local server
Once the download is completed extract it and rename it to your desired project name, I will be naming mine firstproject. Now move this folder to your local server root directory I’m using XAMPP as my local server, there are many of them out there such as wamp, lamp, mamp etc. for each of these there are tutorials on how they can be used. Before using any ensure you read through the documentation and usage, now I have mine in the following directory C:\xampp\htdocs\firstproject.View your project on the browser
If you’ve followed all the above steps carefully, then head up to the browser and enter your project name through local host the same way you access your other php projects. Here is how my url looks:
http://localhost:81/firstproject/
with the screen display:
If you are seeing this screen, then congratulations you’ve just created your first CodeIgniter project
Final configurations:
If we leave the project this way we are likely run into the following problems as the project grows:
- All urls must have index.php attached to them, for them to work appropriately
- You will have to manually enter you server url as the base url when moving to development
- You will have broken links when https is required and ur base url is using http
- You will have to always update your database credentials when moving to production environment and back to local.
Let’s quickly fix these challenges one at a time.
Before then open your project folder using a text editor which you are quite familiar with I’m using visual studio code it’s quite good as it has many helper functionalities including version control system.
If you’ve followed me correctly then your project should now have the folder structure as below:
You can remove the user_guide as it is readily available online here https://www.codeigniter.com/user_guide/, now you folder structure should look like this:
Following our folder structure open up applications/config
- Create two sub folders development and Production in this config folder.
- Move config.php and database.php files from the config folder into the development and copy them into the production.
Your folder structure for the config structure should now look like this:
- Open the config file of the development folder and locate the following code:
php $config['base_url'] = '';
This means you have to explicitly enter your site base_url in our case it will be
$config['base_url'] = 'localhost:81/firstproject';
And when you move to a production server you will have to update it to the domain address.
Let’s make this dynamic so that it will automatically pick the server url wherever it is placed.
Replace this line of code
$config['base_url'] = '';
With
$config['base_url'] = "http://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= preg_replace('@/+$@', '', dirname($_SERVER['SCRIPT_NAME'])).'/';
From the above the variable
php $_SERVER['HTTP_HOST'];
means the current server host
If I var dump this in the index.php file it will result to localhost:81 in my case
Which means the base_url will be http://localhost:81
And for the second path
Let’s take it bit by bit, firstly
preg_replace('@/+$@', '', ```
This checks for special characters in the domain name and eliminates them
```phpdirname($_SERVER['SCRIPT_NAME'])).'/```
if I var_dump this it will result to /firstproject/
with these in place our base url will become http://localhost:81/firstproject and when we move to a live environment it will also adapt to the current host name.
repeat these changes for the production folders as well, if the live environment has SSL all you need to add is an s in the http so it becomes
```php
$config['base_url'] = "https://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= preg_replace('@/+$@', '', dirname($_SERVER['SCRIPT_NAME'])).'/';
Don’t touch the database.php yet as we are not connecting to a database yet.
- No lets specify the environment we are at each time of the project phase so that we can tell CI either to display error or not depending on the environment we are in.
Open the root index.php file as shown in the figure below highlighted in blue.
In this file locate the code
phpdefine('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
And replace it with
switch ($_SERVER['SERVER_NAME']) {
case 'localhost':
$env = 'development';
break;
default:
$env = 'production';
break;
}
define('ENVIRONMENT', $env);
From the above, the variable ($_SERVER['SERVER_NAME']) specifies the server name either localhost or live server host this will enable us to define our environment variable as above.
Once we have defined our environment variable we can then instruct CI to only show error on development environment.
To do this, locate the code snippet in the same file
{
case 'development':
error_reporting(-1);
ini_set('display_errors', 1);
break;
case 'testing':
case 'production':
ini_set('display_errors', 0);
if (version_compare(PHP_VERSION, '5.3', '>='))
{
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
}
else
{
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);
}
break;
default:
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'The application environment is not set correctly.';
exit(1); // EXIT_ERROR
}
And replace it with the below code:
if(defined('ENVIRONMENT')){
switch (ENVIRONMENT)
{
case 'development':
error_reporting(-1);
ini_set('display_errors', 1);
break;
case 'testing':
case 'production':
ini_set('display_errors', 0);
if (version_compare(PHP_VERSION, '5.3', '>='))
{
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
}
else
{
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);
}
break;
default:
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'The application environment is not set correctly.';
exit(1); // EXIT_ERROR
}
}
Here we have explicitly made reference to our ENVIRONMENT variable, so that errors should only be shown when in development environment.
- Lastly let’s fix the case of having index.php attached to our url.
Open the .htaccess file in the root directory as shown below
Replace the entire script with this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
The last line removes the index.php from the url allowing you to directly call your controllers. For this post inn particular we won’t go in-depth in this but with subsequent ones as this is just an initial set up guide.
With all these set up properly, you are ready to build that awesome app.
Git hub repository for this project
Thank you for your contribution.
While I liked the content of your contribution, I would still like to extend few advices for your upcoming contributions:
Looking forward to your upcoming tutorials.
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
Hey @portugalcoin
Here's a tip for your valuable feedback! @Utopian-io loves and incentivises informative comments.
Contributing on Utopian
Learn how to contribute on our website.
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!
This is really helpful @mrobele. Gained so much from it
thanks
Well explained codeigniter initial setup instructions..
I'm glad it's clear to you, thank you
I'm glad it's clear to you, thank you
Hey @mrobele
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!