Welcome
CodeDmx is a Our PHP framework project that want to enable you to develop projects much faster than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed task.
CodeDmx PHP Framwork can help you if:
- You want a framework with a small footprint.
- You want a framework that requires nearly zero configuration.
- You want a framework that does not require you to use the command line.
- You want a framework that does not require you to adhere to restrictive coding rules.
- You are not interested in large-scale monolithic libraries like PEAR.
- You do not want to be forced to learn a templating language (although a template parser is optionally available if you desire one).
- You need clear, thorough documentation.
Server Requirements
- Web server: Ngnix or Apache (with mod_rewrite)
- PHP version 7.0 or newer is required.
It should works on 5.6, but we work with the last version of PHP.
- MySQLi PHP Extension
- OpenSSL PHP Extension
- Mbstring PHP Extension
License
The MIT License (MIT)
Copyright (c) 2014 - 2017, CodeDMx
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Installation
CodeDmx is installed really quickly:
- Unzip the package.
- Upload the CodeDmx folders and files to your server.
One additional measure to take in production environments is to disable PHP error reporting and any other development-only functionality. This can be disable in index.php
That's it!
Error reporting
PHP errors are not good enough for development, it's as simple as that. This aims to solve this.
When an error strikes, the page is replaced with a full stack trace, syntax highlighting, and all displayed to be readable.
Works with Ajax too!
If the server errors during an ajax request, then the request is paused, and the error is displayed in the browser. You can then click to automatically retry the last request.
This requires no changes to your JavaScript, and works with existing JS libraries such as jQuery.
By default Error Handler hasn't options in line 92 of index.php file
<?php
$handler = new ErrorHandler(null);
$handler->turn_on();
All options
Usage Examples
<?php
$options = array(
'snippet_num_lines' => 10,
'background_text' => 'Error!',
'error_reporting_off' => 0,
'error_reporting_on' => E_ALL | E_STRICT
);
$handler = new ErrorHandler($options);
$handler->turn_on();
| Option | Default | Description |
|---|---|---|
| catch_ajax_errors | true | When on, this will inject JS Ajax wrapping code, to allow this to catch any future JSON errors. |
| catch_supressed_errors | false | The @ supresses errors. If set to true, then they are still reported anyway, but respected when false. |
| catch_class_not_found | true | When true, loading a class that does not exist will be caught. If there are any existing class loaders, they will be run first, giving you a chance to load the class. |
| error_reporting_on | -1 (everything) | The error reporting value for when errors are turned on by Error Handler. |
| error_reporting_off | the value of 'error_reporting' | The error reporting value for when Error Handler reporting is turned off. By default it just goes back to the standard level. |
| application_root | $_SERVER['DOCUMENT_ROOT'] | When it's working out the stack trace, this is the root folder of the application, to use as it's base. A relative path can be given, but lets be honest, an explicit path is the way to guarantee that you will get the path you want. My relative might not be the same as your relative. |
| display_line_numbers | true | When on, line numbers are shown in the editor, and when off, they are not. |
| server_name | $_SERVER['SERVER_NAME'] | The name for this server; it's domain address or ip being used to access it. This is displayed in the output to tell you which project the error is being reported in. |
| ignore_folders | null (no folders) | This is allows you to highlight non-framework code in a stack trace. An array of folders to ignore, when working out the stack trace. This is folder prefixes in relation to the application_root, whatever that might be. They are only ignored if there is a file found outside of them. If you still don't get what this does, don't worry, it's here cos I use it. |
| application_folders | null (no folders) | Just like ignore, but anything found in these folders takes precedence over anything else. |
| background_text | an empty string | The text that appeares in the background. By default this is blank. Why? You can replace this with the name of your framework, for extra customization spice. |
| wordpress | false | This is no longer needed on the latest versions of WordPress. When on, this will use a lower error reporting level, which works with Wordpress. This is because the Wordpress code base is full of minor bugs, and doesn't like strict error reporting. |
| enable_saving | true | When true, Error Handler allows external requests to save files. This is so the editor can save changes back. |
Configuration
Inside of the folder /application/Config/ you can find multiple files to use better this PHP Framework.
URL Settings
url.settings.php
This file is so important to be the first one to load, because will have all document root files that the Framework needs.
This variables can be edit.
Base site url
<?php
// Can set manually like the URL on is host your project, but if you want you can change with a real URL
// $GLOBALS['COD']->dir = 'http://codedmx.com/';
$GLOBALS['COD']->dir = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ).'://'.$_SERVER['HTTP_HOST'].DS;
Base site document root
<?php
// Is about Document Root $_SERVER['DOCUMENT_ROOT'] of your project, but if you want you can change it.
// $GLOBALS['COD']->doc = '/var/www/vhosts/codedmx/';
$GLOBALS['COD']->doc = str_replace("application/Config", "", realpath(dirname(__FILE__)));
Base site document root for config folder
<?php
// Is about Document Root $_SERVER['DOCUMENT_ROOT'] of your project by Config folder.
// $GLOBALS['COD']->doc_config = '/var/www/vhosts/codedmx/application/Config/';
$GLOBALS['COD']->doc_config = $GLOBALS['COD']->doc . 'application' . DS . 'Config' . DS;
Base site document root for view folder
<?php
// Is about Document Root $_SERVER['DOCUMENT_ROOT'] of your project by View folder.
// $GLOBALS['COD']->doc_view = '/var/www/vhosts/codedmx/application/View/';
$GLOBALS['COD']->doc_view = $GLOBALS['COD']->doc . 'application' . DS . 'View' . DS;
Base site document root for Class folder
<?php
// Is about Document Root $_SERVER['DOCUMENT_ROOT'] of your project by Class folder.
// $GLOBALS['COD']->doc_class = '/var/www/vhosts/codedmx/system/Classes/';
$GLOBALS['COD']->doc_class = $GLOBALS['COD']->doc . 'system' . DS . 'Classes' . DS;
Base site document root for Custom Class folder
<?php
// Is about Document Root $_SERVER['DOCUMENT_ROOT'] of your project by Custom_class folder.
// $GLOBALS['COD']->doc_custom = '/var/www/vhosts/codedmx/system/Custom_class/';
$GLOBALS['COD']->doc_custom = $GLOBALS['COD']->doc . 'system' . DS . 'Custom_class' . DS;
Base site document root for Helper folder
<?php
// Is about Document Root $_SERVER['DOCUMENT_ROOT'] of your project by Helper folder.
// $GLOBALS['COD']->doc_helper = '/var/www/vhosts/codedmx/system/Helper/';
$GLOBALS['COD']->doc_helper = $GLOBALS['COD']->doc . 'system' . DS . 'Helper' . DS;
Default php file when you type your url 'https://codedmx.com'
<?php
$GLOBALS['COD']->default = 'home';
Default php file when you type your url 'https://codedmx.com' and the file can't be found
<?php
// This file will find in /application/View/static/{$GLOBALS['COD']->not_found}.php
$GLOBALS['COD']->not_found = 'File';
Analytics account
You have a variable to set your analytics id account to use it in the future.
<?php
$GLOBALS['COD']->analytics = 'UA-XXXXXXX-X';
Database settings
db.settings.php
This variables are to access your database. You can add more arrays with multiple databases configs.
| Key | Description |
|---|---|
| host | The hostname of your database server. |
| username | The username used to connect to the database. |
| password | The password used to connect to the database. |
| db | The name of the database you want to connect. |
| port | The port used to connect to the database. |
| charset | The character set used in communicating with the database. |
<?php
$GLOBALS['COD']->db = array(
'default' => array(
'host' => 'localhost', // Required
'username' => '', // Required
'password' => '', // Required
'db'=> '', // Required
'port' => 3306,
'charset' => 'utf8'
),
'myotherdb' => array(
'host' => '', // Required
'username' => '', // Required
'password' => '', // Required
'db'=> '', // Required
'port' => 3306,
'charset' => 'utf8'
)
);
Encrypt settings
encrypt.settings.php
Some people believe MD5 would be a safe way to encode passwords. Is a lie! MD5 is a good method to obscure non-sensitive data, because it's quite fast.
Hash the passwords
<?php
// Can be: 2a, 2x or 2y
$GLOBALS['COD']->identifier = '2y';
Encrypt settings
<?php
$GLOBALS['COD']->emethod = ''; // AES-256-CBC | aes-128-cbc, AES-128-CFB
$GLOBALS['COD']->ekey = ''; //qw1209132j
$GLOBALS['COD']->eiv = ''; // *123+1*23*
Autoload Settings
autoload.settings.php
You can set autoload classes and helpers that you need in all the project, and you don't need to load it again in the future.
| Key | Description |
|---|---|
| db | Data base class |
| validate | Validator class |
| crypt | Encryptation class |
| Mailing class | |
| timeago | Timeago class |
| image | Image class |
| ftp | FTP class |
| upload | Uploader class |
| cache | Cache class |
| paginator | Paginator class |
| router | Router class |
| session | Session class |
| zip | Zip class |
You need to send array
<?php
$GLOBALS['COD']->autoload = array();
// Can set db and session like autoload:
$GLOBALS['COD']->autoload = array('db', 'session');
// And you don't need to use this function to load the library
// $this->load->library('db');
// $this->load->library('session');
| Key | Description |
|---|---|
| array | Array helper |
| cookie | Cookie helper |
| directory | Directory helper |
| download | Download helper |
| html | HTML helper |
| security | Security helper |
| string | String helper |
| text | Text helper |
| url | URL helper |
| agent | User helper |
You need to send array
<?php
$GLOBALS['COD']->helpers = array();
// Can set db and session like autoload:
$GLOBALS['COD']->helpers = array('array', 'url');
// And you don't need to use this function to load the helper
// $this->load->helper('array');
// $this->load->helper('url');
FTP Settings
ftp.settings.php
This variables are to access your ftp connection.
| Key | Description |
|---|---|
| hostname | FTP Server hostname (http://codedmx.com OR <IP_ADDRESS>) |
| username | FTP Username |
| password | FTP Password |
| port | FTP Server port |
| passive | Passive mode flag |
<?php
$GLOBALS['COD']->ftp = array(
'hostname' => '',
'username' => '',
'password' => '',
'port' => 21,
'passive' => TRUE
);
Google analytics and Compress Page
Google analytics
You can use a function to create your Google Analytics Code.
Imagine this file

<link href='//my_css.css'>

<?php echo $this->create_ga ?>

And this will output something like this:

<link href='//my_css.css'>

Compress page
You can compress all the code of your page.
Image this file
<?php
$this->compress_page();
?>

<link href='//my_css.css'>

And this will output something like this:
<link href='//my_css.css'>
Loader
CodeDmx Framwork has a master class that can help you to make easy the code that you need
Load library
Load library it called in __construct function to know if you set some class into autoload config.
For example:
You have a database, and you want to use it only in a php file.
You need to use this
<?php
$this->load->library('db');
// Then
$this->db->get('users');
If you set this library in autoload config file, you only need to use the method.
<?php
$this->db->get('users');
Load view
Load a file from your server it's so easy, if the file path doesn't exists, will return not found file alert:
You need to use this
<?php
$this->load->view('my_file');
You can set the path of the file:
<?php
//$file, $path
$this->load->view('my_file', $GLOBALS['COD']->doc . 'system' . DS);
You can send arguments into an array
<?php
// $file, $path, $args
$array = array(
'test' => 1,
'other' => 2
);
$this->load->view('my_file', null, $array);
You can set what is the extension of the file, by default is php
<?php
// $file, $path, $args, $extension
$this->load->view('my_file', null, array(), 'html');
Load helper
Like load a library, you can autoload a helper file
You need to use this
<?php
$this->load->helper('url');
echo $this->url->get_current_URL();
Load custom class
We know that you'll have some custom classes, well, you have a folder to save your classes, and you can call them like this
You need to use this
<?php
/**
* @param string $filename // File name in custom class
* @param string $classname // Class name
* @param string $new_name // What will be it new name ($this->my_class->method())
*/
$this->load->custom('myclass', 'MyClass', 'myclass');
echo $this->myclass->method();
Method extend
When you create a custom class you need to extends all COD_Loader class
Like this, imagine you create user.class.php
<?php
class Users extends COD_Loader {
function __construct() {
$this->extend();
$this->load->library('db');
}
function get_users() {
return $this->db->get('users');
}
}
And you have an index file
<?php
$this->load->custom('user.class', 'Users', 'users');
print_r($this->users->get_users());
Construct
The __construct method firstly know if you set autoload libraries, then check if you set autoload helpers, then Load routers
Router
/application/Config/routers.settings.php
CodeDmx has a router to help you to mane your routes without use htaccess. Let's explain this:
Router Features
- HTTP methods
- Dynamic routing with (named) route parameters
- Flexible regular expression routing, inspired by Sinatra
- Reversed routing
- Custom regexes
Set Base Path
Optionally, if your project lives in a sub-folder of your web root you use the set_base_path() method to set a base path.
$this->router->set_base_path('/sub-folder/');
Router default routes
Router has default routes, firstly the router is Loaded
<?php
$this->router = new COD_Router();
If you type http://yoursite.com this will enter in this condition
<?php
// Make sure that default file exists in the View folder
// By default, the $GLOBALS['COD']->default is 'home'
$this->router->map('GET|POST', '/', function() {
require $GLOBALS['COD']->doc_view . $GLOBALS['COD']->default . '.php';
});
If you type http://yoursite.com/some_file/ this will enter in this condicion
<?php
// Make sure that not_found file exists in the View/Static folder
// By default, the $GLOBALS['COD']->not_found is 'File'
// All string before your site will enter in this condition
$this->router->map('GET|POST', '/[:page]/', function($page) {
if ( ! file_exists($GLOBALS['COD']->doc_view . $page . '.php'))
{
require $GLOBALS['COD']->doc_view . 'static' . DS . $GLOBALS['COD']->not_found . '.php';
exit(1);
}
else
{
require $GLOBALS['COD']->doc_view . $page . '.php';
exit(1);
}
});
Mapping routes
By now, you should have rewritten al requests to be handled by the routers settings which it created the Router instance.
To map your routes, use the map() method. The following example maps all GET / requests.
<?php
$this->router->map( 'GET', '/', 'render_home', 'home' );
The map() method accepts the following parameters.
$method (string) This is a pipe-delimited string of the accepted HTTP requests methods.
Example: GET|POST|PATCH|PUT|DELETE
$route (string) This is the route pattern to match against. This can be a plain string, one of the predefined regex filters or a custom regex. Custom regexes must start with @.
Examples:
| Route | Example Match | Variables |
|---|---|---|
| /contact/ | /contact/ | |
| /users/[i:id]/ | /users/12/ | $id: 12 |
| /[a:c]/[a:a]?/[i:id]? | /controller/action/21 | $c: "controller", $a: "action", $id: 21 |
$target (mixed) As Router leaves handling routes up to you, this can be anything.
Example using a function callback: function() { ... }
Example using a controller#action string: UserController#showDetails
$name (string, optional) If you want to use reversed routing, specify a name parameter so you can later generate URL's using this route.
Example: user_details
Example Mapping
<?php
// map homepage using callable
$this->router->map( 'GET', '/contact/[:string]', function($string) {
$_GET['key_string'] = $string;
require $GLOBALS['COD']->doc_view . 'contact.php';
});
// map users details page using controller#action string
$this->router->map( 'GET', '/users/[i:id]/', 'UserController#showDetails' );
// map contact form handler using function name string
$this->router->map( 'POST', '/contact/', 'handleContactForm' );
For quickly adding multiple routes, you can use the addRoutes method. This method accepts an array or any kind of traversable.
<?php
$this->router->add_routes(array(
array('PATCH','/users/[i:id]', 'users#update', 'update_user'),
array('DELETE','/users/[i:id]', 'users#delete', 'delete_user')
));
Match types
You can use the following limits on your named parameters. Router will create the correct regexes for you.
| Expression | Description |
|---|---|
| * | Match all request URIs |
| [i] | Match an integer |
| [i:id] | Match an integer as 'id' |
| [a:action] | Match alphanumeric characters as 'action' |
| [h:key] | Match hexadecimal characters as 'key' |
| [:action] | Match anything up to the next / or end of the URI as 'action' |
| [create | edit:action] |
| [*] | Catch all (lazy, stops at the next trailing slash) |
| [*:trailing] | Catch all as 'trailing' (lazy) |
| [**:trailing] | Catch all (possessive - will match the rest of the URI) |
| .[:format]? | Match an optional parameter 'format' - a / or . before the block is also optional |
The character before the colon (the 'match type') is a shortcut for one of the following regular expressions
| Expression | Regex |
|---|---|
| i | [0-9]++ |
| a | [0-9A-Za-z]++ |
| h | [0-9A-Fa-f]++ |
| * | .+? |
| ** | .++ |
| [^/.]++ |
You can register your own match types using the add_match_types() method.
<?php
$this->router->add_match_types(array('cId' => '[a-zA-Z]{2}[0-9](?:_[0-9]++)?'));
Matching Requests
To match the current request, just call the match()
method without any parameters.
$match = $this->router->match();
If a match was found, the match() method will return an associative array with the following 3 keys.
target (mixed) The target of the route, given during mapping the route.
params (array) Named parameters found in the request url.
name (string) The name of the route.
Example
<?php
$this->router = new COD_Router();
$this->router->map( 'GET', '/', function() { .. }, 'home' );
// assuming current request url = '/'
$match = $this->router->match();
/*
array(3) {
["target"] => object(Closure)#2 (0) { }
["params"] => array(0) { }
["name"] => 'home'
}
*/
Router does not process the request for you, you are free to use the method you prefer. Here is a simplified example how to process requests using closures though.
Agent Helper
Agent helper can help you about browser or agent user is use it.
First of all you need to load the helper file
<?php
$this->load->helper('agent');
Know browser
<?php
echo $this->agent->know_browser();
// In my case, will output: Google Chrome, Version: 67.0.3396.79, Mac OS2
Is mobile
<?php
// This will return void
var_dump($this->agent->is_mobile());
Curl
<?php
// You can use this method to make curl calls
/**
* @param string $url
* @param string $method
* @param mixed $data
* @param mixed $headers
* @param boolean $return
*/
var_dump($this->agent->curl('http://yoursite.com', 'GET'));
Array Helper
The Array Helper file contains functions that assist in working with arrays.
First of all you need to load the helper file
<?php
$this->load->helper('array');
Random element
Takes an array as input and returns a random element
<?php
/**
* @param array
*
* @return mixed depends on what the array contains
*/
$array = array('blue', 'red', 'green');
$this->array->random_element($array);
Array to string
Convert Array to string expected output:
<?php
/**
* @param array $array
*
* @return string
*/
$array = array(1 => 'blue', 2 => 'red', 3 => 'green');
$this->array->random_element($array);
Chunk an array
Chunks an array into smaller arrays of a specified size.
<?php
/**
* @param array $array
* @param int $size
*
* @return array
*/
$this->array->chunk([1, 2, 3, 4, 5], 2);
// output: [[1, 2], [3, 4], [5]]
Deep Flatten
Deep flattens an array.
<?php
$this->array->deep_flatten([1, [2], [[3], 4], 5]);
// output: [1, 2, 3, 4, 5]
Drop
Returns a new array with n elements removed from the left.
<?php
/**
* @param array $array
* @param int $n default: 1
*
* @return array
*/
$this->array->drop([1, 2, 3]);
// output: [2,3]
$this->array->drop([1, 2, 3], 2);
// output: [3]
Flatten
Flattens an array up to the one level depth.
<?php
$this->array->flatten([[1, [2], 3, 4]);
// output: [1, 2, 3, 4]
Has duplicates
Checks a flat list for duplicate values. Returns true if duplicate values exists and false if values are all unique.
<?php
var_dump($this->array->has_duplicates([1, 2, 3, 4, 5, 5]));
// output: true
Cookie Helper
The Cookie Helper file contains functions that assist in working with cookies.
First of all you need to load the helper file
<?php
$this->load->helper('cookie');
Set cookie
Accepts seven parameters, or you can submit an associative array in the first parameter containing all the values.
<?php
/**
* @param mixed
* @param string the value of the cookie
* @param int the number of seconds until expiration
* @param string the cookie domain. Usually: .yourdomain.com
* @param string the cookie path
* @param string the cookie prefix
* @param bool true makes the cookie secure
* @param bool true makes the cookie accessible via http(s) only (no javascript)
*
* @return void
*/
$this->cookie->set('user', 2);
Get cookie
Fetch an item from the COOKIE array
<?php
/**
* @param string
* @param bool
*
* @return mixed
*/
$this->cookie->get('user');
// If not exists will return false
// Else will return '2'
Delete cookie
<?php
/**
* @param mixed
* @param string the cookie domain. Usually: .yourdomain.com
* @param string the cookie path
* @param string the cookie prefix
*
* @return void
*/
$this->cookie->delete('user');
// Will return void
Directory Helper
The Directory Helper file contains functions that assist in working with directories.
First of all you need to load the helper file
<?php
$this->load->helper('directory');
Map directory
Reads the specified directory and builds an array representation of it. Sub-folders contained with the directory will be mapped as well.
<?php
/**
* @param string $source_dir Path to source
* @param int $directory_depth Depth of directories to traverse
* (0 = fully recursive, 1 = current dir, etc)
* @param bool $hidden Whether to show hidden files
* @return mixed array|false
*/
var_dump($this->directory->map($GLOBALS['COD']->doc. 'uploads/'));
Create directory
<?php
/**
* @param string $direction Path to source
* @param int $mode Mode of the folder
* @param void $recursive Recursive mode
*
* @return void
*/
var_dump($this->directory->create($GLOBALS['COD']->doc. 'uploads/', 0777, false));
Delete directoru
<?php
/**
* @param string $direction Path to source
*
* @return void
*/
var_dump($this->directory->delete($GLOBALS['COD']->doc. 'uploads/');
Download helper
The Download Helper lets you download data to your desktop.
First of all you need to load the helper file
<?php
$this->load->helper('download');
Download file
Generates headers that force a download to happen
<?php
/**
* @param mixed filename (or an array of local file path => destination filename)
* @param mixed the data to be downloaded
* @param bool whether to try and send the actual file MIME type
*
* @return void
*/
$this->download->file($GLOBALS['COD']->doc . 'json' . DS . 'test.json');
HTML Helper
The HTML Helper file contains functions that assist in working with HTML.
First of all you need to load the helper file
<?php
$this->load->helper('html');
Embed string
Parse text to find url's for embed enabled services like: youtube.com, blip.tv, vimeo.com, dailymotion.com, flickr.com, smugmug.com, hulu.com, revision3.com, wordpress.tv, funnyordie.com, soundcloud.com, slideshare.net and instagram.com and embed elements automatically.
<?php
/**
* @param string $string
* @param string $width default: 560
* @param string $height default: 315
*
* @return string
*/
echo $this->html->embed('https://www.youtube.com/watch?v=OK7tWZdO0Ys');
// output:
Create link tag
Lets you create HTML  tags. This is useful for stylesheet links, as well as other links.
Validate email address
<?php
var_dump($this->html->validate_email('test@mysite.com'));
// output void
Generate QR code
<?php
/**
* @param string $string
* @param integer $width default: 150
* @param integer $height default: 150
* @param array $attributes
*/
echo $this->html->get_qr_code('my string to qr code');
// output:
Heading
Generates an HTML heading tag
<?php
/**
* @param string content
* @param int heading level
* @param string
*
* @return string
*/
echo $this->html->heading('My heading', '1', 'class="my_head"');
// output:
My heading

Image
Generates an  element
<?php
/**
* @param mixed $src
* @param mixed $attributes
*
* @return string
*/
echo $this->html->img('https://scontent.fgdl4-1.fna.fbcdn.net/v/t1.0-9/35151329_2086731074928935_8159052263000637440_o.jpg?_nc_cat=0&oh=46fd588d04581c56e2892ab6e7dbadba&oe=5BAE3343', 'class="my_image"');
// output:
UL
Generates an
 element
<?php
$list = array(
'red',
'blue',
'green',
'yellow'
);
$attributes = array(
'class' => 'boldlist',
'id' => 'mylist'
);
echo $this->html->ul($list, $attributes);
// output:

//
red

//
blue

//
green

//
yellow

//

OL
Generates an
 element
<?php
$list = array(
'red',
'blue',
'green',
'yellow'
);
$attributes = array(
'class' => 'boldlist',
'id' => 'mylist'
);
echo $this->html->ol($list, $attributes);
// output:

//
red

//
blue

//
green

//
yellow

//

Security helper
The Security Helper file contains security related functions.
First of all you need to load the helper file
<?php
$this->load->helper('security');
Create an id
Permits you to create one way hashes suitable for encrypting passwords. You can set md5 TRUE.
<?php
echo $this->security->create_id();
// OR
// To set MD5 string
echo $this->security->create_id(TRUE);
Crypt and decrypt string
To use this method, you need to set in encrypt.settings.php about encrypt method, secret key and secret iv. Crypt and decrypt something with sha256 and secret strings.
You can encrypt by default like this:
<?php
echo $this->security->cryptit('123456');
// output: TDRncE5lN3I2UE1TZjhzcThuR0RUZz09
And decrypt that string:
<?php
echo $this->security->decryptit('TDRncE5lN3I2UE1TZjhzcThuR0RUZz09', FALSE);
// output: 123456
Get ip
Returns the IP address of the client.
<?php
echo $this->security->get_ip();
// output: 158.65.359.86
Get Location
Get client location
<?php
echo $this->security->get_location();
// output: Monterrey, MX
String helper
The String Helper file contains functions that assist in working with strings.
First of all you need to load the helper file
<?php
$this->load->helper('string');
Random string
<?php
/**
* @param string type of random string. basic, alpha, alnum, numeric, nozero, unique, md5, encrypt and sha1
* @param int number of characters
*
* @return string
*/
echo $this->string->random_string('alnum', 8);
// output: xg9tCHZb
Reduce multiples
<?php
/**
* @param string
* @param string the character you wish to reduce
* @param bool TRUE/FALSE - whether to trim the character from the beginning/end
*
* @return string
*/
$string = 'Fred, Bill,, Joe, Jimmy';
echo $this->string->reduce_multiples($string, ',');
// output: Fred, Bill, Joe, Jimmy
Create string
<?php
echo $this->string->create_string(8);
// output: xg9tCHZb
Reduce double slashes
Converts double slashes in a string to a single slash, except those found in http://
<?php
$str = 'http://www.some-site.com//index.php';
echo $this->string->reduce_double_slashes(8);
// output: http://www.some-site.com/index.php
Number to word
Convert number to word representation
<?php
echo $this->string->number_to_word(8);
// output: eight
Starts with
Check if a string is starts with a given substring.
<?php
var_dump($this->string->starts_with('Hi, this is me', 'Hi'));
// output: true
Ends with
Check if a string is ends with a given substring.
<?php
var_dump($this->string->ends_with('Hi, this is me', 'me'));
// output: true
First string between
Returns the first string there is between the strings from the parameter start and end.
<?php
/**
* @param string $string
* @param string $start
* @param string $end
*
* @return string
*/
echo $this->string->first_string_between('This is a [custom] string', '[', ']');
// output: custom
Text helper
The Text Helper file contains functions that assist in working with text.
First of all you need to load the helper file
<?php
$this->load->helper('text');
Cut string
Truncate String with or without ellipsis
<?php
/**
* @param string $string
* @param int $max_length
* @param boolean $add_ellipsis
* @param boolean $word_safe
*
* @return string
*/
$string = "Here is a nice text string consisting of eleven words.";
echo $this->text->cut_string($string, 20);
//output: Here is a nice text string
Word censor
Supply a string and an array of disallowed words and any matched words will be converted to #### or to the replacement word you've submitted.
<?php
/**
* @param string the text string
* @param string the array of censored words
* @param string the optional replacement value
*
* @return string
*/
$string = 'Hi Sophie, how do shucks are you?';
$disallowed = array('darn', 'shucks', 'golly', 'phooey');
echo $this->text->word_censor($string, $disallowed, 'Beep!');
// Output: Hi Sophie, how do Beep! are you?
URL Helper
The URL Helper file contains functions that assist in working with URLs.
First of all you need to load the helper file
<?php
$this->load->helper('url');
Current URL
Returns the full URL (including segments) of the page being currently viewed.
<?php
echo $this->url->get_current_URL();
// Output: https://yoursite.com/contact/
Is https
Check if your site run on https
<?php
var_dump($this->url->is_https());
Is AJAX
Determine if current page request type is ajax
<?php
var_dump($this->url->is_ajax());
Encryptation Class
CodeDmx has an encryptation class. Some people believe MD5 would be a safe way to encode passwords. Is a lie! MD5 is a good method to obscure non-sensitive data, because it's quite fast.
First of all you need to load the library file
<?php
$this->load->library('crypt');
A simple example
To hash the password, you only need to call one method
<?php
$password = 'my_password';
echo $this->crypt->hash_password($password);
// Something like: $2y$12$lyAb7hOusPTvEGJBVmia4OGV8nU0pFhBOvG4NZRT3P/1lA3SAMoFK
To check if password against the $hashed, and this returns TRUE / FALSE
<?php
if ($this->crypt->check_password($password, $hashed))
{
// continue
}
Work factor
To increase your hash security this method accepts the optional parameter $work_factor. This defines the number of rounds. With each round the creation time doubles, so the system is exponentially.
<?php
$work_factor = 16;
$password = 'my_password';
echo $this->crypt->hash_password($password, $work_factor);
Change the schema
To alter the default scheme, change the GLOBAL variable on your config file (/application/Config/encrypt.settings.php)$GLOBALS['COD']->identifier to the next strings
2a - Hash wich is potentially generated with the buggy algorithm
2x - "compatibility" option the buggy Bcrypt implementation
2y - Hash generated with the new, corrected algorithm implementation (crypt_blowfish 1.1 and newer)
Structure
$2a$12$Some22CharacterSaltXXO6NC3ydPIrirIzk1NdnTz0L/aCaHnlBa
$2a$ tells PHP to use which Blowfish scheme (Bcrypt is based on Blowfish)
12$ is the number f iterations the hashing mechanism uses
Some22CharacterSaltXX0 is a random salt (by OpenSSL)
Diagram:
<?php
$2a$12$Some22CharacterSaltXXO6NC3ydPIrirIzk1NdnTz0L/aCaHnlBa
\___________________________/\_____________________________/
\ \
\ \ Actual Hash (31 chars)
\
\ $2a$ 12$ Some22CharacterSaltXXO
\__/ \ \____________________/
\ \ \
\ \ \ Salt (22 chars)
\ \
\ \ Number of Rounds (work factor)
\
\ Hash Header
Cache Class
A light, simple but powerful PHP5 Cache Class which uses the filesystem for caching.
Basically the caching class stores its data in files in the JSON format. These files will be created if you store data under a Cache name.
If you set a new Cache name with set_cache(), a new cache file will be generated. The Cache will store all further data in the new file. The Setter method allows you to switch between the different Cache files.
First of all you need to load the library file
<?php
$this->load->library('cache');
Set cache
set_cache($name)
If you want to switch to another Cache or create a new one, then use this method to set a new Cache name.
<?php
$this->cache->set_cache('newcache');
Store
store($key, $data, <$expiration>)
- The key value defines a tag with which the cached data will be associated.
- The data value can be any type of object (will be serialized).
- The expiration value allows you to define an expiration time.
To change data you can overwrite it by using the same key identifier. Beside the data, the Cache will also store a timestamp.
Store a string
<?php
$this->cache->store('hello', 'Hello World!');
Store an array
<?php
$this->cache->store('movies', array(
'description' => 'Movies on TV',
'action' => array(
'Tropic Thunder',
'Bad Boys',
'Crank'
)
));
Get cache elements
retrieve($key, <$timestamp>)
Get particular cached data by its key. To retrieve the timestamp of a key, set the second parameter to true.
retrieve_all(<$meta>)
This allows you retrieve all the cached data at once. You get the meta data by setting the $meta argument to true.
<?php
$result = $this->cache->retrieve('moviews');
print_r($result);
$description = $result['description'];
Switch back
Switch back to the first cache
<?php
$this->cache->set_cache('mycache');
$this->cache->store('hello', 'Hello everybody out there!');
Erase entry
For erasing cached data are these three methods available:
- erase($key) Erases a single entry by its key.
- erase_all() Erases all entries from the Cache file.
- erase_expired() Erases all expired entries.
<?php
$this->cache->erase('hello');
// OR
$this->cache->erase_all();
// OR
$this->cache->erase_expired();
Check cached data
is_cached($key)
Check whether any data is associated with the given key. Returns true or false.
Set Cache path
set_cache_path($path)
The path to the Cache folder must end with a backslash: my_path_to_the_cache_folder/
Get Cache file path
get_cache_dir()
The method returns the path to your current Cache file (the Cache name is always sh1 encoded):
cache/7505d64a54e061b7acd54ccd58b49dc43500b635.cache
FTP Class
CodeDmx has a FTP Class, that permits files to be transferred to a remote server. By this class you can move, rename and delete files or folders.
If you prefer you can store your FTP preferences in a config file in /application/Config/ftp.settings.php, and this will be used automatically.
First of all you need to load class
<?php
$this->load->library('ftp');
//Then
$this->ftp->connect();
Connect to host
Connects to the FTP server. Connection preferences are set by passing an array to the function, or you can store them in the config file in /application/Config/ftp.settings.php.
<?php
$this->ftp->connect();
Upload a file
Uploads a file to your server. You must supply the local path and the remote path, and you can optionally set the mode and permissions. Example:
<?php
$this->ftp->put('/local/path/to/myfile.html', '/public_html/myfile.html');
Parameters:
| Variable | Definition | Default value |
|---|---|---|
| $local_path (string) | Local file path | n/a |
| $remote_path (string) | Remote file path | n/a |
| $mode (string) | FTP mode (options are: ‘auto’, ‘binary’, ‘ascii’) | 'auto' |
| $permissions (int) | File permissions (octal) | '0777' |
Download a file
Downloads a file from your server. You must supply the remote path and the local path, and you can optionally set the mode. Example:
<?php
$this->ftp->download('/public_html/myfile.html', '/local/path/to/myfile.html');
Parameters:
| Variable | Definition | Default value |
|---|---|---|
| $remote_path (string) | Remote file path | n/a |
| $local_path (string) | Local file path | n/a |
| $mode (string) | FTP mode (options are: ‘auto’, ‘binary’, ‘ascii’) | 'auto' |
Delete a file
Supply the source path with the file name.
<?php
$this->ftp->delete_file('/public_html/joe/blog.html');
Delete a folder
Supply the source path to the directory with a trailing slash.
<?php
$this->ftp->delete_dir('/public_html/path/to/folder/');
List files
Permits you to retrieve a list of files on your server returned as an array. You must supply the path to the desired directory.
<?php
$list = $this->ftp->list('/public_html/');
print_r($list);
Create directory
Lets you create a directory on your server. Supply the path ending in the folder name you wish to create, with a trailing slash.
Permissions can be set by passing an octal value in the second parameter.
<?php
// Creates a folder named "bar"
$this->ftp->mkdir('/public_html/foo/bar/', 0755);
Rename a file
Permits you to rename a file. Supply the source file name/path and the new file name/path.
<?php
// Renames green.html to blue.html
$this->ftp->rename('/public_html/foo/green.html', '/public_html/foo/blue.html');
Move a file
Lets you move a file. Supply the source and destination paths:
<?php
// Moves blog.html from "joe" to "fred"
$this->ftp->move('/public_html/joe/blog.html', '/public_html/fred/blog.html');
Image Class
CodeDmx has a class to manipulate images in PHP as simple as possible. With this class, we can do:
- Resize images (free resize, resize to width, resize to height, resize to fit)
- Crop images
- Flip / rotate / adjust orientation
- Adjust brightness and contrast
- Desaturate, colorize, pixelate, blur, etc
- Overlay one image onto another (Watermarking)
- Add text using a font of your choice
- Convert between GIF, JPG, and PNG formats
First of all: A simple example
In the first line we try to load the image. In the second line we shrink it to fit within a 300x250 box, and save it to another path.
<?php
$this->load->library('image');
$this->image->from_file('image.jpg')
->best_fit(300, 250)
->to_file('/path/to/new/image.png', 'image/png');
Saving
It's necessary to save the image after you manipulate it.
<?php
// Or you can specify a new filename
$this->image->to_file('new-image.jpg', 'image/jpeg');
// Also, you can specify quality as a second parameter in percents within range 0 - 100
$this->image->to_file('new-image.jpg', 'image/jpeg', 90);
Converting between Formats
When you try to save it, you can determined by the file extension.
<?php
$this->image->from_file('/path/to/image.jpg')
->to_file('/path/to/new/image.png', 'image/png');
Method Chaining
This class supports method chaining, so you can make multiple changes and save the resulting image with just one line of code:
<?php
$this->image->from_file('/path/to/image.jpg')
->flip('x')
->rotate(90)
->best_fit(300, 250)
->desaturate()
->invert()
->to_file('/path/to/new-image.jpg', 'image/jpeg');
// You can chain all of the methods below as well methods above.
Loaders
from_data_uri($uri)
$uri
* (string) - A data URI.
from_file($file)
Loads an image from a file.
$file
* (string) - The image file to load.
from_new($width, $height, $color)
Creates a new image.
$width
* (int) - The width of the image.$height
* (int) - The height of the image.$color
(string|array) - Optional fill color for the new image (default 'transparent').
from_string($string)
Creates a new image from a string.
$string
* (string) - The raw image data as a string. Example:$string = file_get_contents('image.jpg');
Savers
to_data_uri($mime_type, $quality)
Generates a data URI.
$mime_type
(string) - The image format to output as a mime type (defaults to the original mime type).$quality
(int) - Image quality as a percentage (default 100).
Returns a string containing a data URI.
to_download($filename, $mime_type, $quality)
Forces the image to be downloaded to the clients machine. Must be called before any output is sent to the screen.
$filename
* (string) - The filename (without path) to send to the client (e.g. 'image.jpeg').$mime_type
(string) - The image format to output as a mime type (defaults to the original mime type).$quality
(int) - Image quality as a percentage (default 100).
to_file($file, $mime_type, $quality)
Writes the image to a file.
$mime_type
(string) - The image format to output as a mime type (defaults to the original mime type).$quality
(int) - Image quality as a percentage (default 100).
to_screen($mime_type, $quality)
Outputs the image to the screen. Must be called before any output is sent to the screen.
$mime_type
(string) - The image format to output as a mime type (defaults to the original mime type).$quality
(int) - Image quality as a percentage (default 100).
to_string($mime_type, $quality)
Generates an image string.
$mime_type
(string) - The image format to output as a mime type (defaults to the original mime type).$quality
(int) - Image quality as a percentage (default 100).
Utilities
get_aspect_ratio()
Gets the image's current aspect ratio.
Returns the aspect ratio as a float.
get_exif()
Gets the image's exif data.
Returns an array of exif data or null if no data is available.
get_height()
Gets the image's current height.
Returns the height as an integer.
get_mime_type()
Gets the mime type of the loaded image.
Returns a mime type string.
get_orientation()
Gets the image's current orientation.
Returns a string: 'landscape', 'portrait', or 'square'
get_width()
Gets the image's current width.
Returns the width as an integer.
Manipulation
auto_orient()
Rotates an image so the orientation will be correct based on its exif data. It is safe to call this method on images that don't have exif data (no changes will be made).
best_fit($max_width, $max_height)
Proportionally resize the image to fit inside a specific width and height.
$max_width
* (int) - The maximum width the image can be.$max_height
* (int) - The maximum height the image can be.
crop($x1, $y1, $x2, $y2)
Crop the image.
- $x1 - Top left x coordinate.
- $y1 - Top left y coordinate.
- $x2 - Bottom right x coordinate.
- $y2 - Bottom right x coordinate.
flip($direction)
Flip the image horizontally or vertically.
$direction
* (string) - The direction to flip: x|y|both
max_colors($max, $dither)
Reduces the image to a maximum number of colors.
$max
* (int) - The maximum number of colors to use.$dither
(bool) - Whether or not to use a dithering effect (default true).
overlay($overlay, $anchor, $opacity, $x_offset, $y_offset)
Place an image on top of the current image.
$overlay
* (string|SimpleImage) - The image to overlay. This can be a filename, a data URI, or a SimpleImage object.$anchor
(string) - The anchor point: 'center', 'top', 'bottom', 'left', 'right', 'top left', 'top right', 'bottom left', 'bottom right' (default 'center')$opacity
(float) - The opacity level of the overlay 0-1 (default 1).$x_offset
(int) - Horizontal offset in pixels (default 0).$y_offset
(int) - Vertical offset in pixels (default 0).
resize($width, $height)
Resize an image to the specified dimensions. If only one dimension is specified, the image will be resized proportionally.
$width
* (int) - The new image width.$height
* (int) - The new image height.
rotate($angle, $background_color)
Rotates the image.
$angle
* (int) - The angle of rotation (-360 - 360).$background_color
(string|array) - The background color to use for the uncovered zone area after rotation (default 'transparent').
text($text, $options, &$boundary)
Adds text to the image.
$text*
(string) - The desired text.$options
(array) - An array of options.font_file
* (string) - The TrueType (or compatible) font file to use.size
(int) - The size of the font in pixels (default 12).color
(string|array) - The text color (default black).anchor
(string) - The anchor point: 'center', 'top', 'bottom', 'left', 'right', 'top left', 'top right', 'bottom left', 'bottom right' (default 'center').x_offset
(int) - The horizontal offset in pixels (default 0).y_offset
(int) - The vertical offset in pixels (default 0).shadow
(array) - Text shadow params.x
* (int) - Horizontal offset in pixels.y
* (int) - Vertical offset in pixels.color
* (string|array) - The text shadow color.
$boundary
(array) - If passed, this variable will contain an array with coordinates that surround the text: [x1, y1, x2, y2, width, height]. This can be used for calculating the text's position after it gets added to the image.
thumbnail($width, $height, $anchor)
Creates a thumbnail image. This function attempts to get the image as close to the provided dimensions as possible, then crops the remaining overflow to force the desired size. Useful for generating thumbnail images.
$width
* (int) - The thumbnail width.$height
* (int) - The thumbnail height.$anchor
(string) - The anchor point: 'center', 'top', 'bottom', 'left', 'right', 'top left', 'top right', 'bottom left', 'bottom right' (default 'center').
Drawing
arc($x, $y, $width, $height, $start, $end, $color, $thickness)
Draws an arc.
$x
* (int) - The x coordinate of the arc's center.$y
* (int) - The y coordinate of the arc's center.$width
* (int) - The width of the arc.$height
* (int) - The height of the arc.$start
* (int) - The start of the arc in degrees.$end
* (int) - The end of the arc in degrees.$color
* (string|array) - The arc color.$thickness
(int|string) - Line thickness in pixels or 'filled' (default 1).
border($color, $thickness)
Draws a border around the image.
$color
* (string|array) - The border color.$thickness
(int) - The thickness of the border (default 1).
dot($x, $y, $color)
Draws a single pixel dot.
$x
* (int) - The x coordinate of the dot.$y
* (int) - The y coordinate of the dot.$color
* (string|array) - The dot color.
ellipse($x, $y, $width, $height, $color, $thickness)
Draws an ellipse.
$x
* (int) - The x coordinate of the center.$y
* (int) - The y coordinate of the center.$width
* (int) - The ellipse width.$height
* (int) - The ellipse height.$color
* (string|array) - The ellipse color.$thickness
(int|string) - Line thickness in pixels or 'filled' (default 1).
fill($color)
Fills the image with a solid color.
$color
(string|array) - The fill color.
line($x1, $y1, $x2, $y2, $color, $thickness)
Draws a line.
$x1
* (int) - The x coordinate for the first point.$y1
* (int) - The y coordinate for the first point.$x2
* (int) - The x coordinate for the second point.$y2
* (int) - The y coordinate for the second point.$color
(string|array) - The line color.$thickness
(int) - The line thickness (default 1).
polygon($vertices, $color, $thickness)
Draws a polygon.
$vertices
* (array) - The polygon's vertices in an array of x/y arrays. Example:[ ['x' => x1, 'y' => y1], ['x' => x2, 'y' => y2], ['x' => xN, 'y' => yN] ]
$color
* (string|array) - The polygon color.$thickness
(int|string) - Line thickness in pixels or 'filled' (default 1).
rectangle($x1, $y1, $x2, $y2, $color, $thickness)
Draws a rectangle.
$x1
* (int) - The upper left x coordinate.$y1
* (int) - The upper left y coordinate.$x2
* (int) - The bottom right x coordinate.$y2
* (int) - The bottom right y coordinate.$color
* (string|array) - The rectangle color.$thickness
(int|string) - Line thickness in pixels or 'filled' (default 1).
rounded_rectangle($x1, $y1, $x2, $y2, $radius, $color, $thickness)
Draws a rounded rectangle.
$x1
* (int) - The upper left x coordinate.$y1
* (int) - The upper left y coordinate.$x2
* (int) - The bottom right x coordinate.$y2
* (int) - The bottom right y coordinate.$radius
* (int) - The border radius in pixels.$color
* (string|array) - The rectangle color.$thickness
(int|string) - Line thickness in pixels or 'filled' (default 1).
Filters
blur($type, $passes)
Applies the blur filter.
$type
(string) - The blur algorithm to use: 'selective', 'gaussian' (default 'gaussian').$passes
(int) - The number of time to apply the filter, enhancing the effect (default 1).
brighten($percentage)
Applies the brightness filter to brighten the image.
$percentage
* (int) - Percentage to brighten the image (0 - 100).
colorize($color)
Applies the colorize filter.
$color
* (string|array) - The filter color.
contrast($percentage)
Applies the contrast filter.
$percentage
* (int) - Percentage to adjust (-100 - 100).
darken($percentage)
Applies the brightness filter to darken the image.
$percentage
* (int) - Percentage to darken the image (0 - 100).
desaturate()
Applies the desaturate (grayscale) filter.
duotone($light_color, $dark_color)
Applies the duotone filter to the image.
$light_color
* (string|array) - The lightest color in the duotone.$dark_color
* (string|array) - The darkest color in the duotone.
edge_detect()
Applies the edge detect filter.
emboss()
Applies the emboss filter.
invert()
Inverts the image's colors.
opacity()
Changes the image's opacity level.
$opacity
* (float) - The desired opacity level (0 - 1).
pixelate($size)
Applies the pixelate filter.
$size
(int) - The size of the blocks in pixels (default 10).
sepia()
Simulates a sepia effect by desaturating the image and applying a sepia tone.
sharpen()
Sharpens the image.
sketch()
Applies the mean remove filter to produce a sketch effect.
Color utilities
(static) adjust_color($color, $red, $green, $blue, $alpha)
Adjusts a color by increasing/decreasing red/green/blue/alpha values independently.
$color
* (string|array) - The color to adjust.$red
* (int) - Red adjustment (-255 - 255).$green
* (int) - Green adjustment (-255 - 255).$blue
* (int) - Blue adjustment (-255 - 255).$alpha
* (float) - Alpha adjustment (-1 - 1).
(static) darken_color($color, $amount)
Darkens a color.
$color
* (string|array) - The color to darken.$amount
* (int) - Amount to darken (0 - 255).
extract_colors($count = 10, $backgroundColor = null)
Extracts colors from an image like a human would do.™ This method requires the third-party library \League\ColorExtractor. If you're using Composer, it will be installed for you automatically.
$count
(int) - The max number of colors to extract (default 5).$backgroundColor
(string|array) - By default any pixel with alpha value greater than zero will be discarded. This is because transparent colors are not perceived as is.  So if you want to take transparency into account, you have to specify a default background color.
get_colorAt($x, $y)
Gets the RGBA value of a single pixel.
$x
* (int) - The horizontal position of the pixel.$y
* (int) - The vertical position of the pixel.
(static) lighten_color($color, $amount)
Lightens a color.
$color
* (string|array) - The color to lighten.$amount
* (int) - Amount to darken (0 - 255).
(static) normalize_color($color)
Normalizes a hex or array color value to a well-formatted RGBA array.
$color
* (string|array) - A CSS color name, hex string, or an array [red, green, blue, alpha].
You can pipe alpha transparency through hex strings and color names. For example:
#fff|0.50 <-- 50% white red|0.25 <-- 25% red
Mail Class
CodeDmx provides a simple, chainable class for sending basic emails.
First of all: A simple example
<?php
<EMAIL_ADDRESS>'Your Email')
->set_subject('Test Message')
<EMAIL_ADDRESS>'Domain.com')
->add_mail_header('Reply-To'<EMAIL_ADDRESS>'Test Name')
->add_generic_header('X-Mailer', 'PHP/' . phpversion())
->add_generic_header('Content-type', 'text/html; charset="utf-8"')
->set_message('This is a test message.')
->set_wrap(100);
$send = $this->mail->send();
echo ($send) ? 'Email sent successfully' : 'Could not send email';
Sending an Attachment
<?php
<EMAIL_ADDRESS>'Test user')
->set_from('mailtest', 'Test user 2')
->set_subject('This is a test message')
->add_attachment('test.txt')
->add_attachment('test.txt', 'test_attachment.txt')
->set_message('Hi there');
$send = $this->mail->send();
echo ($send) ? 'Email sent successfully' : 'Could not send email';
Available Methods
<?php
// $email The email address to send to
// $name The name of the person to send to
$this->mail->set_to($email, $name);
/*<EMAIL_ADDRESS>'Robert'); */
// Set the email subject
$this->mail->set_subject($subject);
/* $this->mail->set_subject('Test my mail of CodeDmx'); */
// Set the message to send
$this->mail->set_message($message);
/* $this->mail->set_message('Here is my test of mailing with the PHP Framework CodeDmx'); */
/* $this->mail->set_message('
Here is my test with HTML
'); */
// $path The file path of the attachment
// Optional $filename The filename of the attachment when emailed
$this->mail->add_attachment($path, $filename = null);
/* $this->mail->add_attachment('/path/to/file.txt') */
/* $this->mail->add_attachment('/path/to/file.txt', 'new_name_file.txt') */
// $email The email to send as from
// $name The name to send as from
$this->mail->set_from($email, $name);
/*<EMAIL_ADDRESS>'Ruben') */
// $header The header to add
// Optional $email The email to add
// Optional $name The name to add
$this->mail->add_mail_header($header, $email = null, $name = null);
/* $this->mail->add_mail_header('Reply-To'<EMAIL_ADDRESS>'Zuck') */
// $header The generic header to add
// $value The value of the header
$this->mail->add_generic_header($header, $value);
/* $this->mail->add_generic_header('Content-type', 'text/html, charset="utf-8"') */
// $wrap The number of characters at which the message will wrap
$this->mail->set_wrap($wrap);
/* $this->mail->set_wrap(100); */
// Send to 'To: ' address
$this->mail->send();
/*
$send = $this->mail->send();
echo ($send) ? 'Email send' : 'Unable to send';
*/
Paginator Class
CodeDmx has a lightweight PHP paginator, for generating pagination controls in the style of Stack Overflow and Flickr. The "first" and "last" page links are shown inline as page numbers, and excess page numbers are replaced by ellipses.
These examples show how the paginator handles overflow when there are a lot of pages. They're rendered using the sample templates provided in the examples directory, which depend on Twitter Bootstrap. You can easily use your own custom HTML to render the pagination control instead.
Default template:
Small template (useful for mobile interfaces):
The small template renders the page number as a select list to save space:
First of all you need to load the library file
<?php
$this->load->library('paginator');
Basic usage
<?php
$total_items = 1000;
$items_per_page = 50;
$current_page = 8;
$url_pattern = '/foo/page/(:num)';
$paginator = $this->paginator->get_pagination($total_items, $items_per_page, $current_page, $url_pattern);
?>

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

