LavaLust is a lightweight Web Framework - (using MVC pattern) - for people who are developing web sites using PHP. It helps you write code easily using Object-Oriented Approach. It also provides set of libraries for commonly needed tasks, as well as a helper functions to minimize the amount of time coding.
Lavalust uses MVC pattern. MVC is short for Model, View, and Controller. MVC is a popular way of organizing your code. The big idea behind MVC is that each section of your code has a purpose, and those purposes are different. Some of your code holds the data of your app, some of your code makes your app look nice, and some of your code controls how your app functions.
Installation
Installation of Lavalust is easy as 1...2...3...
Server Requirements
Requires PHP version >= 7.4
MySQL 5 or higher
PDO is installed
Enaled mod_rewrite(optional but recommended for security purposes)
Installation Instruction
Manual Installation
You can install LavaLust in four steps
Unzip the package
Upload the LavaLust folders and files to your server.
Open the app/config/config.php file with a text editor and set your base URL.
If you intend to use a database, open the app/config/database.php file with a text editor and set yourdatabase settings
Using Git
Install Git
Select the server folder then open a terminal. Type "git clone https://github.com/ronmarasigan/LavaLust" and hit enter.
Open the app/config/config.php file with a text editor and set your base URL.
If you intend to use a database, open the app/config/database.php file with a text editor and set yourdatabase settings
To add more flavor in your security, you can change the $system_path and $application_folder name to something new. You can do this by changing their values inside index.php. You can also move them outside public_html directory for better security.
If you plan to do so, you will need to change this two lines inside index.php. Change ROOT_DIR to the full path of where you placed your scheme and app folder. e.g. '/www/MyUser/scheme'.
Replace all files and directories in your scheme/ directory.
Note
There are some changes in config.php file. Please backup your old then replace it by the new one. After replacing, update it based on the your current config.
Note
Routing in LavaLust4 is way different compare to LavaLust3 and below. It is now somehow similar to the modern routing of other fullstack framework.
Before performing an update you should take your site offline by replacing the index.php file with a static one.
LavaLust Overview
The following pages describe the broad concepts behind LavaLust:
Getting Started With LavaLust
I made this documentation as simple and clear as posible.
You need first to do install LavaLust, then read all the topics one by one.
I also provide examples for you to try.
Once you get familiarize with the flow, you can proceed to the different libraries and helpers availble in the framework.
LavaLust at a Glance
Free, Fast and Light Weight
LavaLust is an application framework written in PHP that was designed for faster project development. It has built-in libraries and helpers that can minimize the amount of time needed to code for something. LavaLust is also OPEN-SOURCE under MIT license. Unlike other frameworks out there, LavaLust is very LIGHT WEIGHT and FAST.
Mode-View-Controller
The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the model, the view, and the controller. Each of these components are built to handle specific development aspects of an application. MVC is one of the most frequently used industry-standard web development framework to create scalable and extensible projects.
Generates Clean URLs
The URLs generated by LavaLust are clean and search-engine friendly. Rather than using the standard “query string” approach to URLs that is synonymous with dynamic systems, LavaLust uses a segment-based approach:
example.com/news/article/345
Note
By default the index.php file is included in the URL but it can be removed using a simple .htaccess file.
Support Features
Model-View-Controller Pattern
Super Light Weight
Simple Query Builder Class
Form Data Validation
Session Management
Simple Email Sending
File Uploading Class
Performance Class
Config Class
Simple Logger Class
Pagination
Simple Page Caching
File Downloading Class
Search-engine Friendly URLs
Some helper functions
Application Flow Chart
The following graphic illustrates how data flows throughout the system:
The index.php serves as the front controller, initializing the base
resources needed to run LavaLust.
The Router examines the HTTP request to determine what should be done
with it.
If a cache file exists, it is sent directly to the browser, bypassing
the normal system execution.
Security. Before the application controller is loaded, the HTTP
request and any user submitted data is filtered for security.
The Controller loads the model, core libraries, helpers, and any
other resources needed to process the specific request.
The finalized View is rendered then sent to the web browser to be
seen. If caching is enabled, the view is cached first so that on
subsequent
Model-View-Controller
LavaLust is based on the Model-View-Controller development pattern. MVC is a software approach that separates application logic from presentation. In practice, it permits your web pages to contain minimal scripting since the presentation is separate from the PHP scripting.
The Model represents your data structures. Typically your model
classes will contain functions that help you retrieve, insert, and
update information in your database.
The View is the information that is being presented to a user. A
View will normally be a web page, but in LavaLust, a view can also
be a page fragment like a header or footer. It can also be an RSS
page, or any other type of “page”.
The Controller serves as an intermediary between the Model, the
View, and any other resources needed to process the HTTP request and
generate a web page.
General Topics
We will discuss here all the topics that will be needed for better understanding of LavaLust Framework.
LavaLust URLs
URLs in LavaLust are designed using a segment-based approach for better search-engine optimization unlike the standard "query string" approach:
example.com/news/article/345
URL Structure
Base URL contains only the Hostname
When you have the Base URL https://www.example.com/ and imagine the following URL:
https://www.example.com/blog/news/2022/10?page=2
We use the following terms:
Term
Example
Description
Base URL
https://www.example.com/
Base URL is often denoted as baseURL.
URI Path
/blog/news/2022/10
Route Path
/blog/news/2022/10
The URI path relative to the Base URL. It is also called as URI string.
The URI path relative to the Base URL. It is also called as URI string.
Query
page=2
Removing the index.php file
By default, the index.php file will be included in your URLs:
example.com/index.php/news/article/my_article
If your Apache server has mod_rewrite enabled, you can easily remove this file by using a .htaccess file with some simple rules. Here is an example of such a file, using the “negative” method in which everything is redirected except the specified items:
In the above example, any HTTP request other than those for existing directories and existing files is treated as a request for your index.php file.
Note
These specific rules might not work for all server configurations.
Note
Make sure to also exclude from the above rule any assets that you might need to be accessible from the outside world.
Note
Open app/config/config.php and find the $config['index_page'] = 'index.php'; make it empty.
Controllers and Routing
What is URI Routing?
URI Routing associates a URI with a controller’s method.
LavaLust uses Defined Route Routing. You can define routes manually. It allows flexible URL.
Setting Routing Rules
Routing rules are defined in the app/config/routes.php file. In it you’ll see that it creates an instance of the Router class ($routes) that permits you to specify your own routing criteria. Routes can be specified using placeholders or Regular Expressions.
When you specify a route, you choose a method to corresponding to HTTP verbs (request method). If you expect a GET request, you use the get() method:
<?php$router->get('/', 'Welcome::index');
A route takes the Route Path (URI path relative to the BaseURL. /) on the left, and maps it to the Route Handler (controller and method Home::index) on the right, along with any parameters that should be passed to the controller.
The controller and method should be listed in the same way that you would use a static method, by separating the class and its method with a double-colon, like Users::list.
A URL containing the word journals in the first segment will be mapped to the \app\controllers\Blogs class, and the default method, which is usually index():
<?php$router->get('journals', 'Blogs');
A URL with product as the first segment, and anything in the second will be mapped to the \app\controllers\Catalog class and the productLookup() method:
Controllers are the heart of your application, as they determine how HTTP requests should be handled.
A URL with product as the first segment, and a number in the second will be mapped to the \app\controllers\Catalog class and the productLookupByID() method passing in the match as a variable to the method:
You can supply multiple verbs that a route should match by passing them in as an array to the match() method:
<?php$router->match('products', 'Product::feature', 'GET|POST');
//the above code is same with<?php$router->match('products', 'Product::feature', ['GET', 'POST]);
Using Closures
You can use an anonymous function, or Closure, as the destination that a route maps to. This function will be executed when the user visits that URI. This is handy for quickly executing small tasks, or even just showing a simple view:
<?php$router->get('feed', function () {
$rss = newRSSFeeder();
return$rss->feed('general');
});
Route Parameter
Sometimes you will need to capture segments of the URI within your route. For example, you may need to capture a user's ID from the URL. You may do so by defining route parameters:
<?php$route->get('user/{id}', function ($id) {
return'User '.$id;
});
You may define as many route parameters as required by your route:
$router->get('/posts/{post}/comments/{comment}', function ($postId, $commentId) {
// ...
});
Route parameters are always encased within {} braces and should consist of alphabetic characters. Underscores (_) are also acceptable within route parameter names. Route parameters are injected into route callbacks / controllers based on their order - the names of the route callback / controller arguments do not matter.
Regular Expression Constraints
You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained:
$router->get('/user/{name}', function (string$name) {
// ...
})->where('name', '[A-Za-z]+');
$router->get('/user/{id}', function (string$id) {
// ...
})->where('id', '[0-9]+');
$router->get('/user/{id}/{name}', function (string$id, string$name) {
// ...
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
For convenience, some commonly used regular expression patterns have helper methods that allow you to quickly add pattern constraints to your routes:
$router->get('/user/{id}/{name}', function ($id, $name) {
// ...
})->where_number('id')->where_alpha('name');
$router->get('/user/{name}', function ($name) {
// ...
})->where_alphanumeric('name');
$router->get('/user/{id}', function ($id) {
// ...
})->where_uuid('id');
$router->get('/user/{id}', function ($id) {
//
})->where_ulid('id');
$router->get('/category/{category}', function ($category) {
// ...
})->where_in('category', ['movie', 'song', 'painting']);
If the incoming request does not match the route pattern constraints, a 404 HTTP response will be returned.
Grouping Routes
You can group your routes under a common name with the group() method. The group name becomes a segment that appears prior to the routes defined inside of the group. This allows you to reduce the typing needed to build out an extensive set of routes that all share the opening string, like when building an admin area:
<?php$router->group('admin', function() use ($router) {
$router->get('users', 'Users::index');
$router->get('blog', 'Blog::index');
});
Note
You can use lava_instance() in routes.php by passing it to a variable then add it by using the "use" keyword.
<?php$_lava =& lava_instance();
$router->get('/', function() use ($_lava) {
$_lava->call->view('welcome_page');
});
This would prefix the users and blog URIs with admin, handling URLs like admin/users and admin/blog.
What is a Controller?
Controllers are the heart of your application, as they determine how HTTP requests should be handled.
A Controller is simply a class file that handles a HTTP request. URI Routing associates a URI with a controller.
Protecting Methods
In some cases, you may want certain methods hidden from public access. To achieve this, simply declare the method as private or protected. That will prevent it from being served by a URL request.
For example, if you were to define a method like this for the Helloworld controller:
<?phpclassHelloworldextendsController{
protectedfunctionutility()
{
// some code
}
}
and to define a route (helloworld/utitilty) for the method. Then trying to access it using the following URL will not work:
example.com/index.php/hellowworld/utility
Let’s try it: Hello World!
Let’s create a simple controller so you can see it in action. Using your text editor, create a file called Helloworld.php, and put the following code in it:
Default controller and method was already define as the default routes inside app\config\routes.php file. You can update it to change it to new one.
$router->get('/', 'Welcome::index');
Class Constructors
If you intend to use a constructor in any of your Controllers, you MUST place the following line of code in it:
parent::__construct();
The reason this line is necessary is because your local constructor will be overriding the one in the parent controller class so we need to manually call it.
Example:
<?phpclassHelloworldextendsController{
publicfunction__construct()
{
parent::__construct();
// Your own constructor code
}
}
Constructors are useful if you need to set some default values, or run a default process when your class is instantiated. Constructors can’t return a value, but they can do some default work.
That’s it!
That, in a nutshell, is all there is to know about controllers.
Views
A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be embedded within other views (within other views, etc., etc.) if you need this type of hierarchy.
Views are never called directly, they must be loaded by a controller. Remember that in an MVC framework, the Controller acts as the traffic cop, so it is responsible for fetching a particular view. If you have not read the Controllers page you should do so before continuing.
Using the example controller you created in the controller page, let’s add a view to it.
Creating a View
Using your text editor, create a file called blogview.php, and put this in it:
<html><head><title>My Blog</title></head><body><h1>Welcome to my Blog!</h1></body></html>
Then save the file in your app/views/ directory.
Loading a View
To load a particular view file you will use the following method:
$this->call->view('name');
Where name is the name of your view file.
Note
The .php file extension does not need to be specified unless you use something other than .php.
Now, open the controller file you made earlier called Blog.php, and replace the echo statement with the view loading method:
If you visit your site using the URL you did earlier you should see your new view. The URL was similar to this:
example.com/index.php/blog/
Loading multiple views
LavaLust will intelligently handle multiple calls to $this->call->view() from within a controller. If more than one call happens they will be appended together. For example, you may wish to have a header view, a menu view, a content view, and a footer view. That might look something like this:
In the example above, we are using “dynamically added data”, which you will see below.
Storing Views within Sub-directories
Your view files can also be stored within sub-directories if you prefer that type of organization. When doing so you will need to include the directory name loading the view. Example:
$this->call->view('directory_name/file_name');
Adding Dynamic Data to the View
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading method. Here is an example using an array:
If you use an object, the class variables will be turned into array elements.
Let’s try it with your controller file. Open it add this code:
<?phpclassBlogextendsController{
publicfunctionindex()
{
$data['title'] = "My Real Title";
$data['heading'] = "My Real Heading";
$this->call->view('blogview', $data);
}
}
Now open your view file and change the text to variables that correspond to the array keys in your data:
<?php echo $title;?>
Then load the page at the URL you’ve been using and you should see the variables replaced.
Creating Loops
The data array you pass to your view files is not limited to simple variables. You can pass multi dimensional arrays, which can be looped to generate multiple rows. For example, if you pull data from your database it will typically be in the form of a multi-dimensional array.
Here’s a simple example. Add this to your controller:
<?phpclassBlogextendsController{
publicfunctionindex()
{
$data['todo_list'] = array('Clean House', 'Call Mom', 'Run Errands');
$data['title'] = "My Real Title";
$data['heading'] = "My Real Heading";
$this->call->view('blogview', $data);
}
}
Now open your view file and create a loop:
<?php echo $title;?>
My Todo List
Note
You’ll notice that in the example above we are using PHP’s alternative syntax. If you are not familiar with it you can read about it here.
Models
Models are PHP classes that are designed to work with information in your database. For example, let’s say you use LavaLust to manage a blog. You might have a model class that contains functions to insert, update, and retrieve your blog data. Here is an example of what such a model class might look like:
The methods in the above example use the Query Builder database methods.
Note
For the sake of simplicity in this example we’re using $_POST directly. This is generally bad practice, and a more common approach would be to use the IO Library $this->io->post('title').
Anatomy of a Model
Model classes are stored in your app/models/ directory.
The basic prototype for a model class is this:
classModel_nameextendsModel{
}
Where Model_name is the name of your class. Class names must have the first letter capitalized with the rest of the name lowercase. Make sure your class extends the base Model class.
The file name must match the class name. For example, if this is your class:
classUser_nameextendsModel{
}
Your file will be this:
app/models/User_model.php
Loading a Model
Your models will typically be loaded and called from within your controller methods. To load a model you will use the following method:
$this->call->model('model_name');
If your model is located in a sub-directory, include the relative path from your models directory. For example, if you have a model located at application/models/blog/Queries.php you’ll load it using:
$this->load->model('blog/queries');
Once loaded, you will access your model methods using an object with the same name as your class:
If you find that you need a particular model globally throughout your application, you can tell LavaLust to auto-load it during system initialization. This is done by opening the app/config/autoload.php file and adding the model to the autoload array.
Connecting to your Database
When a model is loaded it does NOT connect automatically to your database. The following options for connecting are available to you:
You can connect using the standard database methods described here, either from within your Controller class or your Model class.
$this->load->model('model_name');
Helpers
Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular category. There are URL Helpers, that assist in creating links, there are Form Helpers that help you create form elements, Cookie Helpers set and read cookies, File Helpers help you deal with files, etc.
Unlike most other systems in LavaLust, Helpers are not written in an Object Oriented format. They are simple, procedural functions. Each helper function performs one specific task, with no dependence on other functions.
LavaLust does not load Helper Files by default, so the first step in using a Helper is to load it. Once loaded, it becomes globally available in your controller and views.
Helpers are typically stored in your scheme/helpers, or app/helpers directory. LavaLust will look first in your app/helpers directory. If the directory does not exist or the specified helper is not located there LavaLust will instead look in your global scheme/helpers/ directory.
Loading
Loading a helper file is quite simple using the following method:
$this->call->helper('name');
Where name is the file name of the helper, without the .php file extension or the “helper” part.
For example, to load the URL Helper file, which is named url_helper.php, you would do this:
$this->call->helper('url');
A helper can be loaded anywhere within your controller methods (or even within your View files, although that’s not a good practice), as long as you load it before you use it. You can load your helpers in your controller constructor so that they become available automatically in any function, or you can load a helper in a specific function that needs it.
Note
The Helper loading method above does not return a value, so don't try to assign it to a variable. Just use it as shown.
Loading Multiple Helpers
If you need to load more than one helper you can specify them in an array, like this:
Once you’ve loaded the Helper File containing the function you intend to use, you’ll call it the way you would a standard PHP function.
For example, to create a link using the redirect() function in one of your view files you would do this:
<?phpredirect('blog/comments');?>
Where “blog/comments” is the URI to the controller/method you wish to redirect to.
Now What?
In the Table of Contents you’ll find a list of all the available Helper Files. Browse each one to see what they do.
Libraries
All of the available libraries are located in your scheme/libraries/ directory. In most cases, to use one of these classes involves initializing it within a controller using the following initialization method:
$this->call->library('class_name');
Where ‘class_name’ is the name of the class you want to invoke. For example, to load the Form Validation Library you would do this:
$this->call->library('Form_validation');
Once initialized you can use it as indicated in the user guide page corresponding to that class.
Additionally, multiple libraries can be loaded at the same time by passing an array of libraries to the load method.
When we use the term “Libraries” we are normally referring to the classes that are located in the libraries directory and described in the Class Reference of this user guide. In this case, however, we will instead describe how you can create your own libraries within your app/libraries directory in order to maintain separation between your local resources and the global framework resources.
As an added bonus, LavaLust permits your libraries to extend native classes if you simply need to add some functionality to an existing library. Or you can even replace native libraries just by placing identically named versions in your app/libraries directory.
In summary:
You can create entirely new libraries.
You can replace native libraries.
The page below explains these two concepts in detail.
Note
Do not attempt to replace the Database Class if you don't know what you are doing. There are variables that rely on it if loaded.
Storage
Your library classes should be placed within your app/libraries directory, as this is where LavaLust will look for them when they are initialized.
Naming Conventions
File names must be capitalized. For example: Myclass.php
Class declarations must be capitalized. For example: class Myclass
Class names and file names must match.
The Class File
Classes should have this basic prototype:
<?phpdefined('PREVENT_DIRECT_ACCESS') OR exit('No direct script access allowed');
classSomeclass{
publicfunctionsome_method()
{
}
}
Note
We are using the name Someclass purely as an example.
Using Your Class
From within any of your Controller methods you can initialize your class using the standard:
$this->call->library('someclass');
Where someclass is the file name, without the “.php” file extension. You can submit the file name capitalized or lower case. LavaLust doesn’t care.
Once loaded you can access your class using the lower case version:
$this->someclass->some_method(); // Object instances will always be lower case
Passing Parameters When Initializing Your Class
In the library loading method you can dynamically pass data as an array via the second parameter and it will be passed to your class constructor:
If you use this feature you must set up your class constructor to expect data:
<?phpdefined('PREVENT_DIRECT_ACCESS') OR exit('No direct script access allowed');
classSomeclass{
publicfunction__construct($params)
{
// Do something with $params
}
}
Utilizing LavaLust Resources within Your Library
To access LavaLust native resources within your library use the lava_instance() method. This method returns the LavaLust super object.
Normally from within your controller methods you will call any of the available LavaLust methods using the $this construct:
$this->call->helper('url');
$this->call->library('session');
// etc.
$this, however, only works directly within your controllers, your models, or your views. If you would like to use LavaLust classes from within your own custom classes you can do so as follows:
First, assign the LavaLust object to a variable:
$LAVA =& lava_instance();
Once you’ve assigned the object to a variable, you’ll use that variable instead of $this:
$LAVA->call->helper('url');
$LAVA->call->library('session');
// etc.
Note
You’ll notice that the above lava_instance() function is being passed by reference:
$LAVA =& lava_instance();
This is very important. Assigning by reference allows you to use the original LavaLust object rather than creating a copy of it.
However, since a library is a class, it would be better if you take full advantage of the OOP principles. So, in order to be able to use the LavaLust super-object in all of the class methods, you’re encouraged to assign it to a property instead:
classExample_library{
protected$LAVA;
// We'll use a constructor, as you can't directly call a function// from a property definition.publicfunction__construct()
{
// Assign the LavaLust super-object$this->LAVA =& lava_instance();
}
publicfunctionfoo()
{
$this->LAVA->call->helper('url');
redirect();
}
}
Replacing Native Libraries with Your Versions
Simply by naming your class files identically to a native library will cause LavaLust to use it instead of the native one. To use this feature you must name the file and the class declaration exactly the same as the native library. For example, to replace the native Email library you’ll create a file named app/libraries/Email.php, and declare your class with:
classEmail{
}
To load your library you’ll see the standard loading method:
$this->call->library('email');
Auto-loading Resources
LavaLust comes with an “Auto-load” feature that permits libraries, helpers, and models to be initialized automatically every time the system runs. If you need certain resources globally throughout your application you should consider auto-loading them for convenience.
The following items can be loaded automatically:
Classes found in the libraries/ directory
Helper files found in the helpers/ directory
Models found in the models/ folder
To autoload resources, open the app/config/autoload.php file and add the item you want loaded to the autoload array. You’ll find instructions in that file corresponding to each type of item.
Note
Do not include the file extension (.php) when adding items to the autoload array.
Additionally, if you want LavaLust to use a Composer auto-loader, just set $config['composer_autoload'] to TRUE or a custom path in app/config/config.php.
Security
This page describes some “best practices” regarding web security, and details LavaLust's internal security features.
URI Security
LavaLust is fairly restrictive regarding which characters it allows in your URI strings in order to help minimize the possibility that malicious data can be passed to your application. URIs may only contain the following:
Alpha-numeric text (latin characters only)
Tilde: ~
Percent sign: %
Period: .
Colon: :
Underscore: _
Dash: -
Space
display_errors
In production environments, it is typically desirable to “disable” PHP’s error reporting by setting the internal display_errors flag to a value of 0. This disables native PHP errors from being rendered as output, which may potentially contain sensitive information.
Setting LavaLust's ENVIRONMENT constant in index.php to a value of ‘production’ will turn off these errors. In development mode, it is recommended that a value of ‘development’ is used.
Best Practices
Before accepting any data into your application, whether it be POST data from a form submission, COOKIE data, URI data, XML-RPC data, or even data from the SERVER array, you are encouraged to practice this three step approach:
Validate the data to ensure it conforms to the correct type, length, size, etc.
Filter the data as if it were tainted.
Escape the data before submitting it into your database or outputting it to a browser.
XSS Filtering
LavaLust has html_escape() function that escapes string or array to prevent XSS. If you are planning to accept html elements/tags from users then you might need to use other libraries such as HTMLPurifier.
CSRF protection
CSRF stands for Cross-Site Request Forgery, which is the process of an attacker tricking their victim into unknowingly submitting a request.
LavaLust provides CSRF protection out of the box, which will get automatically triggered for every non-GET HTTP request, but also needs you to create your submit forms in a certain way. You can call security helper and use csrf_field() function to add hidden with csrf token inside a form that can be check automatically or manually.
To automatically check the csrf token added and submitted using csrf_field() function:
$config['csrf_protection'] = TRUE;
Password handling
It is critical that you handle passwords in your application properly.
Unfortunately, many developers don’t know how to do that, and the web is full of outdated or otherwise wrongful advices, which doesn’t help.
We would like to give you a list of combined do’s and don’ts to help you with that. Please read below.
DO NOT store passwords in plain-text format. Always hash your passwords.
DO NOT use Base64 or similar encoding for storing passwords. This is as good as storing them in plain-text. Really. Do hashing, not encoding. Encoding, and encryption too, are two-way processes. Passwords are secrets that must only be known to their owner, and thus must work only in one direction. Hashing does that - there’s no un-hashing or de-hashing, but there is decoding and decryption.
DO NOT use weak or broken hashing algorithms like MD5 or SHA1. These algorithms are old, proven to be flawed, and not designed for password hashing in the first place. Also, DON’T invent your own algorithms. Only use strong password hashing algorithms like BCrypt, which is used in PHP’s own Password Hashing functions.
DO NOT ever display or send a password in plain-text format! Even to the password’s owner, if you need a “Forgotten password” feature, just randomly generate a new, one-time (this is also important) password and send that instead.
DO NOT put unnecessary limits on your users’ passwords. If you’re using a hashing algorithm other than BCrypt (which has a limit of 72 characters), you should set a relatively high limit on password lengths in order to mitigate DoS attacks - say, 1024 characters. Other than that however, there’s no point in forcing a rule that a password can only be up to a number of characters, or that it can’t contain a certain set of special characters. Not only does this reduce security instead of improving it, but there’s literally no reason to do it. No technical limitations and no (practical) storage constraints apply once you’ve hashed them, none!
Validate input data
LavaLust has a Form Validation Library that assists you in validating, filtering, and prepping your data.
Even if that doesn’t work for your use case however, be sure to always validate and sanitize all input data. For example, if you expect a numeric string for an input variable, you can check for that with is_numeric() or ctype_digit(). Always try to narrow down your checks to a certain pattern.
Have it in mind that this includes not only $_POST and $_GET variables, but also cookies, the user-agent string and basically all data that is not created directly by your own code.
Escape all data before database insertion
Never insert information into your database without escaping it. It was already done if you use the native Database Class. It uses prepared statements for mySQL database.
Hide your files
Another good security practice is to only leave your index.php and “assets” (e.g. .js, css and image files) under your server’s webroot directory (most commonly named “htdocs/”). These are the only files that you would need to be accessible from the web.
Allowing your visitors to see anything else would potentially allow them to access sensitive data, execute scripts, etc.
If you’re not allowed to do that, you can try using a .htaccess file to restrict access to those resources.
LavaLust will have an index.html file in all of its directories in an attempt to hide some of this data, but have it in mind that this is not enough to prevent a serious attacker.
Libraries
We will discuss here all the topics in LavaLust Framework Libraries.
Performance Class
LavaLust has a Performance class that is always active, enabling the time difference between any two marked points to be calculated.
Note
This class is initialized automatically by the system so there is no need to do it manually.
In addition, the performance is always started the moment the framework is invoked, and ended by the output class right before sending the final view to the browser, enabling a very accurate timing of the entire system execution to be shown.
Using the Performance Class
The Performance class can be used within your controllers , views, or your models. The process for usage is this:
Mark a start point
Mark an end point
Run the “elapsed time” function to view the results
Here’s an example using real code:
$this->performance->start('referrence_name');
// Some code happens here$this->performance->stop('referrence_name');
echo$this->performance->elapsed_time('referrence_name');
Note
The words "tag" are arbitrary. They are simply words used to set the marker. You can use any words you want, and you can set multiple sets of markers. Consider this example:
$this->performance->start('dog');
// Some code happens here$this->performance->start('cat');
// More code happens here$this->performance->stop('cat');
$this->performance->start('bird');
// More code happens here$this->performance->stop('bird');
$this->performance->stop('dog');
echo$this->performance->elapsed_time('dog');
echo$this->performance->elapsed_time('cat');
echo$this->performance->elapsed_time('bird');
Displaying Total Execution Time
If you would like to display the total elapsed time from the moment LavaLust starts to the moment the final output is sent to the browser, simply place this in one of your view templates:
<?phpecho$this->performance->elapsed_time();?>
Displaying Memory Consumption
If your PHP installation is configured with –enable-memory-limit, you can display the amount of memory consumed by the entire system using the following code in one of your view file:
<?phpecho$this->performance->memory_usage();?>
Note
This function can only be used in your view files. The consumption will reflect the total memory used by the entire app.
Cache Class
LavaLust provide a simple caching system that can boost the performance of your application.
You can cache liraries or models and other object or array data. You need first to load Cache library by calling $this->call->library('cache').
You ca specify the cache folder by changing the configuration set in app/config/config.php file.
In the example above let say we have news_model class with get_news() method and two parameters: $param1 and $param2. get_news() method will be cached for 120 minutes as set as the 4th parameter in the example.
In the example above let say we have some_library class with calculate_something() method and three parameters: $foo, $bar and $bar. calculate_something() method will be cached for unlimited time if you do not specify it in the 4th parameter. This is also applicable in caching model.
Example: Caching a array or object
$data = array(
'id' => 1,
'username' => 'acidcore'
);
//Storing the data in a cache with a name "cached_name"$this->cache->write($data, 'cached_name');
//Retrieving a cache based on its name "cached_name"$data = $this->cache->get('cached_name');
Example: Delete specific cache by its name.
$this->cache->delete('cached_name');
In the example above, it will find and delete a cache inside cached folder based on its name "cached_name".
Example: Delete all cache
$this->cache->delete_all();
In the example above, it will delete all stored cache inside the cache direcotry.
In the example above, the cache version of the method get_news of news model will be deleted inside the cache directory. This will be the same if you'll use this in library classes.
Note
Model or library will be cached in unlimited time if you do not specify the time in minute before the cache expired. It was set as the fourth parameter in $this->cache->model() and $this->cache->library()
Email Class
Sending email is simple and easy to do. It only uses built-in mail() function of PHP. If you are planning to use more advanced features, you can use PHPMailer library.
Here is a basic example demonstrating how you might send email. Note: This example assumes you are sending the email from one of your controllers.
Here are the complete list of methods that can be used in sending email.
Method
Description
sender($sender_email, $sender_name)
$sender_email(required): Email address of the sender $sender_name: Name of the sender
reply_to($sender_email)
$sender_email: Email address of the where the reply should go.
recepient($receiver_email)
$receiver_email(required): Email address of the recepient
subject($subject)
$subject(required): Subject that will appear in the email
email_content($content, $email_type)
$content(required): Content of the email $email_type: default value is "plain". You can set it to "html" if your email has html content
attachment($path)
$path(required): Path where your attachment is located.
send()
It will send the email.
Form Validation Class
Before explaining LavaLust's approach to data validation, let’s describe the ideal scenario:
A form is displayed.
You fill it in and submit it.
If you submitted something invalid, or perhaps missed a required
item, the form is redisplayed containing your data along with an
error message describing the problem.
This process continues until you have submitted a valid form.
On the receiving end, the script must:
Check for required data.
Verify that the data is of the correct type, and meets the correct
criteria. For example, if a username is submitted it must be
validated to contain only permitted characters. It must be of a
minimum length, and not exceed a maximum length. The username can’t
be someone else’s existing username, or perhaps even a reserved word.
Etc.
Sanitize the data for security.
Pre-format the data if needed (Does the data need to be trimmed? HTML
encoded? Etc.)
Prep the data for insertion in the database.
Although there is nothing terribly complex about the above process, it usually requires a significant amount of code, and to display error messages, various control structures are usually placed within the form HTML. Form validation, while simple to create, is generally very messy and tedious to implement.
Form Validation Tutorial
In order to implement form validation you’ll need three things:
To try your form, visit your site using a URL similar to this one:
example.com/index.php/form/
If you submit the form you should simply see the form reload. That’s because you haven’t set up any validation rules yet.
Since you haven’t told the Form Validation class to validate anything yet, it returns FALSE (boolean false) by default. ``The run()`` method only returns TRUE if it has successfully applied your rules without any of them failing.
Explanation
You’ll notice several things about the above pages:
The form (myform.php) is a standard web form with a couple exceptions:
It uses a form helper to create the form opening. Technically, this
isn’t necessary. You could create the form using standard HTML.
However, the benefit of using the helper is that it generates the
action URL for you, based on the URL in your config file. This makes
your application more portable in the event your URLs change.
At the top of the form you’ll notice the following function call:
<?phpecho$this->form_validation->errors(); ?>
This function will return any error messages sent back by the validator. If there are no messages it returns an empty string.
The controller (Form.php) has one method: index(). This method runs the validation routine.
Based on whether the validation was successful it either presents the
form or the success page.
Setting Validation Rules
Let us take a look at our controller above. There are no validation rules set so we will
try to use some of the common validation methods.
In the above code, we use name() method to get the input to validate.
You should use the exact name you’ve given the form field. required(),
min_length(), max_length(),
matches() and valid_email() are all validation methods.
There is an optional parameter for each methods that is used to add custom error message.
Here are the complete list of methods that can be used in form validation.
Method
Description
name()
Form input name(require): The exact name you’ve given the form field for validation
pattern($name, $custom_error)
$name(required): The pattern you want to check if matched.
Possible value: url, alpha, words, alphanum, int, float, tel, file, folder, date_dmy, date_ymd, email
pattern($name, $custom_error)
$name(required): The pattern you want to check if matched.
Possible value: url, alpha, words, alphanum, int, float, tel, file, folder, date_dmy, date_ymd, email
custom_pattern($pattern, $custom_error)
$pattern(required): The pattern you want to check if matched. Use regex syntax.
required($custom_error)
Check if the field is not empty.
matches($field, $custom_error)
$field(required): Check if the field macthes with the current fields.
differs($field, $custom_error)
$field(required): Check if the field differs with the current fields.
is_unique($table, $field, $str, $custom_error)
$table(required): Database table to check if record does not already exists.
$fields(required): Table column name
$str (required): The value to check is exists
exact_length($length, $custom_error)
$length(required): The length of string to check.
min_length($length, $custom_error)
$length(required): The minimum length of string to check.
max_length($length, $custom_error)
$length(required): The max length of string to check.
valid_email($email, $custom_error)
email(required): The email address to check if valid.
alpha($custom_error)
Check if consists of alpha characters.
alpha_numeric($custom_error)
Check if consists of alpha-numeric characters.
alpha_numeric_space($custom_error)
Check if consists of alpha-numeric characters and spaces.
alpha_space($custom_error)
Check if consists of alpha characters and spaces.
alpha_numeric_dash($custom_error)
Check if consists of alpha-numeric characters and dashes.
numeric($custom_error)
Check if consists of numeric characters.
greater_than($value, $custom_error)
$value(required): The value to check if greater than the value of the input field.
greater_than_equal_to($value, $custom_error)
$value(required): The value to check if greater than or equal to the value of the input field.
less_than($value, $custom_error)
$value(required): The value to check if less than the value of the input field.
less_than_equal_to($value, $custom_error)
$value(required): The value to check if less than or equal to the value of the input field.
in_list($list, $custom_error)
$list(required): The value to check if within an array of values.
run()
Check if there is no errors while validating. If true, no errors found.
Note
$custom_error parameter accepts custom error message for each validation method.
Upload Class
LavaLust's File Uploading Class permits files to be uploaded. You can set various preferences, restricting the type and size of the files.
The Process
Uploading a file involves the following general process:
An upload form is displayed, allowing a user to select a file and
upload it.
When the form is submitted, the file is uploaded to the destination
you specify.
Along the way, the file is validated to make sure it is allowed to be
uploaded based on the preferences you set.
Once uploaded, the user will be shown a success message.
To demonstrate this process here is brief tutorial. Afterward you’ll
find reference information.
Creating the Upload Form
Using a text editor, create a form called upload_form.php. In it, place this code and save it to your app/views/ directory:
You’ll notice we are using a form helper to create the opening form tag.
File uploads require a multipart form, so the helper creates the proper
syntax for you. You’ll also notice we have an $error variable. This is
so we can show error messages in the event the user does something
wrong.
The Success Page
Using a text editor, create a form called upload_success.php. In it, place this code and save it to your app/views/ directory:
You’ll need a destination directory for your uploaded images. Create a directory at the root of your LavaLust installation called uploads and set its file permissions to 777.
Reference Guide
Like most other classes in LavaLust, the Upload class is initialized in your controller using the $this->call->library() method:
$this->call->library('upload');
Once the Upload class is loaded, the object will be available using: $this->upload
Setting Preferences
Similar to other libraries, you’ll control what is allowed to be upload based on your preferences. In the controller you built above you set the following preferences:
The above preferences should be fairly self-explanatory. Below is a table describing all available preferences.
Preferences
The following preferences are available. The default value indicates what will be used if you do not specify that preference.
Method
Description
allowed_extensions()
Allowed file extension. Use default if not set. array('gif', 'jpg', 'jpeg', 'png')
allowed_mimes()
Allowed mimes. Use default if not set. array('image/gif', 'image/jpg', 'image/jpeg', 'image/png')
set_dir()
Directory to store files
max_size()
Allowed maximum file size.
min_size()
Allowed minimum file size.
is_image()
Return true if the file is an image.
get_errors()
Return all errors.
do_upload()
Method to upload the file.
get_filename()
Return the filename of the uploaded file.
get_size()
Return the size of the uploaded file.
get_extension()
Return the file extension of the uploaded file.
ecrypt_name()
Encrypt the filename of the uploaded file.
Language Class
The Language Class provides functions to retrieve language files and lines of text for purposes of internationalization.
In your LavaLust scheme folder, you will find a language sub-directory containing a sample file for the english idiom. (en-US)
returnarray(
/**
* Pagination
*/'first_link' => '‹ First',
'next_link' => '>',
'prev_link' => '<',
'last_link' => 'Last ›',
'page_delimiter' => '/?page=',//if query string is enabled in your config, you can use something like `/?page=` to this'classes' => array('nav' => '', 'ul' => 'pagination', 'li' => 'page-item', 'a' => 'page-link'),//default for bootstrap 4. You can change the value according to your choice./**
* Other String to be translated here
*/'welcome' => 'Hello {username} {type}',
As you can see, there are default keys with value in english language. If you want to add language file and alter the values of each keys, you need to use two functions under language helper. lang() and language()
You can add language file inside app/language folder. For example you will add tl-PH.php and you will alter some values if selected as default language.
returnarray(
/**
* Pagination
*/'first_link' => '‹ Una',
'next_link' => '>',
'prev_link' => '<',
'last_link' => 'Huli ›',
'page_delimiter' => '/?page=',//if query string is enabled in your config, you can use something like `/?page=` to this'classes' => array('nav' => '', 'ul' => 'pagination', 'li' => 'page-item', 'a' => 'page-link'),//default for bootstrap 4. You can change the value according to your choice./**
* Other String to be translated here
*/'welcome' => 'Hello {username} {type}',
To use it as default language, you can call language helper and use the said two functions above.
In the example, you will see "‹ Una" and "Huli › instead of the "‹ First" and "Last ›" because you chose tl-PH upon using language() function.
Session Library
The Session class permits you maintain a user’s “state” and track their activity while they browse your site.
At the moment LavaLust comes with file session storage driver only:
Using the Session Class
Initializing a Session
Sessions will typically run globally with each page load, so the Session class should either be initialized in your controller constructors, or it can be auto-loaded by the system. For the most part the session class will run unattended in the background, so simply initializing the class will cause it to read, create, and update sessions when necessary.
To initialize the Session class manually in your controller constructor, use the $this->call->library() method:
$this->call->library('session');
Once loaded, the Sessions library object will be available using:
$this->session;
Important
Because the Loader Class is instantiated by LavaLust base controller, make sure to call parent::__construct() before trying to load a library from inside a controller constructor.
How do Sessions work?
When a page is loaded, the session class will check to see if valid session cookie is sent by the user’s browser. If a sessions cookie does not exist (or if it doesn’t match one stored on the server or has expired) a new session will be created and saved.
If a valid session does exist, its information will be updated. With each update, the session ID may be regenerated if configured to do so.
It’s important for you to understand that once initialized, the Session class runs automatically. There is nothing you need to do to cause the above behavior to happen. You can, as you’ll see below, work with session data, but the process of reading, writing, and updating a session is automatic.
What is Session Data?
Session data is simply an array associated with a particular session ID (cookie).
If you’ve used sessions in PHP before, you should be familiar with PHP’s $_SESSION superglobal (if not, please read the content on that link).
LavaLust gives access to its session data through the same means, as it uses the session handlers’ mechanism provided by PHP. Using session data is as simple as manipulating (read, set and unset values) the $_SESSION array.
In addition, LavaLust also provides 2 special types of session data that are further explained below: flashdata and tempdata.
Retrieving Session Data
Any piece of information from the session array is available through the $_SESSION superglobal:
$_SESSION['item']
Or through the Session library method:
$this->session->userdata('item');
Where item is the array key corresponding to the item you wish to fetch. For example, to assign a previously stored ‘name’ item to the $name variable, you will do this:
The userdata() method returns NULL if the item you are trying to access does not exist.
If you want to retrieve all of the existing userdata, you can simply omit the item key
$_SESSION// or:$this->session->userdata();
Adding Session Data
Let’s say a particular user logs into your site. Once authenticated, you could add their username and e-mail address to the session, making that data globally available to you without having to run a database query when you need it.
You can simply assign data to the $_SESSION array, as with any other variable. Or as a property of $this->session.
Alternatively, the method of assigning it as “userdata” is also available. That however passing an array containing your new data to the set_userdata() method:
$this->session->set_userdata($array);
Where $array is an associative array containing your new data. Here’s an example:
If you want to verify that a session value exists, simply check with isset():
// returns FALSE if the 'some_name' item doesn't exist or is NULL,// TRUE otherwise:isset($_SESSION['some_name'])
Or you can call has_userdata():
$this->session->has_userdata('some_name');
Removing Session Data
Just as with any other variable, unsetting a value in $_SESSION can be done through unset():
unset($_SESSION['some_name']);
// or multiple values:unset(
$_SESSION['some_name'],
$_SESSION['another_name']
);
Also, just as set_userdata() can be used to add information to a session, unset_userdata() can be used to remove it, by passing the session key. For example, if you wanted to remove ‘some_name’ from your session data array:
LavaLust supports “flashdata”, or session data that will only be available for the next request, and is then automatically cleared.
This can be very useful, especially for one-time informational, error or status messages (for example: “Record 2 deleted”).
It should be noted that flashdata variables are regular session vars, only marked in a specific way under the ‘__ci_vars’ key (please don’t touch that one, you’ve been warned).
To mark an existing item as “flashdata”:
$this->session->mark_as_flash('item');
If you want to mark multiple items as flashdata, simply pass the keys as an array:
Or alternatively, using the set_flashdata() method:
$this->session->set_flashdata('item', 'value');
You can also pass an array to set_flashdata(), in the same manner as set_userdata().
Reading flashdata variables is the same as reading regular session data through $_SESSION:
$_SESSION['item']
Important
The userdata() method will NOT return flashdata items.
However, if you want to be sure that you’re reading “flashdata” (and not any other kind), you can also use the flashdata() method:
$this->session->flashdata('item');
Or to get an array with all flashdata, simply omit the key parameter:
$this->session->flashdata();
Note
The flashdata() method returns NULL if the item cannot be found.
If you find that you need to preserve a flashdata variable through an additional request, you can do so using the keep_flashdata() method. You can either pass a single item or an array of flashdata items to keep.
LavaLust will usually make everything work out of the box. However, Sessions are a very sensitive component of any application, so some careful configuration must be done. Please take your time to consider all of the options and their effects.
You’ll find the following Session related preferences in your app/config/config.php file:
Preference
Default
Options
Description
sess_driver
files
files
The session storage driver to use.
sess_cookie_name
LLSession
[A-Za-z_-] characters only
The name used for the session cookie.
sess_expiration
7200 (2 hours)
Time in seconds (integer)
The number of seconds you would like the session to last. If you would like a non-expiring session (until browser is closed) set the value to zero: 0
sess_save_path
Empty
None
Specifies the storage location, depends on the driver being used.
sess_match_ip
FALSE
TRUE/FALSE (boolean)
Whether to validate the user’s IP address when reading the session cookie. Note that some ISPs dynamically changes the IP, so if you want a non-expiring session you will likely set this to FALSE.
sess_time_to_update
300
Time in seconds (integer)
This option controls how often the session class will regenerate itself and create a new session ID. Setting it to 0 will disable session ID regeneration.
sess_regenerate_destroy
FALSE
TRUE/FALSE (boolean)
Whether to destroy session data associated with the old session ID when auto-regenerating the session ID. When set to FALSE, the data will be later deleted by the garbage collector.
Input and Ouput
Note
This class is initialized automatically by the system so there is no need to do it manually.
Accessing form data
Using POST, GET, COOKIE, or SERVER Data
LavaLust comes with helper methods that let you fetch POST, GET, COOKIE or SERVER items. The main advantage of using the provided methods rather than fetching an item directly ($_POST['something']) is that the methods will check to see if the item is set and return NULL if not. This lets you conveniently use data without having to test whether an item exists first. In other words, normally you might do something like this:
With LavaLust's built in methods you can simply do this:
$something = $this->io->post('something');
The main methods are:
//The first parameter will contain the name of the POST item you are looking for:$this->io->post('field')
$this->io->post(array('field1', 'field2'));
//This method is identical to post(), only it fetches GET data.$this->io->get('field')
$this->io->get(array('field1', 'field2'));
//This method is identical to post() and get(), only it fetches cookie data:$this->io->cookie('field')
$this->io->cookie(array('some_cookie', 'some_cookie2'));
//This method is identical to the post(), get() and cookie() methods, only it fetches server data ($_SERVER):$this->io->server('field')
$this->io->server(array('SERVER_PROTOCOL', 'REQUEST_URI'));
There are other availble methods like:
//This method works pretty much the same way as post() and get(), only combined. It will search through both POST and GET streams for data, looking in POST first, and then in GET:$this->io->post_get('field')
//This method works the same way as post_get() only it looks for GET data first.$this->io->get_post('field')
//Sets a cookie containing the values you specify. There are two ways to pass information to this method so that a cookie can be set: Array Method, and Discrete Parameters://options value: doamin, path, prefix, secure, and samesite$this->io->set_cookie($name, $value, $expiration, $options = array())
//Returns the IP address for the current user. If the IP address is not valid, the method will return ‘0.0.0.0’:$this->io->ip_address()
//Takes an IP address as input and returns TRUE or FALSE (boolean) depending on whether it is valid or not.$this->io->valid_ip('sample_id')
//Checks to see if the HTTP_X_REQUESTED_WITH server header has been set, and returns boolean TRUE if it is or FALSE if not.$this->io->is_ajax()
//Returns the $_SERVER['REQUEST_METHOD'], with the option to set it in uppercase or lowercase.$this->io->method()
Other Response Methods
If you need customize responses with the ability to add and set headers, set status codes and contents you LavaLust IO class has default methods for them.
//Alternatively, send a JSON response (for API)$this->io->add_header('Access-Control-Allow-Origin', '*');
$this->io->add_header('Content-Type', 'application/json');
//Or use array for add_header$this->io->add_header([
'Access-Control-Allow-Origin' => '*',
'Content-Type' => 'application/json'
]);
$data = ['message' => 'Hello, World!'];
$this->io->set_status_code(200);
$this->io->send_json($data);
Config Class
The Config class provides a means to retrieve configuration preferences. These preferences can come from the default config file (app/config/config.php) or from your own custom config files.
By default, LavaLust has one primary config file, located at app/config/config.php. If you open the file using your text editor you’ll see that config items are stored in an array called $config.
You can add your own config items to this file, or if you prefer to keep your configuration items separate (assuming you even need config items), simply create your own file and save it in config folder.
Note
If you do create your own config files use the same format as the primary one, storing your items in an array called $config. LavaLust will intelligently manage these files so there will be no conflict even though the array has the same name (assuming an array index is not named the same as another).
Manual Loading
To load one of your custom config files you will use the following function within the controller that needs it:
$this->config->load('filename');
Where filename is the name of your config file, without the .php file extension.
If you need to load multiple config files normally they will be merged into one master config array. Name collisions can occur, however, if you have identically named array indexes in different config files. To avoid collisions you can set the second parameter to TRUE and each config file will be stored in an array index corresponding to the name of the config file. Example:
// Stored in an array with this prototype: $this->config['blog_settings'] = $config$this->config->load('blog_settings', TRUE);
Auto-loading
If you find that you need a particular config file globally, you can have it loaded automatically by the system. To do this, open the autoload.php file, located at application/config/autoload.php, and add your config file as indicated in the file.
Fetching Config Items
To retrieve an item from your config file, use the following function:
$this->config->get('item_name');
Where item_name is the $config array index you want to retrieve. For example, to fetch your language choice you’ll do this:
$lang = $this->config->get('language');
The function returns NULL if the item you are trying to fetch does not exist.
If you are using the second parameter of the $this->config->load function in order to assign your config items to a specific index you can retrieve it by specifying the index name in the second parameter of the $this->config->get() function. Example:
// Loads a config file named blog_settings.php and assigns it to an index named "blog_settings"$this->config->load('blog_settings', TRUE);
// Retrieve a config item named site_name contained within the blog_settings array$site_name = $this->config->get('site_name', 'blog_settings');
// An alternate way to specify the same item:$blog_config = $this->config->get('blog_settings');
$site_name = $blog_config['site_name'];
Setting a Config Item
If you would like to dynamically set a config item or change an existing one, you can do so using:
$this->config->set('item_name', 'item_value');
Where item_name is the $config array index you want to change, and item_value is its value.
Encryption Class
The Encryption Library provides two-way data encryption. To do so in a cryptographically secure way, it utilizes PHP extensions called OpenSSL
Initializing the Class
Like most other classes in LavaLust, the Encryption library is initialized in your controller using the $this->call->library() method:
$this->call->library('encryption');
//or $this->call->library('encryption', 'cipher type'); //cipher is optional. If empty, it will use AES-256-CBC cipher.
Once loaded, the Encryption library object will be available using:
$this->encryption;
By default, the Encryption Library will use the AES-256 cipher in CBC mode, using your configured encryption_key.
Encrypting and decrypting data
Encrypting and decrypting data with the already configured library settings is simple. As simple as just passing the string to the encrypt() and/or decrypt() methods:
$plain_text = 'This is a plain-text message!';
$ciphertext = $this->encryption->encrypt($plain_text);
// Outputs: This is a plain-text message!echo$this->encryption->decrypt($ciphertext);
Database Reference
LavaLust has database class that supports both semi-traditional structures and Query Builder patterns..
Database Configuration
LavaLust has a config file that lets you store your database connection values (username, password, database name, etc.). The config file is located at application/config/database.php.
The config settings are stored in a multi-dimensional array with this prototype:
The database type. ie: mysqli, postgre, odbc, etc. Must be specified in lower case.
hostname
The hostname of your database server. Often this is ‘localhost’.
port
The database port number. To use this value you have to add a line to the database config array.
username
The username used to connect to the database.
password
The password used to connect to the database.
database
The name of the database you want to connect to.
dbprefix
An optional table prefix which will added to the table name when running Query Builder queries. This permits multiple LavaLust installations to share one database.
charset
The character set used in communicating with the database.
Connecting to your Database
Automatically Connecting
The “auto connect” feature will load and instantiate the database class with every page load. To enable “auto connecting”, add the word database to the library array, as indicated in the following file:
app/config/autoload.php
Manually Connecting
If only some of your pages require database connectivity you can manually connect to your database by adding this line of code in any function where it is needed, or in your class constructor to make the database available globally in that class.
$this->call->database();
If the above function does not contain any information in the first parameter it will connect to the group specified in your database config file. For most people, this is the preferred method of use.
Manually Connecting to a Database
The first parameter of this function can optionally be used to specify a particular database group from your config file, or you can even submit connection values for a database that is not specified in your config file. Examples:
To choose a specific group from your config file you can do this:
$this->call->database('group_name');
Where group_name is the name of the connection group from your config file.
For information on each of these values please see the configuration page.
Connecting to Multiple Databases
If you need to connect to more than one database simultaneously you can do so as follows:
Note: Change the words “group_one” and “group_two” to the specific group names you are connecting to. If you don't specify the group_name, it will automatically defined $this->db variable to use for database queries.
The following code loads and initializes the database class based on your configuration settings:
$this->call->database();
Once loaded the class is ready to be used as described below.
Note: If all your pages require database access you can connect automatically
raw()
This method has one require parameter which is the SQL statement.
The second parameter is an array which will be substituted to the placeholder (?) or named placeholder (:id) when statement is executed.
$data = $this->db->raw('select * from user where id = ?', array(1))->fetchAll();
foreach($dataas$row) {
echo$row['id'];
echo$row['username'];
echo$row['password'];
}
echo$this->db->row_count();
You can also use named parameters like this.
$data = $this->db->raw('select * from user where id = :id', array('id' => 1))->fetchAll();
foreach($dataas$row) {
echo$row['id'];
echo$row['username'];
echo$row['password'];
}
echo$this->db->row_count();
select()
# Usage 1: string parameter$this->db->table('table')->select('column1, column2')->get_all();
# Output: "SELECT column1, column2 FROM table"$this->db->table('table')->select('column1 AS c1, column2 AS c2')->get_all();
# Output: "SELECT column1 AS c1, column2 AS c2 FROM table"
select functions
You can use this method in 5 ways. These;
select_min
select_max
select_sum
select_avg
select_count
# Usage 1:$this->db->table('table')->select_max('price')->get();
# Output: "SELECT MAX(price) FROM table"# Usage 2:$this->db->table('table')->select_count('id', 'total_row')->get();
# Output: "SELECT COUNT(id) AS total_row FROM table"
table()
# Usage 1: string parameter$this->db->table('table');
# Output: "SELECT * FROM table"$this->db->table('table1, table2');
# Output: "SELECT * FROM table1, table2"$this->db->table('table1 AS t1, table2 AS t2');
# Output: "SELECT * FROM table1 AS t1, table2 AS t2"
get() and get_all()
# get(): return 1 record. It has one optional parameter, yo u can set the fetchmode. example: PDO::FETCH_OBJ by# default PDO::FETCH_ASSOC# get_all(): return multiple records.$this->db->table('table')->get_all();
# Output: "SELECT * FROM table"$this->db->table('users')->select('username')->where('status', 1)->get_all();
# Output: "SELECT username FROM users WHERE status='1'"$this->db->table('pages')->select('title')->where('id', 17)->get();
# Output: "SELECT title FROM pages WHERE id='17' LIMIT 1"
$this->db->table('table')->where("id", 17)->delete();
# Output: "DELETE FROM table WHERE id = '17'"# OR$this->db->table('table')->delete();
# Output: "TRUNCATE TABLE delete"
where()
$where = [
'name' => 'Ron',
'age' => 23,
'status' => 1
];
$this->db->table('users')->where($where)->get();
# Output: "SELECT * FROM users WHERE name='Ron' AND age='23' AND status='1' LIMIT 1"# OR$this->db->table('users')->where('active', 1)->get_all();
# Output: "SELECT * FROM users WHERE active='1'"# OR$this->db->table('users')->where('age', '>=', 18)->get_all();
# Output: "SELECT * FROM users WHERE age>='18'"# OR$this->db->table('users')->where('age = ? OR age = ?', [18, 20])->get_all();
# Output: "SELECT * FROM users WHERE age='18' OR age='20'"
You can use this method in 6 ways. These;
where
or_where
not_where
or_not_where
where_null
where_not_null
$this->db->table('users')->where('active', 1)->not_where('auth', 1)->get_all();
# Output: "SELECT * FROM users WHERE active = '1' AND NOT auth = '1'"# OR$this->db->table('users')->where('age', 20)->or_where('age', '>', 25)->get_all();
# Output: "SELECT * FROM users WHERE age = '20' OR age > '25'"$this->db->table('users')->where_not_null('email')->get_all();
# Output: "SELECT * FROM users WHERE email IS NOT NULL"
join()
$this->db->table('test as t')->join('foo as f', 't.id=f.t_id')->where('t.status', 1)->get_all();
# Output: "SELECT * FROM test as t JOIN foo as f ON t.id=f.t_id WHERE t.status='1'"
You can use this method in 7 ways. These;
join
left_join
right_join
inner_join
full_outer_join
left_outer_join
right_outer_join
$this->db->table('test as t')->left_join('foo as f', 't.id=f.t_id')->get_all();
# Output: "SELECT * FROM test as t LEFT JOIN foo as f ON t.id=f.t_id"$this->db->table('test as t')->full_outer_join('foo as f', 't.id=f.t_id')->get_all();
# Output: "SELECT * FROM test as t FULL OUTER JOIN foo as f ON t.id=f.t_id"
grouped()
$this->db->table('users')
->grouped(function($q) {
$q->where('country', 'USA')->or_where('country', 'Philippines');
})
->where('status', 1)
->get_all();
# Ouput: "SELECT * FROM users WHERE (country='USA' OR country='Philippines') AND status ='1'"
in()
$this->db->table('users')->where('active', 1)->in('id', [1, 2, 3])->getAll();
# Output: "SELECT * FROM users WHERE active = '1' AND id IN ('1', '2', '3')"
You can use this method in 4 ways. These;
in
or_in
not_in
or_not_in
$this->db->table('users')->where('active', 1)->not_in('id', [1, 2, 3])->get_all();
# Output: "SELECT * FROM users WHERE active = '1' AND id NOT IN ('1', '2', '3')"# OR$this->db->table('users')->where('users', 1)->or_in('id', [1, 2, 3])->get_all();
# Output: "SELECT * FROM table WHERE active = '1' OR id IN ('1', '2', '3')"
between()
$this->db->table('users')->where('active', 1)->between('age', 18, 25)->get_all();
# Output: "SELECT * FROM users WHERE active = '1' AND age BETWEEN '18' AND '25'"
You can use this method in 4 ways. These;
between
or_between
not_between
or_not_between
$this->db->table('users')->where('active', 1)->not_between('age', 18, 25)->get_all();
# Output: "SELECT * FROM users WHERE active = '1' AND age NOT BETWEEN '18' AND '25'"# OR$this->db->table('users')->where('active', 1)->or_between('age', 18, 25)->get_all();
# Output: "SELECT * FROM users WHERE active = '1' OR age BETWEEN '18' AND '25'"
like()
$this->db->table('books')->like('title', "%php%")->get_all();
# Output: "SELECT * FROM books WHERE title LIKE '%php%'"
You can use this method in 4 ways. These;
like
or_like
not_like
or_not_like
$this->db->table('books')->where('active', 1)->not_like('tags', '%dot-net%')->get_all();
# Output: "SELECT * FROM books WHERE active = '1' AND tags NOT LIKE '%dot-net%'"# OR$this->db->table('books')->like('bio', '%php%')->or_like('bio', '%java%')->get_all();
# Output: "SELECT * FROM books WHERE bio LIKE '%php%' OR bio LIKE '%java%'"
group_by()
# Usage 1: One parameter$this->db->table('books')->where('status', 1)->group_by('cat_id')->get_all();
# Output: "SELECT * FROM books WHERE status = '1' GROUP BY cat_id"# Usage 1: Array parameter$this->db->table('books')->where('status', 1)->group_by(['cat_id', 'user_id'])->get_all();
# Output: "SELECT * FROM books WHERE status = '1' GROUP BY cat_id, user_id"
having()
$this->db->table('books')->where('status', 1)->group_by('city')->having('COUNT(person)', 100)->get_all();
# Output: "SELECT * FROM books WHERE status='1' GROUP BY city HAVING COUNT(person) > '100'"# OR$this->db->table('employee')->where('active', 1)->group_by('department_id')->having('AVG(salary)', '<=', 500)->get_all();
# Output: "SELECT * FROM employee WHERE active='1' GROUP BY department_id HAVING AVG(salary) <= '500'"# OR$this->db->table('employee')->where('active', 1)->group_by('department_id')->having('AVG(salary) > ? AND MAX(salary) < ?', [250, 1000])->get_all();
# Output: "SELECT * FROM employee WHERE active='1' GROUP BY department_id HAVING AVG(salary) > '250' AND MAX(salary) < '1000'"
order_by()
# Usage 1: One parameter$this->db->table('test')->where('status', 1)->order_by('id', 'ASC')->get_all();
# Output: "SELECT * FROM test WHERE status='1' ORDER BY id ASC"
limit()
# Usage 1: One parameter$this->db->table('table')->limit(10)->get_all();
# Output: "SELECT * FROM table LIMIT 10"#or# Usage 2: One parameter$this->db->table('table')->limit(10, 20)->get_all();
# Output: "SELECT * FROM table LIMIT 10"
offset()
# Usage 1: One parameter$this->db->table('table')->offset(10)->get_all();
# Output: "SELECT * FROM table OFFSET 10"
pagination()
# Usage 1: One parameter$this->db->table('table')->pagination(10, 1)->get_all();
# Output: "SELECT * FROM table LIMIT 10 OFFSET 10"