3 Simple steps to speed up your CodeIgniter applications. HTML, Page Caching and Gzip.
We will not be covering the minifying the JS or/and CSS:
1. Compress HTML output
We will need to create a hook. This hook will remove any whitespace in the HTML output.
Go to system/application/config/config.php and enable hooks:
$config['enable_hooks'] = TRUE;
Code language: PHP (php)
Go to system/application/config/hooks.php and add the new hook:
$hook['display_override'][] = array(
'class' => '',
'function' => 'compress',
'filename' => 'compress.php',
'filepath' => 'hooks'
);
Code language: PHP (php)
Create the file system/application/hooks/compress.php and add the following code:
$CI =& get_instance();
$buffer = $CI->output->get_output();
$search = array(
'/\>[^\S ]+/s',
'/[^\S ]+\</s',
'/(\s)+/s', // shorten multiple whitespace sequences
'#(?://)?<!\[CDATA\[(.*?)(?://)?\]\]>#s' //leave CDATA alone
);
$replace = array(
'>',
'<',
'\\1',
"//<![CDATA[\n".'\1'."\n//]]>"
);
$buffer = preg_replace($search, $replace, $buffer);
$CI->output->set_output($buffer);
$CI->output->_display();
Code language: PHP (php)
2. Cache functions
You can cache certain functions in your controllers.
Add the following line and it will create a cached HTML of the page.
Make sure the Application/cache folder is writable.
$this->output->cache(60); // Will expire in 60 minutes
Code language: PHP (php)
More info http://codeigniter.com/user_guide/general/caching.html
3. Enable Gzip Compression
Go to application/config/config.php and enable the Gzip compression:
|-------------------------------------------------------------------------- | Output Compression |-------------------------------------------------------------------------- | | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could | even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not "echo" any values with compression enabled. | */ $config['compress_output'] = TRUE;
Thomas B. D.
Be careful with this! White-space may be styled to be significant or may have meaning to specific browsers where:
and
Does NOT render equally.
The best thing to do is simply to remove ^\s* and leave the rest alone. Even the “pros” haven’t found a right way of doing this without leaving some uncertainty about various scenarios regarding the significance of white-space.
Simply compressing with GZip should suffice these days.
eventsrecorder
hi
i try this but i get this error
Fatal error: Call to undefined function compress() in system/core/Hooks.php on line 236
Rick
Perhaps is the CodeIgniter version.
Ashish Mahana
you have to wrap the code for the file system/application/hooks/compress.php inside a function called compres()
See how i did this
function compress(){ $CI =& get_instance(); $buffer = $CI->output->get_output(); $search = array( '/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', // shorten multiple whitespace sequences '#(?://)?#s' //leave CDATA alone ); $replace = array( '>', '" ); $buffer = preg_replace($search, $replace, $buffer); $CI->output->set_output($buffer); $CI->output->_display(); }
yanirk
function compress() { ini_set("pcre.recursion_limit", "16777"); $CI =& get_instance(); $buffer = $CI->output->get_output(); $re = '%# Collapse whitespace everywhere but in blacklisted elements. (?> # Match all whitespans other than single space. [^\S ]\s* # Either one [\t\r\n\f\v] and zero or more ws, | \s{2,} # or two or more consecutive-any-whitespace. ) # Note: The remaining regex consumes no text at all... (?= # Ensure we are not in a blacklist tag. [^<]*+ # Either zero or more non-"<" {normal*} (?: # Begin {(special normal*)*} construct < # or a < starting a non-blacklist tag. (?!/?(?:textarea|pre|script)\b) [^<]*+ # more non-"<" {normal*} )*+ # Finish "unrolling-the-loop" (?: # Begin alternation group. textarea|pre|script)\b | \z # or end of file. ) # End alternation group. ) # If we made it here, we are not in a blacklist tag. %Six'; $new_buffer = preg_replace($re, " ", $buffer); // We are going to check if processing has working if ($new_buffer === null) { $new_buffer = $buffer; } $CI->output->set_output($new_buffer); $CI->output->_display(); }
Son
I am encountering this as well. Did you find the problem?
Son
Figured out the problem. You need to wrap the code for the hook inside a function called “compress()”;
Rick
Awesome, thanks for sharing Son π
Thor
It would be nice if CodeIgniter’s caching library was:
1. Mine-type aware,
2. Query-string aware (easy hack),
3. GZipped content before saving it to file, and then served the GZipped content to browsers that support decompression (99%?). Just a thought.
4. Served HTTP cache headers (also easy hack)
Dan
WARNING: I am sure this is due to something I did wrong but this completely F**ked up my entire site. Even restoring the changed files to their originals did not save it. If this works for you great but I really wish I hadnt bothered.
Rick
Hi Dan,
I’m sorry about that. All the tips in my post shouldn’t break your site.
Even if they do (yeah, it could happen) you’d be able to restore with a backup.
The output, the gzip or the cache can be turned off easily and without permanent effect!
Please let me know if you can figure out the issue.
Kind regards,
Rick
Shayan
Read this warning you must have use the echo in your controller which displays the blank pages specially inmac browsers:
VERY IMPORTANT: If you are getting a blank page when compression is enabled it
means you are prematurely outputting something to your browser. It could
even be a line of whitespace at the end of one of your scripts. For
compression to work, nothing can be sent before the output buffer is called
by the output class. Do not “echo” any values with compression enabled.
er
what fuck its not working its having error when take action undoo
mrj0909
I am getting this error after using this compression method
The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression.
Rick
Maybe you can try to got the index.php file and change error handling.
Try:
or
let me know if this helps.
Cheers.
mrj0909
what do you mean by “prematurely outputting”
Rick
It means you might have a space or something at the beggining of the code.
Also, it says you can not use the php echo function such as:
echo $my_var;
Mohammed
I cannot use echo function where exactly?
Thanks Rick!
Rick
Hi there Mohammed,
I don’t quite understand your problem. Isn’t the optimization working for you? Does it show any errors?
Rick
mrj0909
Again I am getting ” unsupported form of compression ” error
Anvar Ulugov
Nice tutorial, thank you!
Rick
You’re welcome Anvar!
IvanZ
Hello and thanks for these speedup suggestions.
I had however a problem rising with the hooks, the W3C validator throws a 500 error, while the website renders correctly on firefox/chrome/ie
For now I stick with Gzip and cleaned/minified css wich is sufficient I guess, even though i liked a lot the idea of compressing entire html source code
Rick
Yup, gzip should be enough to boost your site’s load π
IvanZ
btw: Gzip reduced by 70/80% the size, a lot of benefits for few clicks and key strokes π
Rick
w00t! π
Riyaz
HI
I have used your code but while every page getting load shows popup i can’t understand that
“Please configure the polyfill’s absolute(!) script path before referencing the css-filters-polyfill.js, like so:
var polyfilter_scriptpath = “/js/css-filters-polyfill/”;”
Anand
Nice Post,
But getting problem while enabling hooks all the ajax functionality has stopped .
Mahipal
Can i change in .htaccess file for page speed ? how to minify css and js file in codeigniter.
Rick
Yes you can.
If you control your own VPN take a look at the Mod PageSpeed for Apache or NGINX
https://developers.google.com/speed/pagespeed/module/
Haris Haide
I got these error ?
This site can't be reached
The webpage at http://localhost:8080/metropolitan09/Grid/usergrid might be temporarily down or it may have moved permanently to a new web address.
ERR_CONTENT_DECODING_FAILED
Nads
Not Working at all. A lot of bugs with this. when i did it its logged me in everywhere let suppose i logged in chrome browser and after that i hit any url to other browser or any other system its not asking to login.
Rick
Hello Nads,
The code is 7 years old, we have so assume CodeIgniter has changed since then. The code above will probably no longer be valid.
Best regards
Deepak
Do you intend to update the code for newer version? And what is your take on the first comment regarding meaningful whitespaces?
Rick
Hello Deepak,
No I do not intend to update the code I posted 7 years ago. I am no longer a PHP developer, I wouldn’t know how to do it π
Best of luck!
stefi
Can u help me how to Enable Gzip Compression on Codeigniter 4?
Ricard Torres
I’m afraid no, sorry. It has been many years since I last used CodeIgniter.
Good luck Stefi!
stefi
Thanks..
May i know what material are u interested now on web programming?
Ricard Torres
Sorry for the late response, I mainly focus on HTML, CSS and JavaScript. No backend languages.