<?php
// Example of rendering the pagination control with the built-in template.
// See below for information about using other templates or custom rendering.
echo $paginator;
?>

This will output the following:

« Previous

1

...

5

6

7

8

9

10

11

12

...

20

Next »

Rendering a custom pagination control
Use get_pages(), get_next_url(), and get_prev_url() to render a pagination control with your own HTML. For example:
<?php
$total_items = 1000;
$items_per_page = 50;
$current_page = 8;
$url_pattern = '/foo/page/(:num)';
$this->paginator->get_pagination($total_items, $items_per_page, $current_page, $url_pattern);
?>

<?php if ($this->paginator->get_prev_url()): ?>

<a href="<?php echo $this->paginator->get_prev_url(); ?>">« Previous

<?php endif; ?>
<?php foreach ($this->paginator->get_pages() as $page): ?>
<?php if ($page['url']): ?>
<li <?php echo $page['is_current'] ? 'class="active"' : ''; ?>>
<a href="<?php echo $page['url']; ?>"><?php echo $page['num']; ?>

<?php else: ?>

<?php echo $page['num']; ?>

<?php endif; ?>
<?php endforeach; ?>
<?php if ($this->paginator->get_next_url()): ?>

<a href="<?php echo $this->paginator->get_next_url(); ?>">Next »

