CodeIgniter Cart class product name restrictions

codeigniter logo

The CodeIgniter cart class has a non immediately apparent feature regarding special characters in the Product Name. Within the Cart library the line

var $product_name_rules = ‘\.\:\-_ a-z0-9’; // alpha-numeric, dashes, underscores, colons or periods

will strip out any non defined special characters. While you could hack this line, the correct way to do this is to extend the library and create an over-ride.

Create a new file application/libraries/MY_Cart.php

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

class MY_Cart extends CI_Cart {

function __construct() {
parent::__construct();

// Remove limitations in product names
$this->product_name_rules = ‘\d\D’;
}
}

Note this will allow all characters, you may want to limit to specified special characters.

CodeIgniter routes and .htaccess

CodeIgniter has a robust routing module as part of its MVC architecture. A trap for the inexperienced arises when the default controller works (e.g. site.com) but anything else such as mysite.com/dashboard goes to a server based 404, not the CodeIgniter one.

Solution: in your config.php file ensure this line is present

$config[‘index_page’] = ”;

and place the following code in an .htacess file

Options -Indexes
Options +FollowSymLinks

# Set the default file for indexes
DirectoryIndex index.php

<IfModule mod_rewrite.c>

# activate URL rewriting
RewriteEngine on

# do not rewrite links to the documentation, assets and public files (your folders here)
RewriteCond $1 !^(images|assets|uploads|js)

# do not rewrite for php files in the document root, robots.txt or the maintenance page etc
RewriteCond $1 !^([^\..]+\.php|robots\.txt|maintenance\.html)

# rewrite everything else
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>

# If we don’t have mod_rewrite installed, all 404’s can be sent to index.php, and everything works as normal.

ErrorDocument 404 index.php

</IfModule>

Speeding up PHP FOR loops

Refactoring some client code the other day I found a lot of inefficient logic. Whilst this example is written in PHP the concept is applicable in other programming languages.

Many people use for loops in the belief that they are faster than a foreach, and while this is often the case it can be slower and less flexible if you make some simple mistakes. Consider the following:

A slow FOR loop

$text=”thequickbrownfoxjumpsoverthelazydog”;
for($i=0; $i < strlen($text); $i++){ // Loop through the characters
echo ( substr($text,$i,1) == ‘o’ ) ? “Its an o” : “Not an o”; // Display true or false as relevant
}

A faster FOR loop

$text=”thequickbrownfoxjumpsoverthelazydog”;
$length = strlen($text); // obtain length of the string
for($i=0; $i < $length ; $i++){ // Loop through the characters
echo ( substr($text,$i,1) == ‘o’ ) ? “Its an o” : “Not an o”; // Display true or false as relevant
}

The second loop is faster because it does not evaluate the string length each time the loop runs strlen($text) as in the first example. Small differences like this can have a large effect on the speed of scripts especially if there are many loops or iterations.

08/02/2012 Emergency PHP Updates on server

EMERGENCY PHP UPDATES

We will be applying a PHP update to the servers later this evening.

This will take the primary PHP install from v5.3.9 to v5.3.10 and will resolve a vulnerability that has been patched in the 5.3.10 release.

The vulnerability present in 5.3.9 allows for the possibility of remote code execution depending on how large numbers and arrays are used.

As this is a security issue we will be performing emergency maintenance between midnight and 3am (GMT).

There should be no interruption to service however, as the work is being done on components critical to PHP based sites, this period should be considered at risk.

The work will cause slightly higher than normal load on the servers and may involve a restart of the web server.

In the worst cast scenario (such as a failed compile) the installer will restore a backup of the current working configuration.

No module or configuration changes will be made to the PHP stack and scripts should notice no difference.

You can view the change log on the php.net site: http://php.net/ChangeLog-5.php

Obtain Facebook likes via PHP SDK

In an update to this post here is another way to obtain the number of likes for a Facebook page.

I’ll assume that you’ve already registered a Facebook application, have downloaded the PHP SDK and have included for use in your code.

require(‘facebook.php’);

Setup an array with your Facebook applications credentials

$facebook = new Facebook(array(
‘appId’ => ‘000000000’, // Put appID here
‘secret’ => ‘0000c000c000c000c’, // Put your secret key here
));

Decide which page you wish to obtain the number of likes for

$getRequest = $facebook->api(‘/cocacola’); // Lets look at the Facebook page for the popular soft drink
echo $getRequests[‘likes’];

Obviously you can consume, contrast and display this information in more exciting ways than simply echoing it to the screen. Enjoy.

Use PHP to display Gravatar images

All URLs on Gravatar are based on the use of the hashed value of an email address. According to their best practice you should:

  1. Trim leading and trailing whitespace from an email address
  2. Force all characters to lower-case
  3. md5 hash the final string

Of course in PHP this is trivial as the following function shows:

function fetchGravatar() {
$fetchHash = md5(strtolower(trim(‘your_email.address.com’)));
$GravatarImage = ‘http://www.gravatar.com/avatar/’ . $fetchHash;
return $GravatarImage;
}

Profiles are also available if you require them.

PHP Host Settings Without phpinfo()

Occasionally a webhost will block the very useful phpinfo() command making it difficult to understand any limitations of the server configuration. This script can display relevant information to help you understand what is happening behind the scenes.

<?php
$d_func = ini_get(“disable_functions”);
$up_max = ini_get(“upload_max_filesize”);
$up_max = str_replace(“M”,””,$up_max);
$up_max_size = “Megabytes”;
$post_max = ini_get(“post_max_size”);
$post_max = str_replace(“M”,””,$post_max);
$post_max_size = “Megabytes”;
$input_max = ini_get(“max_input_time”);
$mem_limit = ini_get(“memory_limit”);
$mem_limit = str_replace(“M”,””,$mem_limit);
$mem_limit_size = “Megabytes”;
$exec_time = ini_get(“max_execution_time”);
$safe_mode = ini_get(“safe_mode”);

if(!is_null($d_func) && $d_func !== “”){echo “Disabled Functions: \n $d_func”;}
if(!is_null($safe_mode) && $safe_mode !== “”){echo “<span style=’color:red;’>Safe Mode is Active</span> <br>”;}
if($up_max >= 1001){$up_max = $up_max / 1024; $up_max_size = “Gigabytes”;
if($up_max >= 10001){$up_max = $up_max / 1024; $up_max_size = “Terabytes”;}}
if($post_max >= 1001){$post_max = $post_max / 1024; $post_max_size = “Gigabytes”;
if($post_max >= 10001){$post_max = $post_max / 1024;$post_max_size = “Terabytes”;}}
if (min($input_max,60)){$input_max = $input_max /60;}
if (min($exec_time,60)){$exec_time = $exec_time /60;}
if($mem_limit >= 1001){$mem_limit = $mem_limit / 1024; $mem_limit_size = “Gigabytes”;}

echo “Maximum Upload Size = $up_max $up_max_size<br>”;
echo “Maximum Post Size = $post_max $post_max_size <br>”;
echo “Maximum Input Time = $input_max minute/s<br>”;
echo “Memory Limit = $mem_limit $mem_limit_size<br>”;
echo “Maximum Execution Time = $exec_time minute/s<br>”;
?>

PHP Modulo Operator For Alternating Rows

Alternating row colours within a grid of data can make for a more pleasant viewing experience and has become a popular styling method in recent times. I was a little incredulous at some code I saw recently to determine alternating rows so without further introduction, meet the Modulo operator which is a quick and easy way to get up and running:

for($i=0;$i<10;$i++){ if($i % 2){ // This is an even row }else{ // This is an odd row } }

I’m sure you will be able to apply this to your own css or styling within your loops.