Security helper in codeigniter

Security Helper

The Security Helper file contains security related functions.

Loading this Helper

This helper is loaded using the following code:

Available Functions

The following functions are available:

xss_clean($str[, $is_image = FALSE])

Parameters:
  • $str (string) – Input data
  • $is_image (bool) – Whether we’re dealing with an image
  • Returns:XSS-clean string
    Return type:string

    Provides Cross Site Script Hack filtering.

    This function is an alias for CI_Input::xss_clean().

    sanitize_filename($filename)

    Parameters:
  • $filename (string) – Filename
  • Returns:Sanitized file name
    Return type:string

    Provides protection against directory traversal.

    This function is an alias for CI_Security::sanitize_filename().

    do_hash($str[, $type = ‘sha1’])

    Parameters:
  • $str (string) – Input
  • $type (string) – Algorithm
  • Returns:Hex-formatted hash
    Return type:string

    Permits you to create one way hashes suitable for encrypting passwords. Will use SHA1 by default.

    Examples:

    Note
    This function was formerly named dohash(), which has been removed in favor of do_hash().

    Note
    This function is DEPRECATED. Use the native hash() instead.

    do_hash($str[, $type = ‘sha1’])

    Parameters:
  • $str (string) – Input string
  • Returns:The input string with no image tags
    Return type:string

    This is a security function that will strip image tags from a string. It leaves the image URL as plain text.

    Example:

    This function is an alias for CI_Security::strip_image_tags()

    encode_php_tags($str)

    Parameters:
  • $str (string) – Input string
  • Returns:Safely formatted string
    Return type:string

    This is a security function that converts PHP tags to entities.

    Note
    xss_clean() does this automatically, if you use it.

    Example:

    Smiley helper in codeigniter

    Smiley Helper

    The Smiley Helper file contains functions that let you manage smileys (emoticons).

    !Important
    The Smiley helper is DEPRECATED and should not be used. It is currently only kept for backwards compatibility.

    Loading this Helper

    This helper is loaded using the following code:

    Overview

    The Smiley helper has a renderer that takes plain text smileys, like 🙂 and turns them into a image representation, like smile!

    It also lets you display a set of smiley images that when clicked will be inserted into a form field. For example, if you have a blog that allows user commenting you can show the smileys next to the comment form. Your users can click a desired smiley and with the help of some JavaScript it will be placed into the form field.


    Clickable Smileys Tutorial

    Here is an example demonstrating how you might create a set of clickable smileys next to a form field. This example requires that you first download and install the smiley images, then create a controller and the View as described.

    Important

    Before you begin, please download the smiley images and put them in a publicly accessible place on your server. This helper also assumes you have the smiley replacement array located at application/config/smileys.php

    The Controller

    In your application/controllers/ directory, create a file called Smileys.php and place the code below in it.

    Important

    Change the URL in the get_clickable_smileys() function below so that it points to your smiley folder.

    You’ll notice that in addition to the smiley helper, we are also using the Table Class:

    In your application/views/ directory, create a file called smiley_view.php and place this code in it:

    Field Aliases

    When making changes to a view it can be inconvenient to have the field id in the controller. To work around this, you can give your smiley links a generic name that will be tied to a specific id in your view.

    To map the alias to the field id, pass them both into the smiley_js() function:

    Available Functions
    get_clickable_smileys($image_url[, $alias = ”[, $smileys = NULL]])

    Parameters:
  • $image_url (string) – URL path to the smileys directory
  • $alias (string) – Field alias
  • Returns:An array of ready to use smileys
    Return type:array

    Returns an array containing your smiley images wrapped in a clickable link. You must supply the URL to your smiley folder and a field id or field alias.

    Example:

    smiley_js([$alias = ”[, $field_id = ”[, $inline = TRUE]]])

    Parameters:
  • $alias (string) – Field alias
  • $field_id (string) – Field ID
  • $inline (bool) – Whether we’re inserting an inline smiley
  • Returns:Smiley-enabling JavaScript code
    Return type:string

    Generates the JavaScript that allows the images to be clicked and inserted into a form field. If you supplied an alias instead of an id when generating your smiley links, you need to pass the alias and corresponding form id into the function. This function is designed to be placed into the area of your web page.

    Example:

    parse_smileys([$str = ”[, $image_url = ”[, $smileys = NULL]]])

    Parameters:
  • $str (string) – Text containing smiley codes
  • $image_url (string) – URL path to the smileys directory
  • $smileys (array) – An array of smileys
  • Returns:Parsed smileys
    Return type:string

    Takes a string of text as input and replaces any contained plain text smileys into the image equivalent. The first parameter must contain your string, the second must contain the URL to your smiley folder

    Example:

    String helper in codeigniter

    String Helper

    The String Helper file contains functions that assist in working with strings.

    !Important
    Please note that these functions are NOT intended, nor suitable to be used for any kind of security-related logic.

    Loading this Helper

    This helper is loaded using the following code:

    Available Functions

    The following functions are available:


    random_string([$type = ‘alnum'[, $len = 8]])

    Parameters:
  • $type (string) – Randomization type
  • $len (int) – Output string length
  • Returns:A random string
    Return type:string

    Generates a random string based on the type and length you specify. Useful for creating passwords or generating random hashes.

    The first parameter specifies the type of string, the second parameter specifies the length. The following choices are available:

    1. alpha: A string with lower and uppercase letters only.
    1. alnum: Alpha-numeric string with lower and uppercase characters.
    1. basic: A random number based on mt_rand().
    1. numeric: Numeric string.
    1. nozero: Numeric string with no zeros.
    1. md5: An encrypted random number based on md5() (fixed length of 32).
    1. sha1: An encrypted random number based on sha1() (fixed length of 40).

    Usage example:

    Note
    Usage of the unique and encrypt types is DEPRECATED. They are just aliases for md5 and sha1 respectively.

    increment_string($str[, $separator = ‘_'[, $first = 1]])

    Parameters:
  • $str (string) – Input string
  • $separator (string) – Separator to append a duplicate number with
  • $first (int) – Starting number
  • Returns:An incremented string
    Return type:string

    Increments a string by appending a number to it or increasing the number. Useful for creating “copies” or a file or duplicating database content which has unique titles or slugs.

    Usage example:

    alternator($args)

    Parameters:
  • $args (mixed) – A variable number of arguments
  • Returns:Alternated string(s)
    Return type:mixed

    Allows two or more items to be alternated between, when cycling through a loop. Example:

    You can add as many parameters as you want, and with each iteration of your loop the next item will be returned.

    Note
    To use multiple separate calls to this function simply call the function with no arguments to re-initialize.

    repeater($data[, $num = 1])

    Parameters:
  • $data (string) – Input
  • $num (int) – Number of times to repeat
  • Returns:Repeated string
    Return type:string

    Generates repeating copies of the data you submit. Example:

    The above would generate 30 newlines.

    Note!
    This function is DEPRECATED. Use the native str_repeat() instead.

    reduce_double_slashes($str)

    Parameters:
  • $str (string) – Input string
  • Returns:A string with normalized slashes
    Return type:string

    Converts double slashes in a string to a single slash, except those found in URL protocol prefixes (e.g. http://).

    Example:

    strip_slashes($data)

    Parameters:
  • $data (mixed) – Input string or an array of strings
  • Returns:String(s) with stripped slashes
    Return type:mixed

    Removes any slashes from an array of strings.

    Example:

    The above will return the following array:

    Note
    For historical reasons, this function will also accept and handle string inputs. This however makes it just an alias for stripslashes().

    trim_slashes($str)

    Parameters:
  • $str (string) – Input string
  • Returns:Slash-trimmed string
    Return type:string

    Removes any leading/trailing slashes from a string. Example:

    This function is DEPRECATED. Use the native trim() instead: | | trim($str, ‘/’);

    reduce_multiples($str[, $character = ”[, $trim = FALSE]])

    Parameters:
  • $str (string) – Text to search in
  • $character (string) – Character to reduce
  • $trim (bool) – Whether to also trim the specified character
  • Returns:Reduced string
    Return type:string

    Reduces multiple instances of a particular character occurring directly after each other. Example:

    Example:

    If the third parameter is set to TRUE it will remove occurrences of the character at the beginning and the end of the string. Example:

    quotes_to_entities($str)

    Parameters:
  • $str (string) – Input string
  • Returns:String with quotes converted to HTML entities
    Return type:string

    Converts single and double quotes in a string to the corresponding HTML entities. Example:

    strip_quotes($str)

    Parameters:
  • $str (string) – Input string
  • Returns:String with quotes stripped
    Return type:string

    Removes single and double quotes from a string. Example:

    Text Helper in codeigniter

    Text Helper

    The Text Helper file contains functions that assist in working with text.

    Loading this Helper

    This helper is loaded using the following code:

    Available Functions

    The following functions are available:


    word_limiter($str[, $limit = 100[, $end_char = ‘…’]])

    Parameters:
  • $str (string) – Input string
  • $limit (int) – Limit
  • $end_char (string) – End character (usually an ellipsis)
  • Returns:Word-limited string
    Return type:string

    Truncates a string to the number of words specified. Example:

    The third parameter is an optional suffix added to the string. By default it adds an ellipsis.

    character_limiter($str[, $n = 500[, $end_char = ‘…’]])

    Parameters:
  • $str (string) – Input string
  • $n (int) – Number of characters
  • $end_char (string) – End character (usually an ellipsis)
  • Returns:Character-limited string
    Return type:string

    Truncates a string to the number of characters specified. It maintains the integrity of words so the character count may be slightly more or less than what you specify.

    Usage example:

    The third parameter is an optional suffix added to the string, if undeclared this helper uses an ellipsis.

    Note! If you need to truncate to an exact number of characters please see the ellipsize() function below.

    ascii_to_entities($str)

    Parameters:
  • $str (string) – Input string
  • Returns:A string with ASCII values converted to entities
    Return type:string

    Converts ASCII values to character entities, including high ASCII and MS Word characters that can cause problems when used in a web page, so that they can be shown consistently regardless of browser settings or stored reliably in a database. There is some dependence on your server’s supported character sets, so it may not be 100% reliable in all cases, but for the most part it should correctly identify characters outside the normal range (like accented characters).

    Example:

    convert_accented_characters($str)

    Parameters:
  • $str (string) – Input string
  • Returns:A string with accented characters converted
    Return type:string

    Transliterates high ASCII characters to low ASCII equivalents. Useful when non-English characters need to be used where only standard ASCII characters are safely used, for instance, in URLs.

    Example:

    Note! This function uses a companion config file application/config/foreign_chars.php to define the to and from array for transliteration.

    word_censor($str, $censored[, $replacement = ”])

    Parameters:
  • $str (string) – Input string
  • $censored (array) – List of bad words to censor
  • $replacement (string) – What to replace bad words with
  • Returns:Censored string
    Return type:string

    Enables you to censor words within a text string. The first parameter will contain the original string. The second will contain an array of words which you disallow. The third (optional) parameter can contain a replacement value for the words. If not specified they are replaced with pound signs: ####.

    Example:

    highlight_code($str)

    Parameters:
  • $str (string) – Input string
  • Returns:String with code highlighted via HTML
    Return type:string

    Colorizes a string of code (PHP, HTML, etc.). Example:

    The function uses PHP’s highlight_string() function, so the colors used are the ones specified in your php.ini file.

    highlight_phrase($str, $phrase[, $tag_open = ‘‘[, $tag_close = ‘‘]])

    Parameters:
  • $str (string) – Input string
  • $phrase (string) – Phrase to highlight
  • $tag_open (string) – Opening tag used for the highlight
  • $tag_close (string) – Closing tag for the highlight
  • Returns:String with a phrase highlighted via HTML
    Return type:string

    Will highlight a phrase within a text string. The first parameter will contain the original string, the second will contain the phrase you wish to highlight. The third and fourth parameters will contain the opening/closing HTML tags you would like the phrase wrapped in.

    Example:

    The above code prints:

    Note! This function used to use the tag by default. Older browsers might not support the new HTML5 mark tag, so it is recommended that you insert the following CSS code into your stylesheet if you need to support such browsers:

    word_wrap($str[, $charlim = 76])

    Parameters:
  • $str (string) – Input string
  • $charlim (int) – Character limit
  • Returns:Word-wrapped string
    Return type:string

    Wraps text at the specified character count while maintaining complete words.

    Example:

    ellipsize($str, $max_length[, $position = 1[, $ellipsis = ‘…’]])

    Parameters:
  • $str (string) – Input string
  • $max_length (int) – String length limit
  • $position (mixed) – Position to split at (int or float)
  • $ellipsis (string) – What to use as the ellipsis character
  • Returns:Ellipsized string
    Return type:string

    This function will strip tags from a string, split it at a defined maximum length, and insert an ellipsis.

    The first parameter is the string to ellipsize, the second is the number of characters in the final string. The third parameter is where in the string the ellipsis should appear from 0 – 1, left to right. For example. a value of 1 will place the ellipsis at the right of the string, .5 in the middle, and 0 at the left.

    An optional forth parameter is the kind of ellipsis. By default, … will be inserted.

    Example:

    Produces:

    Typography Helper in codeigniter

    Typography Helper

    The Typography Helper file contains functions that help your format text in semantically relevant ways.

    Loading this Helper
    This helper is loaded using the following code:

    Available Functions
    The following functions are available:

    auto_typography($str[, $reduce_linebreaks = FALSE])

    Parameters:
  • $str (string) – Input string
  • $reduce_linebreaks (bool) – Whether to reduce multiple instances of double newlines to two
  • Returns:HTML-formatted typography-safe string
    Return type:string

    Formats text so that it is semantically and typographically correct HTML.
    This function is an alias for CI_Typography::auto_typography(). For more info, please see the Typography Library documentation.
    Usage example:

    Note! Typographic formatting can be processor intensive, particularly if you have a lot of content being formatted. If you choose to use this function you may want to consider caching your pages.

    nl2br_except_pre($str)

    Parameters:
  • $str (string) – Input string
  • Returns:String with HTML-formatted line breaks
    Return type:string

    Converts newlines to tags unless they appear within tags. This function is identical to the native PHP nl2br() function, except that it ignores tags.
    Usage example:


    entity_decode($str, $charset = NULL)

    Parameters:
  • $str (string) – Input string
  • $charset (string) – Character set
  • Returns:String with decoded HTML entities
    Return type:string

    This function is an alias for CI_Security::entity_decode(). Fore more info, please see the Security Library documentation.

    URL helper codeigniter

    URL Helper
    The URL Helper file contains functions that assist in working with URLs.
    Loading this Helper
    This helper is loaded using the following code:

    Available Functions
    The following functions are available:

    site_url([$uri = ”[, $protocol = NULL]])

    Parameters:
  • $uri (string) – URI string
  • $protocol (string) – Protocol, e.g. ‘http’ or ‘https’
  • Returns:Site URL
    Return type:string

    Returns your site URL, as specified in your config file. The index.php file (or whatever you have set as your site index_page in your config file) will be added to the URL, as will any URI segments you pass to the function, plus the url_suffix as set in your config file.

    You are encouraged to use this function any time you need to generate a local URL so that your pages become more portable in the event your URL changes.

    Segments can be optionally passed to the function as a string or an array. Here is a string example:

    The above example would return something like: http://example.com/index.php/news/local/123
    Here is an example of segments passed as an array:

    This function is an alias for CI_Config::site_url(). For more info, please see the Config Library documentation.

    base_url($uri = ”, $protocol = NULL)

    Parameters:
  • $uri (string) – URI string
  • $protocol (string) – Protocol, e.g. ‘http’ or ‘https’
  • Returns:Base URL
    Return type:string

    Returns your site base URL, as specified in your config file. Example:

    This function returns the same thing as site_url(), without the index_page or url_suffix being appended.
    Also like site_url(), you can supply segments as a string or an array. Here is a string example:

    The above example would return something like: http://example.com/blog/post/123

    This is useful because unlike site_url(), you can supply a string to a file, such as an image or stylesheet. For example:

    This would give you something like: http://example.com/images/icons/edit.png
    This function is an alias for CI_Config::base_url(). For more info, please see the Config Library documentation.

    current_url()

    Returns:The current URL
    Return type:string

    Returns the full URL (including segments) of the page being currently viewed.
    Note!Calling this function is the same as doing this: | | site_url(uri_string());

    uri_string()

    Returns:An URI string
    Return type:string

    Returns the URI segments of any page that contains this function. For example, if your URL was this:

    The function would return:

    This function is an alias for CI_Config::uri_string(). For more info, please see the Config Library documentation.

    index_page()

    Returns:‘index_page’ value
    Return type:mixed

    Returns your site index_page, as specified in your config file. Example:


    anchor($uri = ”, $title = ”, $attributes = ”)

    Parameters:
  • $uri (string) – URI string
  • $title (string) – Anchor title
  • $attributes (mixed) – HTML attributes
  • Returns:HTML hyperlink (anchor tag)
    Return type:string

    Creates a standard HTML anchor link based on your local site URL.
    The first parameter can contain any segments you wish appended to the URL. As with the site_url() function above, segments can be a string or an array.

    Note!If you are building links that are internal to your application do not include the base URL (http://…). This will be added automatically from the information specified in your config file. Include only the URI segments you wish appended to the URL.
    The second segment is the text you would like the link to say. If you leave it blank, the URL will be used.
    The third parameter can contain a list of attributes you would like added to the link. The attributes can be a simple string or an associative array.
    Here are some examples:

    anchor_popup($uri = ”, $title = ”, $attributes = FALSE)

    Parameters:
  • $uri (string) – URI string
  • $title (string) – Anchor title
  • $attributes (mixed) – HTML attributes
  • Returns:Pop-up hyperlink
    Return type:string

    Nearly identical to the anchor() function except that it opens the URL in a new window. You can specify JavaScript window attributes in the third parameter to control how the window is opened. If the third parameter is not set it will simply open a new window with your own browser settings.
    Here is an example with attributes:

    Note!The above attributes are the function defaults so you only need to set the ones that are different from what you need. If you want the function to use all of its defaults simply pass an empty array in the third parameter: | | echo anchor_popup(‘news/local/123’, ‘Click Me!’, array());
    Note!The window_name is not really an attribute, but an argument to the JavaScript window.open() method, which accepts either a window name or a window target.
    Note!Any other attribute than the listed above will be parsed as an HTML attribute to the anchor tag.
    mailto($email, $title = ”, $attributes = ”)

    Parameters:
  • $email (string) – E-mail address
  • $title (string) – Anchor title
  • $attributes (mixed) – HTML attributes
  • Returns:A “mail to” hyperlink
    Return type:string

    Creates a standard HTML e-mail link. Usage example:

    As with the anchor() tab above, you can set attributes using the third parameter:

    safe_mailto($email, $title = ”, $attributes = ”)

    Parameters:
  • $email (string) – E-mail address
  • $title (string) – Anchor title
  • $attributes (mixed) – HTML attributes
  • Returns:A spam-safe “mail to” hyperlink
    Return type:string

    Identical to the mailto() function except it writes an obfuscated version of the mailto tag using ordinal numbers written with JavaScript to help prevent the e-mail address from being harvested by spam bots.
    auto_link($str, $type = ‘both’, $popup = FALSE)

    Parameters:
  • $str (string) – Input string
  • $type (string) – Link type (‘email’, ‘url’ or ‘both’)
  • $popup (bool) – Whether to create popup links
  • Returns:Linkified string
    Return type:string

    Automatically turns URLs and e-mail addresses contained in a string into links. Example:

    The second parameter determines whether URLs and e-mails are converted or just one or the other. Default behavior is both if the parameter is not specified. E-mail links are encoded as safe_mailto() as shown above.
    Converts only URLs:

    Converts only e-mail addresses:

    The third parameter determines whether links are shown in a new window. The value can be TRUE or FALSE (boolean):

    url_title($str, $separator = ‘-‘, $lowercase = FALSE)

    Parameters:
  • $str (string) – Input string
  • $separator (string) – Word separator
  • $lowercase (bool) – Whether to transform the output string to lower-case
  • Returns:URL-formatted string
    Return type:string

    Takes a string as input and creates a human-friendly URL string. This is useful if, for example, you have a blog in which you’d like to use the title of your entries in the URL. Example:

    Note!Old usage of ‘dash’ and ‘underscore’ as the second parameter is DEPRECATED.
    The third parameter determines whether or not lowercase characters are forced. By default they are not. Options are boolean TRUE/FALSE.
    Example.

    prep_url($str = ”)

    Parameters:
  • $str (string) – URL string
  • Returns:Protocol-prefixed URL string
    Return type:string

    This function will add http:// in the event that a protocol prefix is missing from a URL.
    Pass the URL string to the function like this:

    redirect($uri = ”, $method = ‘auto’, $code = NULL)

    Parameters:
  • $uri (string) – URI string
  • $method (string) – Redirect method (‘auto’, ‘location’ or ‘refresh’)
  • $code (string) – HTTP Response code (usually 302 or 303)
  • Return type:void

    Does a “header redirect” to the URI specified. If you specify the full site URL that link will be built, but for local links simply providing the URI segments to the controller you want to direct to will create the link. The function will build the URL based on your config file values.

    The optional second parameter allows you to force a particular redirection method. The available methods are auto, location and refresh, with location being faster but less reliable on IIS servers. The default is auto, which will attempt to intelligently choose the method based on the server environment.

    The optional third parameter allows you to send a specific HTTP Response Code – this could be used for example to create 301 redirects for search engine purposes. The default Response Code is 302. The third parameter is only available with location redirects, and not refresh. Examples:

    Note!In order for this function to work it must be used before anything is outputted to the browser since it utilizes server headers.
    Note!For very fine grained control over headers, you should use the Output Library set_header() method.
    Note!To IIS users: if you hide the Server HTTP header, the auto method won’t detect IIS, in that case it is advised you explicitly use the refresh method.
    Note!When the location method is used, an HTTP status code of 303 will automatically be selected when the page is currently accessed via POST and HTTP/1.1 is used.
    Important!This function will terminate script execution.

    Self repeating countdown timer using javascript

    Timed events are fun and interactive for your users. People love performing in some type of competition, but there are many other reasons to show a JavaScript timer on your website. Regardless of the reasons, I am going to show you how to create a countdown timer using JavaScript and HTML. My primary caution for you is to understand JavaScript handled on the client side and has a dependency on the user’s computer speed. However, countdown timers are still effective for encouraging your users to quickly perform a particular task.

    This timer can be used as comming soon page for your website.

    This timer is for 8 hours, so when countdown to 0 it again starts to 8 hours. We are using simple Javascript Date function(UTC), some CSS for design.

    Below is the javascript used in the counter:

    Download Now

    XML helper codeigniter

    XML Helper
    The XML Helper file contains functions that assist in working with XML data.
    Loading this Helper
    This helper is loaded using the following code

    Available Functions
    The following functions are available:

    Parameters:
  • $str (string) – the text string to convert
  • $protect_all (bool) – Whether to protect all content that looks like a potential entity instead of just numbered entities, e.g. &foo;
  • Returns:XML-converted string
    Return type:string

    Takes a string as input and converts the following reserved XML characters to entities:
    1. Ampersands: &
    2. Less than and greater than characters: < >
    3. Single and double quotes: ‘ “
    4. Dashes: –

    This function ignores ampersands if they are part of existing numbered character entities, e.g. {. Example:

    Outputs: