Archive

Author Archive

gzdecode()

October 20th, 2011 No comments

It looks like with version 5.4 (currently in beta), PHP will include native gzdecode() function. Until now developers were writing their own implementation of this function and usually name it gzdecode(). Now when PHP has a native function, when you upgrade to 5.4 you will get an error: “Cannot redeclare gzdecode()“. If you get this error, find the file and the line number where this function is declared (this information should be in the error message) and surround the whole function with “if” statement:

1
2
3
4
5
if (! function_exists('gzdecode')) {
    function gzdecode($data) {
        // Your function code goes here
    }
}
Tags:

CodeIgniter JavaScript validation

March 2nd, 2011 5 comments

I use CodeIgniter’s Form Validation library for back-end and jQuery Validation plugin for front-end validation. For my latest project I decided to combine them and here’s what I got so far.

First things first – demo and source code.

jQuery Validation plugin has this handy remote() method, that basically sends AJAX request to back-end script with form field data. Response from back-end script is evaluated as JSON and must be true for valid fields. When string is returned, form field is treated as invalid and returned string is displayed as error message. This allows to return standard CI Form Validation error messages. The code below is an example of back-end script that can handle remote() method from jQuery Validation plugin. You would place this function as a method in your controller where form logic is handled.

public function remote()
{
	// Set JSON headers, no cache
	header('Cache-Control: no-cache, must-revalidate');
	header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
	header('Content-type: application/json');
 
	$field_name = key($_POST);
 
	// Load validation rules set in constructor
	$this->form_validation->set_rules($this->form_rules);
 
	// For JSON response, we don't want error delimiters
	$this->form_validation->set_error_delimiters('', '');
 
	// run_single() is a method extended from core validation library
	if ($this->form_validation->run_single($field_name) == FALSE)
	{
		$response = validation_errors();
	}
	else
	{
		$response = TRUE;
	}
 
	echo json_encode($response);
}

Notice CI Form Validation library is calling run_single() method. I extended base library to add this method, it work exactly the same as standard run() method, but checks only one field. You will need to copy/download my extended validation library to your /application/libraries/MY_Form_validation.php file. This extended library also has helper method called jquery_options() method, that generates JSON encoded string containing validation rules in a format acceptable to jQuery Validation plugin. You can write your own rules in your view file, but this definitely makes it easier.

Speaking of the view file, you will need jQuery and jQuery Validation plugin loaded. Both of them have CDNs, so you can load them like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js" type="text/javascript"></script>

When required JavaScript files are loaded, you need to call validate() method on your form selector and pass parameters as JSON string generated by jquery_options() method from my extended validation library. Here’s an example:

<script type="text/javascript">
	$(document).ready(function(){
		$('#signupform').validate(<?php echo $jquery_validation ?>);
	});
</script>

I uploaded the whole application folder to Bitbucket – here, but you only need these 3 files to see how t works:

/application/libraries/MY_Form_validation.php
/application/controllers/form.php
/application/views/form.php

Tags:

Password hashing class (phpass) converted to CodeIgniter library

June 4th, 2010 6 comments

Password hashing class phpass was suggested in /r/php/ so I decided to use it on one of my CodeIgniter applications. I changed a bit how constructor works to be able to load it as any other CodeIgniter library and modified it’s methods to be able to call them statically.

If you want to give it a try – download it and copy Hash.php to your /application/libraries directory.

 
In your controller, load the library:

1
$this->load->library('hash');

 
Now you can use static methods anywhere in your application – your auth library, users controller, etc.

 
For example, to hash a password you can do this:

1
$hash = Hash::HashPassword($this->input->post('password'));

 
To verify password:

1
2
3
4
if (Hash::CheckPassword($this->input->post('password'), $hash) !== TRUE)
{
	// Login failed
}

 
Hope you’ll find it useful.

Tags:

POP3/IMAP library for CodeIgniter

May 7th, 2010 7 comments

I was looking for POP3/IMAP library to read and delete emails from POP3/IMAP accounts but one I found on CodeIgniter forums was quite buggy. Fortunately I noticed this post on Reddit which featured Flourish PHP “unframework” and it’s fMailbox class.

