Archive for the ‘CodeIgniter’ Category

CodeIgniter 1.7: The URI you submitted has disallowed characters.

on Tuesday 14th July, 2009 Gabe speculated thusly…

I was getting the above error from CodeIgniter after urlencoding some base64 encoded binary data and passing it as a URI parameter to CodeIgniter. I looked in the config.php file and found that percent signs were allowed here:
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';

After some hunting around I found that CodeIgniter is not accepting this in the URI because the actual characters (that are encoded) fall outside the ASCII range. CodeIgniter is actually decoding the characters before testing them. The fix was quite simple, open up libraries/URI.php and go to line 189 where it says:
if ( ! preg_match("|^[".preg_quote($this->config->item('permitted_uri_chars'))."]+$|i", $str))
and change it to:

if ( ! preg_match("|^[".preg_quote($this->config->item('permitted_uri_chars'))."]+$|i", rawurlencode($str)))

Basically wrapping $str in the urlencode() function.

Posted in CodeIgniter, Development, Frameworks, Information, Programming

5 Comments »

An alternative img() helper function for CodeIgniter

on Wednesday 20th May, 2009 Gabe speculated thusly…

It is my opinion that CodeIgniter’s default img() function that comes in the HTML Helper could have been easier to use. As it is if you want to give your image a name css class you have to define an array consisting of these attributes.

That takes up space and makes the code less readable for non-PHP programmers. Since I work closely with a web designer who is good with HTML but gets lost in PHP I want to leverage the pragmatic power of PHP to automate repetitive tasks (like typing out an entire HTML image tag), but at the same time the result needs to be obvious to a non-programmer but also shorter than the HTML equivalent. I feel the img() helper in CodeIgniter falls short of both these requirements.

CodeIgniter’s img() helper also takes a second parameter, a boolean, this decides whether the index.php file is included in the image path, good if you are using a media controller. For 99.9% of my sites I don’t need these. Therefore I wrote my own helper.

The file is called MY_html_helper.php and lives inside the folder system/application/helpers. As with other extensions to the CI core the prefix MY_ is determined in your config file, so change MY_ to whatever it should be. Add the following code to the file:

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

function img($imgName, $attrs=FALSE)
{
	$CI =& get_instance();

	if (strpos($imgName, 'http') === 0) return;

	$imgPath = $CI->config->item('base_url');

	if ( ! $imgDir = $CI->config->item('image_dir')) $imgDir = 'assets/images/';

	$img = $imgPath.$imgDir.$imgName;

	$str = '<img src="'.$img.'" ';

	if ($attrs) $str .= $attrs." ";

	$str .= "/>";

	return $str;
}

All you have to make sure you do is load the html helper: $this->load->helper('html'); in your controller,
or put it in the array of helpers in system/application/config/autoload.php.

The helper assumes images live in the folder assets/images which lives alongside the system folder. If this is not where you put your images then you can specify an alternative directory in your config.php file. Simply add a line that looks like this to config.php: $config['image_dir'] = 'alternative/path/images/';. Don’t forget the trailing slash at the end. This alternative folder would live at the very top level of your application, alongside index.php.

Using the helper is easy and straightforward: <?=img('example.gif')?>

Will produce <img src="http://mysite.com/assets/images/example.gif" />.

Any additional attributes you want in the html tag can be written as per usual as the second parameter. For example if you want to give the image an alt attribute and class:
<?=img('example.gif', 'class="myclass" alt="Example Image"')?>

Will produce:

<img src="http://mysite.com/assets/images/example.gif" class="myclass" alt="Example Image" />

The only hard part about this is making sure you get the single and double quotes correct in the second parameter.

Cheers

Posted in CodeIgniter, Development, Frameworks, Information, Linux, Operating System, Programming, Server

1 Comment »

Making CodeIgniter’s Profiler AJAX compatible

on Tuesday 13th January, 2009 Gabe speculated thusly…

Modern web applications almost all make use of AJAX to enhance their user appeal. However, AJAX can be hard to debug, especially when all the traditional tools do little to help. When doing standard PHP coding CodeIgniter (CI) offers a profiler which will be appended to the bottom of generated pages. This gives you information on the request that was recently processed, including any POST or GET values passed to the script, how long execution took and how long any SQL queries took as well as what those queries actually were. During development I find this information indispensable to make sure my SQL queries are correct and things are working as I want.

However, when coding up AJAX aspects of the application this doesn’t work very well, any page fragments fed back to the JavaScript will have the profiler stuck at the bottom, and since these fragments are usually inserted inside DIVs the profiler cannot be read in it’s entirety, or it breaks the layout, or more likely, both of the above. Therefore I set out to find a way of making it AJAX compatible, so that it would always end up at the bottom of the page, even when it was originally returned appended to a page fragment. In the end this turned out easier than anticipated.

One small change needs to be made to your footer, you need to create an empty div with an ID of “debug”, this div will hold the profiler, so place the div where you want the profiler. The advantage with this is that you cannot see it when it is empty so it could even be left in for production code. The div looks like this:
<div id="debug"></div>

Now we need to extend, or rather override the CI profiler so create the file system/application/libraries/MY_Profiler.php

Replace MY_ with the value of $config['subclass_prefix'] found in your config file, by default it is MY_.