<?php endif; ?>

<?php echo $this->paginator->get_total_items(); ?> found.
Showing
<?php echo $this->paginator->get_current_page_first_item(); ?>
-
<?php echo $this->paginator->get_current_page_last_item(); ?>.

Pages data structure
$this->paginator->get_pages()
get_pages() returns a data structure like the following:
<?php
array (
array ('num' => 1, 'url' => '/foo/page/1', 'isCurrent' => false),
array ('num' => '...', 'url' => NULL, 'isCurrent' => false),
array ('num' => 5, 'url' => '/foo/page/5', 'isCurrent' => false),
array ('num' => 6, 'url' => '/foo/page/6', 'isCurrent' => false),
array ('num' => 7, 'url' => '/foo/page/7', 'isCurrent' => false),
array ('num' => 8, 'url' => '/foo/page/8', 'isCurrent' => true),
array ('num' => 9, 'url' => '/foo/page/9', 'isCurrent' => false),
array ('num' => 10, 'url' => '/foo/page/10', 'isCurrent' => false),
array ('num' => 11, 'url' => '/foo/page/11', 'isCurrent' => false),
array ('num' => 12, 'url' => '/foo/page/12', 'isCurrent' => false),
array ('num' => '...', 'url' => NULL, 'isCurrent' => false),
array ('num' => 20, 'url' => '/foo/page/20', 'isCurrent' => false),
)
Customizing the number of pages shown
By default, no more than 10 pages are shown, including the first and last page, with the overflow replaced by ellipses. To change the default number of pages:
$this->paginator->set_max_pages_to_show(5);
Query Builder Class
CodeDmx has a Mysqli Query Builder. This class can help you minified your code to connect with the database.
First of all you need to load the library file
<?php
$this->load->library('db');
// Then
$this->db->get('users');
Add multiple connection
<?php
$this->db->add_connection('slave', $GLOBALS['COD']->db['other']);
// Then
$this->db->connection('slave')->get('clients');
Select Query
The following functions allow you to build SQL SELECT statements:
<?php
$users = $this->db->get('users');
print_r($users);
$users = $this->db->get('users', 10);
print_r($users);
You can select with custom columns set.
<?php
$cols = array('id', 'name', 'email');
$users = $this->db->get('users', null, $cols);
if ($this->db->count > 0)
{
foreach ($users as $user)
{
print_r($user);
}
}
You can select just one row
<?php
$this->db->where('id', 1);
$user = $this->db->get_one('users');
echo $user['id'];
$stats = $this->db->get_one('users', 'sum(id), count(*) as cnt');
echo "total " . $stats['cnt'] . "users found";
You can select one column value of function result
<?php
$count = $this->db->get_value('users', 'count(*)');
echo "{$count} users found";
You can select one column value or function result from multiple rows:
<?php
// Select login from users
$logins = $this->db->get_value('users', 'login', null);
// Select login from users limit 5
$logins = $this->db->get_value('users', 'login', 5);
foreach ($logins as $login)
{
echo $login;
}
Insert Query
Just a simple example:
<?php
$data = array(
"login" => "admin",
"firstName" => "John",
"lastName" => "Dow"
);
$id = $this->db->insert('users', $data);
if ($id)
{
echo "user was created. Id=" . $id;
}
Insert with functions:
<?php
$data = array(
'login' => 'admin',
'active' => true,
'firstName' => 'John',
'lastName' => 'Dow',
'password' => $this->db->func('SHA1(?)', array('secretpassword+salt')),
// password = SHA1('secretpassword+salt')
'createdAt' => $this->db->now(),
// createdAt = NOW()
'expires' => $this->db->now('+1Y')
// expires = NOW() + interval 1 year
// Supported intervals [s]econd, [m]inute, [h]our, [d]ay, [M]onth, [Y]ear
);
$id = $this->db->insert('users', $data);
if ($id)
{
echo "user was created. Id=" . $id;
}
else
{
echo "insert failed " . $this->db->get_last_error();
}
Insert with on duplicate key update
<?php
$data = array(
'login' => 'admin',
'firstName' => 'John',
'lastName' => 'Dow',
'createdAt' => $this->db->now(),
'updatedAt' => $this->db->now()
);
$update_columns = array('updatedAt');
$last_insert_id = 'id';
$this->db->on_duplicate($update_columns, $last_insert_id);
$id = $this->db->insert('users', $data);
Insert multiple data at once
<?php
$data = array(
array('login' => 'admin',
'firstName' => 'John',
'lastName' => 'Doe'
),
array('login' => 'other',
'firstName' => 'Another',
'lastName' => 'User',
'password' => 'very_cool_hash'
)
);
$ids = $this->db->insert_multi('users', $data);
if ( ! $ids)
{
echo 'insert failed: ' . $this->db->get_last_error();
}
else
{
echo 'new users inserted with following id\'s: ' . implode(', ', $ids);
}
If all datasets only have the same keys, it can be simplified
<?php
$data = array(
array('admin', 'John', 'Doe'),
array('other', 'Another', 'User'),
);
$keys = array('login', 'firstName', 'lastName');
$ids = $this->db->insert_multi('users', $data, $keys);
if ( ! $ids)
{
echo 'insert failed: ' . $this->db->get_last_error();
}
else
{
echo 'new users inserted with following id\'s: ' . implode(', ', $ids);
}
Update Query
<?php
$data = array(
'firstName' => 'Bobby',
'lastName' => 'Tables',
// editCount = editCount + 2;
'editCount' => $this->db->inc(2),
// active = !active;
'active' => $this->db->not()
);
$this->db->where('id', 1);
if ($this->db->update('users', $data))
{
echo $this->db->count . ' records were updated';
}
else
{
echo 'update failed: ' . $this->db->get_last_error();
}
Update also support limit parameter
<?php
$this->db->update('users', $data, 10);
// Gives: UPDATE users SET ...  '%', 'LIKE');
BETWEEN / NOT BETWEEN
<?php
$this->db->where('id', array(4, 20), 'BETWEEN');
// or $this->db->where('id', array('BETWEEN' => array(4, 20)));
$results = $this->db->get('users');
print_r($results);
// Gives: SELECT * FROM users WHERE id BETWEEN 4 AND 20
IN / NOT IN
<?php
$this->db->where('id', array(1, 5, 27, -1, 'd'), 'IN');
// or $this->db->where('id', array('IN' => array(1, 5, 27, -1, 'd')));
$results = $this->db->get('users');
print_r($results);
// Gives: SELECT * FROM users WHERE id IN (1, 5, 27, -1, 'd');
OR CASE
<?php
$this->db->where('firstName', 'John');
$this->db->or_where('firstName', 'Peter');
$results = $this->db->get('users');
print_r($results);
// Gives: SELECT * FROM users WHERE firstName='John' OR firstName='peter'
NULL COMPARISON
<?php
$this->db->where('lastName', NULL, 'IS NOT');
$results = $this->db->get('users');
print_r($results);
// Gives: SELECT * FROM users WHERE lastName IS NOT NULL
Also you can use raw where conditions:
<?php
$this->db->where("id != companyId");
$this->db->where('DATE(createdAt) = DATE(lastLogin)');
$results = $this->db->get('users');
print_r($results);
// Gives: SELECT * FROM users WHERE id != companyId AND DATE(createdAt) = DATE(lastLogin)
Or raw condition with variables:
<?php
$this->db->where("(id = ? OR id = ?)", array(6, 2));
$this->db->where('login', 'mike');
$results = $this->db->get('users');
print_r($results);
// Gives: SELECT * FROM users WHERE (id = 6 OR id = 2) AND login='mike'
Find the total number of rows matched. Simple pagination example:
<?php
$offset = 10;
$count = 15;
$users = $this->db->with_total_count()->get('users', array($offset, $count));
echo "Showing {$count} from {$this->db->total_count}";
Ordering method
<?php
$this->db->order_by('id', 'ASC');
$this->db->order_by('login', 'DESC');
$this->db->order_by('RAND ()');
$results = $this->db->get('users');
print_r($results);
// Gives: SELECT * FROM users ORDER BY id ASC, login DESC, RAND();
Order by values
<?php
$this->db->order_by('userGoup', 'ASC', array('superuser', 'admin', 'users'));
$results = $this->db->get('users');
print_r($results);
// Gives: SELECT * FROM users ORDER BY FIELD (userGroup, 'superuser', 'admin', 'users') ASC;
If you are using set_prefix() functionality and need to use tables names in order_by() method make sure that table names are escaped with ''.
<?php
// WRONG
$this->db->set_prefix("t_");
$this->db->order_by("users.id", 'ASC');
$results = $this->db->get('users');
// WRONG: SELECT * FROM t_users ORDER BY users.id ASC;
$this->db->set_prefix("t_");
$this->db->order_by("users.id", 'ASC');
$results = $this->db->get('users');
// CORRECT: SELECT * FROM t_users ORDER BY t_users.id ASC;
Groping Method
<?php
$this->db->group_by('name');
$results = $this->db->get('users');
print_r($results);
// Gives: SELECT * FROM users GROUP BY name;
JOIN Method
<?php
$this->db->join('users u', 'p.id=u.id', 'LEFT');
$this->db->where('u.id', 6);
$results = $this->db->get('posts p', null, 'u.firstName, p.title');
print_r($results);
JOIN with 3 tables
<?php
$this->db->join('users u', 'p.id=u.id', 'LEFT');
$this->db->join('articles a', 'a.id=u.id', 'LEFT');
$this->db->where('u.id', 6);
$results = $this->db->get('posts p', null, 'u.firstName, p.title, a.lolname');
print_r($results);
JOIN with AND condition
<?php
$this->db->join('users u', 'p.id=u.id', 'LEFT');
$this->db->join_where('users u', 'u.id', 5);
$results = $this->db->get('posts p', null, 'u.firstName, p.title');
print_r($results);
// Gives: SELECT u.firstName, p.title FROM products p LEFT JOIN users u ON (p.id=u.id AND u.id=5)
JOIN with OR condition
<?php
$this->db->join('users u', 'p.id=u.id', 'LEFT');
$this->db->join_or_where('users u', 'u.id', 5);
$results = $this->db->get('posts p', null, 'u.firstName, p.title');
print_r($results);
// Gives: SELECT u.firstName, p.title FROM products p LEFT JOIN users u ON (p.id=u.id OR u.id=5)
Has method
A convenient function that returns TRUE if exists at least an element that satisfy the where condition specified calling the "where" method before this one.
<?php
$this->db->where('user', $user);
$this->db->where('password', md5($password));
if ($this->db->has('users'))
{
echo 'You are logged';
}
else
{
echo 'Wrong user/password';
}
Helper methods
Reconnect in case mysql connection died:
<?php
if ( ! $this->db->ping())
{
$this->db->connect();
}
Get last executed SQL query
<?php
$this->db->get('users');
echo 'Last executed query was '. $this->db->get_last_query();
Check if table exists
<?php
if ($this->db->table_exists('users'))
{
echo 'lml';
}
Real escape string
<?php
$escaped = $this->db->escape("' and 1=1");
Error helpers
<?php
$this->db->where('login', 'admin')->update('users', ['firstName' => 'Jack']);
if ($this->db->get_last_errno() === 0)
{
echo 'Update succesfull';
}
else
{
echo 'Update failed. Erro: '. $this->db->get_last_error();
}
Properties sharing
Also is possible to copy properties
<?php
$this->db->where('agentId', 10);
$this->db->where('active', TRUE);
$customers = $this->db->copy();
$res = $customers->get('customers', array(10, 10));
// Gives: SELECT * FROM customers WHERE agentId = 10 AND active = 1 LIMIT 10,10
$cnt = $this->db->get_value('customers', 'count(id)');
echo 'total records found: '. $cnt;
//Gives: SELECT count(id) FROM users WHERE agentId = 10 AND active = 1
Pagination
Use paginate() instead of get() to fetch paginated result
<?php
$page = 1;
$this->db->page_limit = 2;
$products = $this->db->array_builder()->paginate('products', $page);
echo 'showing $page out of '. $this->db->total_pages;
Query exectution time benchmarking
To track query execution time set_trace() function should be called.
<?php
$this->db->set_trace(TRUE);
$this->db->get('users');
$this->db->get('test');
print_r($this->db->trace);
/*
Array
(
[0] => Array
(
[0] => SELECT * FROM users
[1] => 0.00048494338989258
)
[1] => Array
(
[0] => SELECT * FROM test
[1] => 0.0076069831848145
)
)
*/
Subqueries
Subquery without an alias to use in insert/update/where Eg.  AND login = ?', $params);
print_r($users);
$params = array(10, 1, 10, 11, 2, 10);
$q = '(
SELECT a FROM t1
WHERE a = ? AND B = ?
ORDER BY a LIMIT ?
) UNION (
SELECT a FROM t2
WHERE a = ? AND B = ?
ORDER BY a LIMIT ?
);';
$result = $this->db->raw_query($q, $params);
print_r($result);
Session Class
CodeDmx has a Session class for you guessed it, managing sessions. Back in the day, when there weren't many open source frameworks on the market, developers had to code things from scratch to achieve certain functionality. This class's inception, is the from one of those instances. With this class you can easily time-out your authenticated users after a specified interval.
First of all you need to load the library file
<?php
$this->load->library('session');
Set session
Set key/value in session
<?php
$this->session->set('id', 12345);
// LIKE $_SESSION['id'] = 12345;
// OR
$session = array(
'id' => 12345,
'name' => 'John',
'email' =><EMAIL_ADDRESS>);
$this->session->set($session);
Has seted
Verify that a session value exists
<?php
var_dump($this->session->has_seted('id'));
// Output: bool
Unset
Remove session data
<?php
$this->session->_unset('id');
// LIKE unset($_SESSION['id']);
Get
Retrieve value stored in session by key.
<?php
echo $this->session->get('name');
// Output: John
// LIKE echo $_SESSION['name'];
Destroy
Destroys the session.
<?php
$this->session->end();
// similar like session_destroy();
TimeAgo Class
First of all you need to load the library file
<?php
// The array must have two values
// First one is about TimeZone like 'America/Mexico'
// Second one is about language, by default is in spanish (es)
$arg = array(null, 'en');
$this->load->library('timeago', $arg);
How to determine, what "ago" is
<?php
0 <-> 29 secs # => less than a minute
30 secs <-> 1 min, 29 secs # => 1 minute
1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes
44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour
89 mins, 29 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours
23 hrs, 59 mins, 29 secs <-> 47 hrs, 59 mins, 29 secs # => 1 day
47 hrs, 59 mins, 29 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days
29 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 1 month
59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months
1 yr <-> 2 yrs minus 1 secs # => about 1 year
2 yrs <-> max time or date # => over [2..X] years
Simple module, that displays the date in a "time ago" format.
Using this class
<?php
echo $this->timeago->in_words('2016-06-05 10:10:10');
Do you want the actual years, months, days, hours, minutes, seconds difference?
<?php
$this->load->library('timeago');
$dateDifferenceArray = $this->timeago->date_difference("2017-03-02 07:53:00", "2017-03-02 07:53:01");
// This will return an array with the following data:
[
'years' => 0
'months' => 0
'days' => 0
'hours' => 0
'minutes' => 0
'seconds' => 1
]
Upload class
CodeDmx has an Upload Class, that permits upload files to a remote server.
First of all you need to load class
<?php
$this->load->library('upload');
A simple example
<?php
if ( ! empty($_FILES))
{
$this->load->library('upload');
$this->upload->input('file');
$this->upload->destination($GLOBALS['COD']->doc . 'uploads' . DS);
$this->upload->save();
if ($this->upload->status())
{
echo 'is upload!';
}
}
?>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload now!" />
</form>
allow_mime_type
This method will allow you to establish a new mime type
Example:
<?php
$this->upload->allow_mime_type("text/html");
# But you can also use the mime_helping(Show more in $mime_helping)
$this->upload->allow_mime_type("image"); // Set: image/jpeg, image/jpg, image/pjpeg, image/png and image/gif.
allowed_mime_types
This method will allow you to set multiple mime types.
Example:
<?php
$this->upload->allowed_mime_types(array(
"text/plain",
"text/html"
));
auto_filename
This method will allow you to generate a unique name for the file you are uploading.
callback_input
This method will allow you to set a function to be executed to start the process. The method used must have a single parameter, which will be equivalent $this->upload->get_info()
Example:
<?php
$this->upload->callback_input(function($file){
echo "start!";
});
callback_output
This method will allow you to set a function to be executed at the end of the process. The method used must have a single parameter, which will be equivalent $this->upload->get_info()
Example:
<?php
$this->upload->callback_output(function($file){
rename($file->destination, time());
});
destination
This method allows you to set where the file will be saved trying to upload.
If the file path does not exist, you can set the parameter to true $create_if_not_exist when trying to create a new path.
Examples:
<?php
$this->upload->destination("./uploads");
$this->upload->destination("../uploads");
$this->upload->destination("/var/www/html/uploads");
$this->upload->destination("/var/www/html/uploads/tmp", true); // If path not exists, force create
filename
This method will allow you to set the name of the file you are uploading. For the extension of the file, use the wildcard %s.
Example:
<?php
$this->upload->filename("my_new_file.%s");
max_file_size
This method allows you to limit the size of file you are uploading.
Examples:
<?php
$this->upload->max_file_size("1m"); // Limit is 1MB(1048576 Bytes)
$this->upload->max_file_size("1.5Megabytes"); // Limit is 1.5MB(1572864 Bytes)
$this->upload->max_file_size("1.5MB"); // Limit is 1.5MB(1572864 Bytes)
$this->upload->max_file_size("12Gbytes"); // Limit is 12 GB(12884901888 Bytes)
$this->upload->max_file_size("1048576"); // Limit is 1MB(1048576 Bytes)
$this->upload->max_file_size("1331.2"); // Limit is 1.3KB(1331.2 Bytes)
upload_function
This method allows you to use the function that you need to upload files
Example:
<?php
$this->upload->upload_function("copy"); // Default is move_uploaded_file
size_format
Converts bytes to units of measurement.
Example:
<?php
$this->upload->size_format("1"); // return 1B
$this->upload->size_format("1024"); // return 1K
$this->upload->size_format("1048576"); // return 1M
$this->upload->size_format("1073741824"); // return 1G
$this->upload->size_format("1099511627776"); // return 1T
$this->upload->size_format("1331.2"); // return 1.3K
size_in_bytes
Converts measurement units to bytes
Example:
<?php
$this->upload->size_in_bytes("1"); // return 1
$this->upload->size_in_bytes("1B"); // return 1
$this->upload->size_in_bytes("1K"); // return 1024
$this->upload->size_in_bytes("1M"); // return 1048576
$this->upload->size_in_bytes("1G"); // return<PHONE_NUMBER>
$this->upload->size_in_bytes("1.56M"); // return 1635778.56
get_info()
Returns all information about uploading the file.
Example
<?php
stdClass Object
(
[status] => false // true if successful upload
[mime] => ""// File mime type
[filename] => "" // The new filename
[original] => "" // Filename before to save in destination directory
[size] => 0 // In bytes
[size_formated] => 0B // In B, K, M and G
[destination] => "" // Default is current dir ( ./ )
[allowed_mime_types]=> Array () // All allowed mime types
[log] => Array () // All logs
[error] => 0 // File error
)
status()
Returns the status of the upload. If the condition is false, then the file has not yet risen, if the state is true, the file upload was performed successfully.
is_dirpath
Validates the directory path "is_dirpath($directory)"
is_filename
Validates the filename "is_filename($filename)"
allow_overwriting()
If the file you try to upload already exists, it can not be overwritten unless you enable overwriting using this method.
check_mime_type
Validates the mime type of the file. If you have not enabled any mime type, the validation will return true. "check_mime_type($mime_type)"
clear_allowed_mime_types()
Removes all previously enabled mime types.
dir_exists
Checks if the directory exists. "dir_exists($directory)"
file_exists
Checks if the file exists. "file_exists($file)"
save()
This method loads the file, applies filters and save the file to the set destination.
Validator Class
CodeDmx has a Validator class. This class can help you to validate inputs, form, or data that you sent.
First of all you need to load class
<?php
$this->load->library('validate');
A simple example
Before to explain this example, let's to describe the ideal scenario:
- A form is displayed
- The user fill it and submit
Runs the validation of the form submited:
<?php
$is_valid = $this->validate->is_valid($_POST, array(
'username' => 'required|alpha_numeric',
'password' => 'required|max_len,100|min_len,6'
));
if ($is_valid === TRUE)
{
//continue
}
else
{
print_r($is_valid);
}
Available Methods
This are all available methods of Validator Class
<?php
// The short way to validate
$this->validate->is_valid(array $data, array $rules);
// Get or set the validation rules
$this->validate->validation_rules(array $rules);
// Get or set the filtering rules
$this->validate->filter_rules(array $rules);
// Run the filter and validation routines
$this->validate->run(array $data);
// Strips and encodes unwanted characters
$this->validate->xss_clean(array $data);
// Sanitizes data and converts strings to UTF-8, this isn't required, but it's safest to do so.
$this->validate->sanitize(array $input);
// Validates input data according to the provided rules
$this->validate->validate(array $input, array $rules);
// Filters input data according to the provided filter
$this->validate->filter(array $input, array $filter);
// Returns human readable error text in an array or string
$this->validate->get_readable_errors($convert_to_string = false);
// Fetch an array of validation errors indexed by the field names
$this->validate->get_errors_array();
// Override field names with readable ones for errors
$this->validate->set_field_name($field, $readable_name);
Long format example
Runs the validation of the form submited:
<?php
$_POST = $this->validate->sanitize($_POST); // You don't have to do this, but it's safest to do.
$this->validate->validation_rules(array(
'username' => 'required|alpha_numeric|max_len,20|min_len,6',
'password' => 'required|max_len,100|min_len,6',
'email' => 'required|valid_email'
));
$this->validate->filter_rules(array(
'username' => 'trim|sanitize_string',
'password' => 'trim',
'email' => 'trim|sanitize_email'
));
$validated_data = $this->validate->run($_POST);
if ($validated_data === FALSE)
{
echo $this->validate->get_readable_errors(TRUE);
}
else
{
print_r($validated_data); // validation successful
}
Creating your own validators and filters
Adding custom validators and filters is made easy by using callback functions.
<?php
/*
Create a csutom validation rule named "is_object".
This callback receives 3 arguments:
The field to validate, the values being validated, and any parameters used in the validation rule.
It sould return a boolean value indicating whether the value is valid.
*/
$this->validate->add_validator('is_object', function($field, $input, $param = NULL) {
return is_object($input[$field]);
});
/*
Create a custom filter named "upper".
The callback function receives two arguments:
The value to filter, and any parameters used in the filter rule. It should returned the filtered value.
*/
$this->validate->add_filter('upper', function($value, $param = NULL) {
return strtoupper($value);
});
Available Filters
Filters can be any PHP function that returns a string. You don't need to create your own if a PHP function exists that does what you want the filter to do.
| Rule | Description |
|---|---|
| sanitize_string | Remove script tags and encode HTML entities, similar to $this->validate->xss_clean(); |
| urlencode | Encode url entities |
| htmlencode | Encode HTML entities |
| sanitize_email | Remove illegal characters from email addresses |
| sanitize_numbers | Remove any non-numeric characters |
| sanitize_floats | Remove any non-float characters |
| trim | Remove spaces from the beginning and end of strings |
| base64_encode | Base64 encode the input |
| base64_decode | Base64 decode the input |
| sha1 | Encrypt the input with the secure sha1 algorithm |
| md5 | MD5 encode the input |
| noise_words | Remove noise words from string |
| json_encode | Create a json representation of the input |
| json_decode | Decode a json string |
| rmpunctuation | Remove all known punctuation characters from a string |
| basic_tags | Remove all layout orientated HTML tags from text. Leaving only basic tags |
| whole_number | Check that the provided numeric value is represented as a whole number |
Validate file fields
When you use a form that want to upload files, you can validate the file too
<?php
$is_valid = $this->validate->is_valid(array_merge($_POST, $_FILES), array(
'title' => 'required|alpha_numeric',
'image' => 'required_file|extension,png;jpg'
));
if ($is_valid === TRUE)
{
//continue
}
else
{
print_r($is_valid);
}
URL Exists (Example)
<?php
$_POST = array(
'url' => 'http://asidnqowineoqiwneoinspoqwehpi1.com' // This url doesn't exist
);
$rules = array(
'url' => 'url_exists'
);
$is_valid = $this->validate->validate($_POST, $rules);
if ($is_valid === TRUE)
{
echo 'The URL provided is valid';
}
else
{
print_r($this->validate->get_readable_errors());
}
Validate street address (Example)
<?php
$data = array(
'street' => 'Kuwait 6958'
);
$validate = $this->validate->is_valid($data, array(
'street' => 'required|street_address'
));
if ($validate === TRUE)
{
echo 'Valid Street Address';
}
else
{
print_r($validate);
}
Sanitize string (Example)
<?php
$_POST = array(
'string' => ''
);
$filter = array(
'string' => 'sanitize_string'
);
print_r($this->validate->filter($_POST, $filter));
Match strings (Example)
<?php
$data = array(
'username' => 'myusername',
'password' => 'mypassword',
'password_confirm' => 'mypa33word'
);
$is_valid = $this->validate->is_valid($data, array(
'username' => 'required|alpha_numeric',
'password' => 'required|max_len,100|min_len,6',
'password_confirm' => 'equalsfield,password'
));
if ($is_valid === TRUE)
{
// continue
}
else
{
print_r($is_valid);
}
Escaping Mysql Strings (Example)
<?php
$_POST = array(
'username' => 'my username',
'password' => "' OR ''='"
);
$this->validate->sanitize($_POST);
$filter = array(
'username' => 'noise_words',
'password' => 'trim|strtolower|addslashes'
);
print_r($this->validate->filter($_POST, $filter));
Custom validator (Example)
<?php
// Add the custom validator
$this->validate->add_validator('is_object', function($field, $input, $param = NULL) {
return is_object($input[$field]);
});
// Generic data
$input_data = array(
'not_object' => 'asdqwezxc',
'valid_object' => new stdClass()
);
$rules = array(
'not_object' => 'is_object',
'valid_object' => 'is_object'
);
/*
Long Method
*/
$validated = $this->validate->validate(
$input_data, $rules
);
if ($validated === TRUE)
{
echo 'Validation passed!';
}
else
{
echo $this->validate->get_readable_errors(TRUE);
}
/*
Short Method
*/
$is_valid = $this->validate->is_valid($input_data, $rules);
if ($is_valid === TRUE)
{
echo 'Validation passed!';
}
else
{
print_r($is_valid);
}
Zip Class
First of all you need to load the library file
<?php
$this->load->library('zip');
Adding new files to the zip / Creating new zip file:
Multi-line style
<?php
$this->zip->zip_start("path/to/new/or/old/zip_file.zip");
$this->zip->zip_add("path/to/example.png"); // adding a file
$this->zip->zip_add(array("path/to/example1.png","path/to/example2.png")); // adding two files as an array
$this->zip->zip_add(array("path/to/example1.png","path/to/directory/")); // adding one file and one directory
$this->zip->zip_end();
One-line style
<?php
$this->zip->zip_files(array("path/to/new/or/old/zip_file.zip","path/to/directory/"),"path/to/zip/file.zip");
Extracting (unzipping) files:
Multi-line style
<?php
$this->zip->unzip_file("path/to/new/or/old/zip_file.zip");
$this->zip->unzip_to("path/to/containing/directory/");
One-line style
<?php
$this->zip->unzip_file("path/to/new/or/old/zip_file.zip","path/to/containing/directory/");