I tried to run fMailbox class stand-alone and it worked quite well, so I decided to use it on my CodeIgniter application. I had to change how this class is initiated to use it as regular CodeIgniter library. Also in some places I had to replace Flourish exceptions with CodeIgniter’s error handling.

So, this is how you initiate library with just required parameters:

1
2
3
4
5
6
$config['type'] = 'imap';
$config['host'] = 'mail.example.com';
$config['username'] = 'info@example.com';
$config['password'] = 'letsplay';
 
$this->load->library('mailbox', $config);

More options are available:

1
2
3
4
5
6
7
8
9
$config['type'] = 'imap';
$config['host'] = 'mail.example.com';
$config['username'] = 'info@example.com';
$config['password'] = 'letsplay';
$config['port'] = 993;
$config['secure'] = TRUE;
$config['timeout'] = 5;
 
$this->load->library('mailbox', $config);

And this is how you call methods:

1
$messages = $this->mailbox->listMessages(10);

So it works basically as documented here, but you have to pass initial arguments as array. Hope someone will find it useful, here’s the download, just copy Mailbox.php to your “libraries” directory and you should be good to go.

Tags:

CodeIgniter’s forum member ranks

April 27th, 2010 No comments

Ever wondered what those member ranks in CodeIgniter’s forum were all about and how to get one? Well there’s a little back-story posted by Derek Jones from EllisLab, Inc. (creators of CodeIgniter).

[...] But our forum activity has increased so much in the past 1-2 years that there are now many people with over 1000 posts, and some above 2500, 5000, 10000, etc.  It seemed time to add some new ranks in to accommodate the upper tiers, but the current names bore me.  They should be fun, but not goofy, and should work well for both ExpressionEngine and CodeIgniter users, and other communities we might have as EllisLab creates them.  Hence, the lab metaphor.



And here is a full table of member ranks on CodeIgniter’s forums:

0 Summer Student
30 Grad Student
100 Lab Assistant
300 Research Assistant
1000 Lab Technician
2500 Sr. Research Associate
5000 Research Scientist
10000 ?????
Tags:

Check if hour falls between two hours

March 15th, 2009 No comments

Part of the program I’m writing had to check if given hour falls between two hours, for example, if 1 pm is between 5 am – 5 pm, or 11 pm is between 9 pm – 9 am. I couldn’t find snippet on the net so I wrote my own function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * Checks if given hour is between two hours (in 24 hour format)
 * if $hour is not specified it defaults to current hour
 * 
 * @return bool 
 * @param integer $start
 * @param integer $end
 * @param integer $hour[optional] 
 */
function is_between_hours($start, $end, $hour = NULL)
{
	$hour = (is_null($hour)) ? date('G') : $hour;
 
	if ($start == $end) return TRUE;
 
	if ($start > $end) return (($hour < $start) && ($hour > $end)) ? FALSE : TRUE;
 
	else return (($hour >= $start) && ($hour <= $end)) ? TRUE : FALSE;
}

If you know better way of doing it or have a question – please leave a comment.

Tags:

SitePoint forums switched to nofollow

March 14th, 2009 7 comments

Just noticed this morning that my SitePoint Forum posts have rel=”nofollow” attribute added to signature links. Not cool. I always thought SitePoint was dofollow forum. After a little digging I found this post: Fluff posting on the forum. Apparently change was made on Nov 17th 2008 and SitePoint now requires at least 100 posts to have signature links without rel=”nofollow” attribute.

Tags: ,

Moving WordPress to another directory

March 12th, 2009 No comments

Yesterday I had to move WordPress directory for a client (don’t ask why). After following basic instructions outlined in Codex Moving WordPress page I had only one problem left – missing images in blog posts. In database they are saved using full path and were pointing to the old directory.

I came up with following query to fix the problem:

UPDATE wp_posts 
SET guid = replace(guid, 'http://website.com/dir1/', 'http://website.com/dir2/')
WHERE post_type = 'attachment'

It looks in your wp_posts table and and replaces paths to uploaded files, in this case case – from “http://website.com/dir1/” to “http://website.com/dir2/”.

Use at your own risk!

Tags: ,