Next paste the following code in to it. Remember to change the name of the class as dictated by the filename you use, also change the name of the constructor function too. You can also change the script line to load the jQuery library from one of your servers, or even rewrite the entire script section to use any JavaScript you like.

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Profiler extends CI_Profiler
{
    function MY_profiler()
    {
        parent::CI_Profiler();
    }

    function run()
    {
            $output = <<<ENDJS
<script src="http://code.jquery.com/jquery-latest.js" />
<script type="text/javascript" language="javascript" charset="utf-8">
// < ![CDATA[
    $(document).ready(function() {
        var html = $('#codeigniter_profiler').clone();
        $('#codeigniter_profiler').remove();
        $('#debug').hide().empty().append(html).fadeIn('slow');
    });
// ]]>
</script>
ENDJS;
            $output .= "<div id='codeigniter_profiler' style='font-size: 0.7em; clear:both;background-color:#fff;padding:10px;'>";
            $output .= $this->_compile_uri_string();
            $output .= $this->_compile_controller_info();
            $output .= $this->_compile_memory_usage();
            $output .= $this->_compile_benchmarks();
            $output .= $this->_compile_get();
            $output .= $this->_compile_post();
            $output .= $this->_compile_queries();
            $output .= '</div>';
            return $output;
    }
}

If you have already loaded a jQuery library in your header somewhere then make sure this ajax fragment doesn’t load jQuery again – otherwise all your event bindings and everything else will fail. If this is the case simply remove the line:

<script src="http://code.jquery.com/jquery-latest.js" />

From the above code.

That should be it, hit me back if you have any feedback, questions, or need some help.

Posted in CodeIgniter, Development, Frameworks, Operating System, PHP, Programming

2 Comments »

HTML Helper for generating a country drop-down list in CodeIgniter

on Friday 9th May, 2008 Gabe speculated thusly…

Frustrated at having to create my own drop-down country lists in CI I created a helper for it. It can even work with the CI Validation class, so if the form is submitted and fails validation when it is redisplayed the same country is selected as the form was submitted with.

Download the file MY_form_helper.php and put it in the folder: /system/application/helpers/.

Download the file countries.php and place that in /system/application/config/.

You will now be able to create drop-down lists of countries in your views like this:
< ?=form_countries( 'country', $this->validation->country, array( 'style' => 'width: 250px' ) )?>

Ensure that you create a validation rule called “country” in your controller and that you are loading the form helper.

form_countries() takes three arguments. The first is the name you would like to give the select box, this is required. The second is the country to select by default – this could be something like ‘GB’, or $this->validation->country, otherwise you can leave it blank. The third argument is any additional properties to give the select box, you can leave this blank, or pass an array. In the example above we also set the width to 250x. The country chosen by the user will be returned to the script as a two-letter ISO country code, if you are validating this then you can set the min and max length values as 2, and accept alphabetical characters only. If using MySQL as your database you will get best performance by creating a column of the type char with a length of 2.

Posted in CodeIgniter, Development, Frameworks, PHP, Programming

4 Comments »

Profiling in CodeIgniter

on Tuesday 6th May, 2008 Gabe speculated thusly…

Profiling an application is a great way to see how it is performing. CodeIgniter comes with a profiling class, which you can make calls to from your controllers. However, during development I find profiling so helpful that I want it on all my pages, without having to specifically call it each time. I also want to be able to deploy my development site to a production server – making calls to the profiler throughout the controllers means I would need to edit each and every controller to make sure the profiler wasn’t active on the live server.

After much searching I discovered a better solution. This allows you to add profiling to the bottom of every page (along with its debug info and SQL query info). When you copy the dev site live you just exclude 1 file, and profiling will be removed totally. All you need to do is create a file called MY_Output.php in system/application/libraries that extends the Output core class, with the following contents:

< ?php
# /system/application/libraries/MY_Output.php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Output extends CI_Output {
function __construct() {
parent::__construct();
$this->enable_profiler( TRUE );
}
}
?>

This will enable profiling output on all your pages for development and debug purposes. When you copy your site to a production server just make sure you don’t copy MY_Output.php file. I normally use rsync for copying live and just add: --exclude="MY_Output.php" to the rsync command.

The condition to using the name MY_Output.php is that you left the variable $config['subclass_prefix'] in config.php as default. This defaults to $config['subclass_prefix'] = 'MY_';, so if you change it you will need to alter the filename of your new class.

Posted in CodeIgniter, Development, Frameworks, HowTo, PHP, Programming

No Comments »

Protected: CodeIgniter for Rapid PHP Application development

on Thursday 6th March, 2008 Gabe speculated thusly…

This post is password protected. To view it please enter your password below:


Posted in Books, CodeIgniter, Frameworks, Information, PHP, Programming

Enter your password to view comments

Linking images in Code Igniter

on Sunday 17th February, 2008 Gabe speculated thusly…

I’m a big fan of the PHP framework, CodeIgniter. However, until recently it has lacked an elegant way of nesting an image in an anchor tag. I had to resort to manually typing out HTML like this:
<a href="<?=site_url?>/controller/action"><img src="<?=base_url()?>/images/button.gif"></a>
CodeIgniter 1.6 has been released, quickly followed by 1.6.1. This includes an image helper. One is still unable to elegantly link images using CI’s helpers. If you want to be able to do something like this:
<?= anchor( 'controller/action', img( 'images/button.gif' )?>

You could just comment out line 117 in /system/helpers/url_helper.php but that means you are altering CI core, which is not a good idea. For a start it will be overwritten when you upgrade and it is an inelegant hack.

A better bet is to create your own helper file and use it to override CodeIgniter’s one. This is dead-simple, just create a file called MY_url_helper.php in the following location /system/application/helpers/. Note that the MY_ prefix is set in the config.php file under $config['subclass_prefix'] = 'MY_'; so if you have changed that setting you will need to adjust your file-name accordingly.

Then just copy and paste the following in to it: (more…)

Posted in CodeIgniter, Development, Frameworks, PHP, Programming

7 Comments »