--- layout: default title: Dokdo Island meta: This is website for save Dokdo Island from dispute exists regarding Dokdo ---
Dokdo is the easternmost end of Korea's territories and is located 87.4km to the southeast of Ulleungdo of Korea and 157.5km to the northwest of Oki island of Japan. Dokdo, the easternmost island in East Sea, is an integral part of Korean territory historically, geographically, and under international law. No territorial dispute exists regarding Dokdo, and Dokdo is not a matter to be dealt with through diplomatic negotiations or judicial settlement.


Creating a Custom Node
Dynamo offers several different methods for creating custom nodes. You can build custom nodes from scratch, from an existing graph, or explicitly in C#. In this section we will cover building a custom node in the Dynamo UI from an existing graph. This method is ideal for cleaning up the workspace, as well as packaging a sequence of nodes to reuse elsewhere.
Custom Nodes for UV Mapping
In the image below, we map a point from one surface to another using UV coordinates. We'll use this concept to create a panelized surface which references curves in the XY plane. We'll create quad panels for our panelization here, but using the same logic, we can create a wide variety of panels with UV mapping. This is a great opportunity for custom node development because we will be able to repeat a similar process more easily in this graph or in other Dynamo workflows.
Creating a Custom Node from an Existing Graph
Download and unzip the example files for this exercise (Right click and choose "Save Link As..."). A full list of example files can be found in the Appendix. UV-CustomNode.zip
Let’s start by creating a graph that we want to nest into a custom node. In this example, we will create a graph that maps polygons from a base surface to a target surface, using UV coordinates. This UV mapping process is something we use frequently, making it a good candidate for a custom node. For more information on surfaces and UV space, see section 5.5. The complete graph is UVmapping_Custom-Node.dyn from the .zip file downloaded above.
- Code Block: Create a range of 10 numbers between 45 and negative 45 using a code block.
- Point.ByCoordinates: Connect the output of the Code Block to the ‘x’ and ‘y’ inputs and set the lacing to cross-reference. You should now have a grid of points.
- Plane.ByOriginNormal: Connect the ‘Point’ output to the ‘origin’ input to create a plane at each of the points. The default normal vector of (0,0,1) will be used.
- Rectangle.ByWidthLength: Connect the planes from the previous step into the ‘plane’ input, and use a Code Block with a value of 10 to specify the width and length.
You should now see a grid of rectangles. Let’s map these rectangles to a target surface using UV coordinates.
- Polygon.Points: Connect the Rectangle output from the previous step to the ‘polygon’ input to extract the corner points of each rectangle. These are the points that we will map to the target surface.
- Rectangle.ByWidthLength: Use a Code Block with a value of 100 to specify the width and length of a rectangle. This will be the boundary of our base surface.
- Surface.ByPatch: Connect the Rectangle from the previous step to the ‘closedCurve’ input to create a base surface.
- Surface.UVParameterAtPoint: Connect the ‘Point’ output of the Polygon.Points node and the ‘Surface’ output of the Surface.ByPatch node to return the UV parameter at each point.
Now that we have a base surface and a set of UV coordinates, we can import a target surface and map the points between surfaces.
- File Path: Select the file path of the surface you want to import. The file type should be .SAT. Click the "Browse..." button and navigate to the UVmapping_srf.sat file from the .zip file downloaded above.
- Geometry.ImportFromSAT: Connect the file path to import the surface. You should see the imported surface in the geometry preview.
- UV: Connect the UV parameter output to a UV.U and a UV.V node.
- Surface.PointAtParameter: Connect the imported surface as well as the u and v coordinates. You should now see a grid of 3D points on the target surface.
The final step is to use the 3D points to construct rectangular surface patches.
- PolyCurve.ByPoints: Connect the points on the surface to construct a polycurve through the points.
- Boolean: Add a Boolean to the workspace and connect it to the ‘connectLastToFirst’ input and toggle to True to close the polycurves. You should now see rectangles mapped to the surface.
- Surface.ByPatch: Connect the polycurves to the ‘closedCurve’ input to construct surface patches.
Now let’s select the nodes that we want to nest into a Custom Node, thinking about what we want to be the inputs and outputs of our node. We want our Custom Node to be as flexible as possible, so it should be able to map any polygons, not just rectangles.
Select the above nodes (beginning with Polygon.Points), right click on the workspace and select ‘node from selection’.
In the Custom Node Properties dialog, assign a name, description, and category to the Custom Node.
The Custom Node has considerably cleaned up the workspace. Notice that the inputs and outputs have been named based on the original nodes. Let’s edit the Custom Node to make the names more descriptive.
Double click the Custom Node to edit it. This will open a workspace with a yellow background representing the inside of the node.
- Inputs: Change the input names to baseSurface and targetSurface.
- Outputs: Add an additional output for the mapped polygons.
Save the custom node and return to the home workspace.
The MapPolygonsToSurface node reflects the changes we just made.
We can also add to the robustness of the Custom Node by adding in Custom Comments. Comments can help to hint at the input and output types or explain the functionality of the node. Comments will appear when the user hovers over an input or output of a Custom Node.
Double click the Custom Node to edit it. This will re-open the yellow background workspace.
- Begin editing the Input Code Block. To start a Comment, type "//" followed by the comment text. Type anything that may help to clarify the Node - Here we will describe the targetSurface.
- Let's also set the default value for the inputSurface by setting the input type equal to a value. Here, we will set the default value to the original Surface.ByPatch set.
Comments can also be applied to the Outputs. Begin editing the text in the Output Code Block. To start a Comment, type "//" followed by the comment text. Here we will clarify the Polygons and the surfacePatches Outputs by adding a more in-depth description.
>
- Hover over the Custom Node Inputs to see the Comments.
- With the default value set on our inputSurface, we can also run the definition without a surface input.


