Category Archives: Code Snippets

Here you will find various snippets and code examples that I have used to make some thing in my life a little easier to deal with.

Simple PHP function to convert hexadecimal colors to RGB (red, green, blue) decimal values

This function will convert hexadecimal colors with a length of 6, 3, 2, or 1 into their RGB decimal equivalents. If a value cannot be converted, it defaults to black…

function hex2rgb($hex = NULL) {
	preg_match('/^#{0,1}([0-9a-f]{1,6})$/i', $hex, $matches);
	if ($hex[0] == '#') $hex = substr($hex, 1);
	$length = @strlen($matches[1]);
	switch ($length) {
		case 6:
			$rgb = array($hex[0] . $hex[1], $hex[2] . $hex[3], $hex[4] . $hex[5]);
			break;
		case 3:
			$rgb = array($hex[0] . $hex[0], $hex[1] . $hex[1], $hex[2] . $hex[2]);
			break;
		case 2:
			$rgb = array($hex[0] . $hex[1], $hex[0] . $hex[1], $hex[0] . $hex[1]);
			break;
		default:
			$hex = ($length == 1) ? $hex . $hex : 0;
			$rgb = array($hex, $hex, $hex);
			break;
	}
	return array(
		'r' => hexdec($rgb[0]),
		'g' => hexdec($rgb[1]),
		'b' => hexdec($rgb[2])
	);
}

Short, simple and sweet 🙂

How-To: Reload verification image using Codeigniter 2 CAPTCHA helper

Out of the box, CodeIgniter has a good CAPTCHA helper to use in your web applications. Here is a simple example of how to get a new CAPTCHA image without having to reload the page 😉

Basic Controller

class Welcome extends CI_Controller {

    private $captcha_path = 'assets/img/captcha/';

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

    public function index()
    {
        $this->load->helper(array('captcha'));
        $captcha = create_captcha(array(
            'word'        => strtoupper(substr(md5(time()), 0, 6)),
            'img_path'    => $this->captcha_path,
            'img_url'    => $this->captcha_path
        ));
        $data = array(
            'captcha'        => $captcha
        );
        $this->session->set_userdata('captcha', $captcha['word']);
        $this->load->view('welcome', $data);
    }

}

The View (jQuery used for UI buttons and altering CAPTCHA image ‘src’ attribute)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/blitzer/jquery-ui.css">
<script>
$(function(){
    $('#new_captcha').button({
        text: false,
        icons: {
            primary: 'ui-icon-refresh'
        }
    }).click(function(event){
        event.preventDefault();
        $(this).prev().attr('src', 'welcome/new_captcha?'+Math.random());
    });
});
</script>
<?php echo $captcha['image']; ?>
<a href="#" id="new_captcha">Reload CAPTCHA</a>

Modified Controller Continue reading

Extending the CodeIgniter URI class to simplify pagination base_url option

In a lot of my controllers, I use pagination along with the HTML <base> tag’s href attribute for relative link URLs.

Example URL: http://www.domain.com/admin/users/index/pagination_offset

HTML Base tag: <base href=”http://www.domain.com/admin/”>

What this means, is I usually have to build pagination’s base_url option based on where I am and what information is being passed in the URI. A lot of times it ends up looking something like…

$this->load->library('pagination', array(
    'base_url'       => $this->uri->segment(2) . '/' . $this->uri->segment(3) . '/' . $this->uri->segment(4),
    'total_rows'     => $total_rows,
    'per_page'       => 20,
    'uri_segment'    => 4
));

What I decided to do what extend the core CodeIgniter URI class to provide a basic slice method to grab a chunk of the URI by applying PHP’s array_slice function to the segments property of the URI class. Continue reading

Use JavaScript (using jQuery) to add support for HTML5 placeholder attribute in form fields

Some browsers do not support the placeholder attribute added in HTML5. This attribute is useful for field hinting such as input formats for dates, phone numbers, and the like. If you see text in the field below, your browser supports placeholder, if not, add the code below to mimic the behavior 😉

