Archive for the ‘Frameworks’ 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 »

Apache Virtual Hosts on OS X Leopard

on Sunday 31st May, 2009 Gabe speculated thusly…

If you develop multiple sites and you need virtual hosting functionality, scroll down to the end of the /private/etc/apache2/httpd.conf file and uncomment the following:

# Include /private/etc/apache2/extra/httpd-vhosts.conf

Next, you’ll need to setup whatever virtual hosts you have in the virtual hosts file /private/etc/apache2/extra/httpd-vhosts.conf

You need to make an entry in the httpd-vhosts.conf file like so:

<virtualhost *:80>
   ServerName beta-site-1.com
   ServerAlias www.beta-site-1.com
   ServerAdmin webmaster@beta-site-1.com
   ErrorLog "/private/var/log/apache2/dummy-host2.example.com-error_log"
   CustomLog "/private/var/log/apache2/dummy-host2.example.com-access_log" common

   DocumentRoot "/Library/WebServer/beta-site-1"
   ScriptAlias /cgi-bin/ "/Library/WebServer/beta-site-1/cgi-bin"
   
     Options FollowSymLinks MultiViews Includes
     AllowOverride All
     Order allow,deny
     Allow from all
   
</virtualhost>

The examples provided by Apple in the vhosts file are slightly incorrect and if you use the CustomLog lines as is you will get errors the following errors if you run: apachectl -t -D DUMP_VHOSTS:
Syntax error on line 40 of /private/etc/apache2/extra/httpd-vhosts.conf:
CustomLog takes two or three arguments, a file name, a custom log format string or format name, and an optional "env=" clause (see docs)

This is because
CustomLog "/private/var/log/apache2/dummy-host.example.com-access_log common

Should actually read:
CustomLog "/private/var/log/apache2/dummy-host.example.com-access_log" common

Posted in Development, Frameworks, HowTo, Information, Leopard, Linux, OS X, Operating System, PHP, Server, Ubuntu

2 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 »

Starting with Symfony – Internal Server Error

on Tuesday 13th January, 2009 Gabe speculated thusly…

You will get an internal server error unless you set:
magic_quotes_gpc = Off
in your php.ini file.

Posted in Frameworks, Programming, Uncategorized

No Comments »

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 »

Using Python Doctests in Django with fixtures

on Tuesday 24th June, 2008 Gabe speculated thusly…

Django is a pretty decent web framework for Python. Having brushed up on my Python programming I started to fall in love with doctests. I then went ahead and wrote about 100 lines of doctest for model in Django, then found all tests were failing because the database fixtures weren’t being loaded.

I couldn’t find out how to install fixtures inside doctests from the official documentation, I did however, come across what seemed like a web page written in Japanese. I had to skip the Japanese but figured out the code samples. Getting fixtures working with doctests in django is fairly simple – once you know how!

At the top of your doctest you will need the following two lines:
>>> from django.core import management
>>> management.call_command("loaddata", "project/fixtures/test.json", \
verbosity=0)

Replace project and test.json with your project name and fixture. Then continue with the doctests as per usual. After they are done put the following line at the end of the doctest:
>>> management.call_command("flush", verbosity=0, interactive=False)

That should be just about it :)

Posted in Development, Django, Frameworks, Programming, Python

No 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: Ruby on Rails for PHP and Java Developers

on Thursday 6th March, 2008 Gabe speculated thusly…

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


Posted in Books, Frameworks, Information, Ruby on Rails

Enter your password to view 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