Providing Quality Holistic Fitness For The Triangle - NC
| Why Choose Holistic health |
Humans are multi-dimensional beings comprised of the body, mind, soul and emotions, and we believe effective health care attends to all of these aspects as they are interrelated and affect one another. To complicate matters, each dimension holds sub-levels, too. Most fitness trainers focus on the body, and it’s no wonder since achieving and maintaining a healthy physical machine requires a deep understanding of how it functions. Most personal trainers today share extensive knowledge and experience with their clients in both exercise and nutrition.
Medical research indicates that working out in conjunction with an organic food-based diet provide:
Improved cardiovascular health
Long-term weight loss and stability
Prevention of cardio vascular related illnesses
Prevention from diabetes and other
Lower cholesterol
Lower blood pressure
Reduce stress
Toning and firming
Build muscle
Increased muscular endurance
Increased flexibility
What Is Holistic Health
World known holistic medical expert Robert Puff, Ph.D, explains in this video what holistic health isand why it's so vital to keeping life-long physical fitness. Thanks to Doctor Robert Puff for posting the information and our partners at South Eastern Wellness for suggesting the information.


Here be a smattering of our series, adventures of all kinds. Find a whole new world to explore!
The Magical Archive lists only the series we have IN FULL. Come in to see what else we’ve begun collecting.
The Malazan Empire is stretched thin. With enemies on all sides, the Empress plots against her own soldiers. Sergeant Whiskeyjack is torn between leading his Bridgeburners to continue their occupation of Darujhistan or seek vengeance against the Empire that betrayed them all. But with rebellions rising in the desert, the bones of the old Empire walking again, old war crimes rearing their heads, and the Gods playing their own games with mortal lives, the petty gripes of a soldier pale in comparison.
Colourful characters fill Canadian Steven Erickson’s dark and brutal world that can never escape the mistakes of its past. This ten book series – with a number of side novels – starts with “The Gardens of the Moon”. Rent it now!
“It was all very well going on about pure logic and how the universe was ruled by logic and the harmony of numbers, but the plain fact of the matter was that the Disc was manifestly traversing space on the back of a giant turtle and the gods had a habit of going round to atheists' houses and smashing their windows.”
  Forty-eight different adventures following a wide variety of heroes and villains, and we've got them ALL!
Ask Edward where to start!
A hilarious romp through piles of bones and a haunted mansion in space. Gideon the Ninth is the first book of a brand new trilogy by Tasmyn Muir featuring more skeletons than any other book in our collection.
Harrowhark Nonagesimus, Reverend Daughter of the Ninth House, has been given an opportunity. If she and her Cavalier can complete a series of puzzles in the First House, she may be invited into the Emperor’s personal guard of necromancers. She’ll be competing against all the other houses and their cavaliers, but they’re the least of her worries. Harrow’s chosen cavalier is her old childhood rival, Gideon Nav. Gideon left her manners at home, and packed only her sunglasses, her sword, and enough porn to last her the whole trip. What could go wrong? FIND OUT.


{% extends "base.html" %} {% load staticfiles %} {% load bootstrap %} {% block content %}
There are currently {{ task_count }} jobs in the queue.