Example field:

JavaScript (jQuery) workaround: Continue reading

Auto-claim Zynga Rewards (Everybody & Friends)

Here’s a little bookmarklet I wrote that you can add use automatically collect Zynga rewards while you’re playing games over at Zynga.com. It seems to work for all rewards regardless of which game you’re playing (though I primarily use it for CastleVille).

javascript:var classesPublic='zui_list_itemsContainer zui_zdc_gameboard_rts_rtsList_itemsContainer zui_zdc_gameboard_rts_rtsPublicList_itemsContainer';var classesNeighbors='zui_list_itemsContainer zui_zdc_gameboard_rts_rtsList_itemsContainer zui_zdc_gameboard_rts_rtsNeighborList_itemsContainer';var classesButtons='zui zui_button zui_enabled zui_button_enabled zui_zdc zui_button_zdc zui_zdc_enabled zui_button_zdc_enabled zui_button_tiny zui_button_white';var unclaimedRewardsNeighbors,unclaimedRewardsPublic;var unclaimedNeighborsInit=unclaimedPublicInit=true;function collectRewardsNeighbors(){for(unclaimedIndex=0;unclaimedIndex=1){if(unclaimedNeighborsInit){unclaimedNeighborsInit=false;collectRewardsNeighbors();}else{setTimeout('collectRewardsNeighbors()',1000);}}},false);var parentUnclaimedPublic=document.getElementsByClassName(classesPublic)[0];parentUnclaimedPublic.addEventListener('DOMSubtreeModified',function(){unclaimedRewardsPublic=parentUnclaimedPublic.getElementsByClassName(classesButtons);if(unclaimedRewardsPublic.length>=1){if(unclaimedPublicInit){unclaimedPublicInit=false;collectRewardsPublic();}else{setTimeout('collectRewardsPublic()',1000);}}},false);

What you need to do, is copy the code above and paste it into a new bookmark within your browser. Couldn’t be easier 🙂

Note: This script requires a browser that supports the DOMSubtreeModified – DOM Level 2 Mutation Event (eg: IE9, FF, Safari and Chrome)

jQuery UI replacement for javascript:confirm() links

Here is a nice confirmation handler to replace javascript:confim() links using jQuery UI…

$(function() {
    $('.ui-icon-trash').click(function(event){
        event.preventDefault();
        var targetUrl = $(this).attr('href');
        $('<div title="Confirmation Required"><p>Delete this record?</p></div>').dialog({
            autoOpen: true,
            modal: true,
            resizable: false,
            buttons: {
                Yes: function() {
                    window.location.href = targetUrl;
                },
                No: function() {
                    $(this).remove();
                }
            }
        });
    });
});

I use it for “delete” links (should be obvious) but it can be easily adjusted for any other type of confirmation.

Cheers!

Number Pad (NumLock On) ASCII ALT Key Character Codes

Just a quick reference list for numeric pad key sequences for typing ASCII characters not found on the keyboard.

All you have to do is turn NumLock on, hold the ALT key, type the desired number, then let go of the ALT key. Have fun 😀

ASCII Codes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
§
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
! # $ % & ( ) * + , . / 0
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
1 2 3 4 5 6 7 8 9 : ; < = > ? @
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
A B C D E F G H I J K L M N O P
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
Q R S T U V W X Y Z [ \ ] ^ _ `
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
a b c d e f g h i j k l m n o p
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
q r s t u v w x y z { | } ~ Ç
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
ü é â ä à å ç ê ë è ï î ì Ä Å É
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
æ Æ ô ö ò û ù ÿ Ö Ü ¢ £ ¥ ƒ á
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
í ó ú ñ Ñ ª º ¿ ¬ ½ ¼ ¡ « »
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
α
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
ß Γ π Σ σ µ τ Φ Θ Ω δ φ ε
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
± ÷ ° · ²
02222 0169 0153
® ©