Categories
Free PHP Classes & Library PHP Tips & Tutorials

Convert Object to Array in PHP

There are quite a few ways to do this and each of them has its strengths and weaknesses. Find out if one suits your needs by trying one of the approaches below.

Casting with (array)

$array = (array) $obj;

Problem is this doesn’t convert complex / multi-dimensional objects well.

get_object_vars()

$array = get_object_vars( $obj );

$array would then be an array of properties and values from $obj that are accessible in the current scope.

Custom function for complex objects

function objectToArray( $object )
    {
        if( !is_object( $object ) && !is_array( $object ) )
        {
            return $object;
        }
        if( is_object( $object ) )
        {
            $object = get_object_vars( $object );
        }
        return array_map( 'objectToArray', $object );
    }

$array = objectToArray( $obj );

This function is conjured by PHPRO.ORG.

JSON – json_encode(), json_decode()

$json  = json_encode($object);
$array = json_decode($json, true);

This is probably the coolest approach delivered by Andy.

Categories
.htaccess Tutorials & Tips Free PHP Classes & Library Information Security PHP Tips & Tutorials

PHP Class for Handling .htpasswd and .htgroup (Member Login & User Management)

Apache is a marvelous web server that offers .htpasswd and .htgroup for controlling restricted access to your website. By help of .htaccess, they work as a member login & user management system that is so simple and easy to deploy. You can even define user groups / roles with it.

Basically,

  • .htpasswd defines pairs of username & password that are user accounts.
  • .htgroup defines groups / roles of user accounts that can be access-controlled as a whole.
  • .htaccess then applies .htpasswd and .htgroup to the current directory, and specifies which groups in .htgroup has access to the current directory.

For example, we have

/home/myuser/.htpasswd

user1:{SHA}kGPaD671VNU0OU5lqLiN/h6Q6ac=
user2:{SHA}npMqPEX3kPQTo+x/+ZckHDrIcQI=
user3:{SHA}q1Fh2LTUjjkncp11m0M9WUH5Zrw=

/home/myuser/.htgroup

admin: user2
editor: user1 user3
writer: user3

/home/myuser/public_html/example.com/member/.htaccess

AuthName "Members Area"
AuthType Basic
AuthUserFile /home/myuser/.htpasswd
AuthGroupFile /home/myuser/.htgroup
<Limit GET POST>
require group admin
require group writer
</Limit>

What they do is only let users in the admin and writer group, that is user2 and user3, to access example.com/member. When someone tries to access example.com/member, Apache would prompt him or her for user name and password, and he or she must be either user2 or user3 to access it – they must enter the correct password set out in .htpasswd for user2 or user3.

user1 isn’t allowed to access example.com/member even if the password is correct. You get the idea.

You can place .htaccess anywhere in your website, and it will control access to the directory it’s in by the defined rules (which groups / roles are allowed to access). Just make sure it is pointing to the right .htpasswd and .htgroup by AuthUserFile and AuthGroupFile.

And you can have multiple .htaccess in different directories of your website, using the same .htpasswd and .htgroup.

This is so simple yet so very handy in creating & managing different users and user roles (.htpasswd, .htgroup) and giving them permissions (.htaccess) in accessing different website assets.

PHP Class

Now that you are familiar with the basic authentication and native user management system in Apache, you can use this two simple PHP classes to automate tasks such as user creation, user deletion, adding user to group, and removing user from group.

class Htpasswd

class Htpasswd {
	
	private $file = '';
	private $salt = 'AynlJ2H.74VEfI^BZElc-Vb6G0ezE9a55-Wj';
	
	private function write($pairs = array()) {
		$str = '';
		foreach ($pairs as $username => $password) {
			$str .= "$username:{SHA}$password\n";
		}
		file_put_contents($this -> file, $str);
	}
	
	private function read() {
		$pairs = array();
		$fh = fopen($this -> file, 'r');
		while (!feof($fh)) {
			$pair_str = str_replace("\n", '', fgets($fh));
			$pair_array = explode(':{SHA}', $pair_str);
			if (count($pair_array) == 2) {
				$pairs[$pair_array[0]] = $pair_array[1];
			}
		}
		return $pairs;
	}
	
	private function getHash($clear_password = '') {
		if (!empty($clear_password)) {
			return base64_encode(sha1($clear_password, true));
		} else {
			return false;
		}
	}
	
	public function __construct($file) {
		if (file_exists($file)) {
			$this -> file = $file;
		} else {
			die($file." doesn't exist.");
			return false;
		}
	}

	public function getUsers() {
		return $this -> read();
	}
	
	public function addUser($username = '', $clear_password = '') {
		if (!empty($username) && !empty($clear_password)) {
			$all = $this -> read();
			if (!array_key_exists($username, $all)) {
				$all[$username] = $this -> getHash($clear_password);
				$this -> write($all);
			}
		} else {
			return false;
		}
	}
	
	public function deleteUser($username = '') {
		$all = $this -> read();
		if (array_key_exists($username, $all)) {
			unset($all[$username]);
			$this -> write($all);
		} else {
			return false;
		}
	}
	
	public function doesUserExist($username = '') {
		$all = $this -> read();
		if (array_key_exists($username, $all)) {
			return true;
		} else {
			return false;
		}
	}
	
	public function getClearPassword($username) {
		return strtolower(substr(sha1($username.$this -> salt), 4, 12));
	}
	
}

class Htgroup

class Htgroup {
	
	private $file = '';
	
	private function write($groups = array()) {
		$str = '';
		foreach ($groups as $group => $users) {
			$users_str = '';
			foreach ($users as $user) {
				if (!empty($users_str)) {
					$users_str .= ' ';
				}
				$users_str .= $user;
			}
			$str .= "$group: $users_str\n";
		}
		file_put_contents($this -> file, $str);
	}
	
	private function read() {
		$groups = array();
		$groups_str = file($this -> file, FILE_IGNORE_NEW_LINES);
		foreach ($groups_str as $group_str) {
			if (!empty($group_str)) {
				$group_str_array = explode(': ', $group_str);
				if (count($group_str_array) == 2) {
					$users_array = explode(' ', $group_str_array[1]);
					$groups[$group_str_array[0]] = $users_array;
				}
			}
		}
		return $groups;
	}
	
	public function __construct($file) {
		if (file_exists($file)) {
			$this -> file = $file;
		} else {
			die($file." doesn't exist.");
			return false;
		}
	}

	public function getGroups() {
		return $this -> read();
	}
	
	public function addUserToGroup($username = '', $group = '') {
		if (!empty($username) && !empty($group)) {
			$all = $this -> read();
			if (isset($all[$group])) {
				if (!in_array($username, $all[$group])) {
					$all[$group][] = $username;
				}
			} else {
				$all[$group][] = $username;
			}
			$this -> write($all);
		} else {
			return false;
		}
	}
	
	public function deleteUserFromGroup($username = '', $group = '') {
		$all = $this -> read();
		if (array_key_exists($group, $all)) {
			$user_index = array_search($username, $all[$group]);
			if ($user_index !== false) {
				unset($all[$group][$user_index]);
				if (count($all[$group]) == 0) {
					unset($all[$group]);
				}
				$this -> write($all);
			}
		} else {
			return false;
		}
	}

	public function getGroupsByUser($username = '') {
		$all = $this -> read();
		$user_groups = array();
		foreach ($all as $group => $users) {
			if (in_array($username, $users)) {
				$user_groups[] = $group;
			}
		}
		return $user_groups;
	}

}

Usage

First, you should use your own $salt. Change the value of $salt in the Htpasswd class to something else for your own application.

To instantiate the classes:

$passwdHandler = new Htpasswd('/home/myuser/.htpasswd');
$groupHandler = new Htgroup('/home/myuser/.htgroup');

To create and delete a user:

// Add a user with name 'user1' and password 'I prefer to use passphrase rather than password.' if it doesn't exist in .htpasswd.
$passwdHandler -> addUser('user1', 'I prefer to use passphrase rather than password.');
// Delete the user 'user1' if it exists in .htpasswd.
$passwdHandler -> deleteUser('user1');

To check if a particular user exists in .htpasswd:

// Check if user 'user1' exists in .htpasswd.
if ($passwdHandler -> doesUserExist('user1')) {
	// User 'user1' exists.
}

To get the clear text password for a particular user (Apache stores passwords in .htpasswd as encoded strings):

// Get the clear password for user 'user1'.
echo $passwdHandler -> getClearPassword('user1');

To add a user to a group:

// Add user 'user1' to group 'admin' in .htgroup. Group will be automatically created if it doesn't exist.
$groupHandler -> addUserToGroup('user1', 'admin');

To delete a user from a group (user still exists in .htpasswd, just not associated with the group any more):

// Delete user 'user1' from group 'admin' in .htgroup. Group will be automatically removed if it doesn't contain any users.
$groupHandler -> deleteUserFromGroup('user1', 'admin');

To get a list of groups a particular user is assigned to:

/* Get an array of groups that 'user1' is a member of. */
$user_groups = $groupHandler -> getGroupsByUser('user1');

Conclusion

This ain’t concluded. It’s just an END notice. Feel free to let me know your thoughts and how my classes work for you.

Categories
Business and Marketing Coupons and Promo Codes Free Web Templates Internet Tools My Personal Reviews

Webmium Review – WYSIWYG Website Builder

Webmium 40% Discount Promo Code: KAVOIRWebmium may not have much to look at on their website – for which they better hurry up and get a better design – it’s actually very very easy and intuitive to use.  With adequate features, abundant site templates to choose from, and hundreds of online marketing guides, it’s the combo solution for people who want to get their business website up in less than 10 minutes, without having to spend an arm and a leg to tackle the challenges of web design, web development, web hosting, and web marketing. Webmium has it all.

Unbelievably Easy and Intuitive

After a few minutes of clicking and typing, my first site on Webmium was up and running – Xi’an Jobs. I didn’t have to think once to get my job done. Everything seemed to be right there when I needed it. I felt like a breeze being pushed by the wind, naturally and comfortably and never did I have to sweat any effort to accomplish the whole website which is decent enough for most undertakings. Your site is well modularized so that you can freely switch between themes / layout and move around objects without jeopardizing anything. Your content is never hard coded.

A WYSIWYG Website Editor Better than Desktop Programs

Everyone can learn and start doing it in a minute. In fact, it’s so intuitive and easy that everything including editing text, uploading image, adding contact form and creating another page is accomplished within one editor page. Check out the editor screenshot:

webmium website editor

You don’t get any more WYSIWYG than this. Lots of desktop website creator programs such as Adobe Dreamweaver and Microsoft Expression Web available on the market who claim to be WYSIWYG don’t come up close. You have to view the produced web page in a browser to see the final results. But with Webmium, it’s all in there, 100% WYSIWYG and never again do you have to scratch your head and ask why the hell does it look so different in the browser from that in the editor.

Free Entry Plan – Very Good for SEO

Best of all it’s free and they’ve got tons of FREE templates to choose from. You should get one up on Webmium right now. Sign up with them. It’s definitely worth the time to have an external page of content up for the sake of SEO. Be sure to create useful, original and rich content or Google won’t buy it just because it’s on a distant IP. Webmium has an auto-submission feature that after you have published your site it will automatically submit the site to search engines like Google.

My tiny site about Xi’an Jobs ( http://xian.webmium.com/ ) was indexed by Google 8 hours after being published at Webmium. Definitely looks promising from the perspective of SEO.

Quick Built-in Guides to Kick Start Your Online Marketing

For small business owners who don’t know how to have their own website online, Webmium is the no-brainer choice. It has got hundreds of articles and guides in the Marketing Academy on how to do it and what the best practices are, about not only the technical aspects but also the marketing part. It’s a perfect companion for starter small businesses owners who want to have their website up today, in the minimum effort and cost possible. And you are well guided along the way with built-in tips while you are building your online presence.

What can be improved about Webmium?

It’s a greatly simple and useful solution for starter business owners but there are definitely ways that Webmium can be improved. I’ll just lay out a few of the problems I met when playing with it:

  1. Currently there’s no way I can add text beside the logo. It’s either a logo or a text but you can’t combine.
  2. I don’t seem to be able to align social buttons such as facebook like buttons and tweet buttons together. Weird.
  3. Unable to modify footer attribution to add copyright notice, etc. I guess it’s because I’m on the free plan. You would probably be able to do that after upgrading to the PRO plan.
  4. For now, each account is limited to one website / domain. I think they can definitely offer the ability to create and manage multiple websites under one account in the PRO plan.

Other than these, Webmium is looking a prosperous future if they keep shaping it better.

Upgrading to PRO? Use a Promo Code!

Webmium was kind enough to offer an exclusive promo code to the readers of Kavoir.com. If you want to take advantage of the PRO plan that offers all the easiness to build a small business website as well as unlimited storage and bandwidth, use promo code:

KAVOIR
Click To Open/Copy

Like this:

Webmium Promo Code

When you are upgrading but before making payment. It would give you a nice 40% discount off the listed price.

Categories
Free PHP Classes & Library PHP Tips & Tutorials

PHP: Crontab Class to Add, Edit and Remove Cron Jobs

Provided that your user account on the server has the privileges to access crontab thus can create or remove cron jobs, you can use this PHP class to integrate crontab in your application. I created it for many of my own projects that need crontab to do scheduled jobs. It’s pretty straightforward.

Don’t know what crontab is and how it works? Read here and here. With this class, you or your users can easily set up crontab jobs and automate tasks by schedule with the web interface.

The Crontab Class

class Crontab {
	
	// In this class, array instead of string would be the standard input / output format.
	
	// Legacy way to add a job:
	// $output = shell_exec('(crontab -l; echo "'.$job.'") | crontab -');
	
	static private function stringToArray($jobs = '') {
		$array = explode("\r\n", trim($jobs)); // trim() gets rid of the last \r\n
		foreach ($array as $key => $item) {
			if ($item == '') {
				unset($array[$key]);
			}
		}
		return $array;
	}
	
	static private function arrayToString($jobs = array()) {
		$string = implode("\r\n", $jobs);
		return $string;
	}
	
	static public function getJobs() {
		$output = shell_exec('crontab -l');
		return self::stringToArray($output);
	}
	
	static public function saveJobs($jobs = array()) {
		$output = shell_exec('echo "'.self::arrayToString($jobs).'" | crontab -');
		return $output;	
	}
	
	static public function doesJobExist($job = '') {
		$jobs = self::getJobs();
		if (in_array($job, $jobs)) {
			return true;
		} else {
			return false;
		}
	}
	
	static public function addJob($job = '') {
		if (self::doesJobExist($job)) {
			return false;
		} else {
			$jobs = self::getJobs();
			$jobs[] = $job;
			return self::saveJobs($jobs);
		}
	}
	
	static public function removeJob($job = '') {
		if (self::doesJobExist($job)) {
			$jobs = self::getJobs();
			unset($jobs[array_search($job, $jobs)]);
			return self::saveJobs($jobs);
		} else {
			return false;
		}
	}
	
}

Public Methods

You may well ignore the private methods that do the internal chores. And keep in mind that any cron job is a text string.

  1. getJobs() – returns an array of existing / current cron jobs. Each array item is a string (cron job).
  2. saveJobs($jobs = array()) – save the $jobs array of cron jobs into the crontab so they would be run by the server. All existing jobs in crontab are erased and replaced by $jobs.
  3. doesJobExist($job = ”) – check if a specific job exist in crontab.
  4. addJob($job = ”) – add a cron job to the crontab.
  5. removeJob($job = ”) – remove a cron job from crontab.

This class has been tested on Rackspace Cloud and Wiredtree. Feel free to post your comments below and let me know how it works on other web hosts.

Categories
Free PHP Classes & Library

PHP Class: Convert Plural to Singular or Vice Versa in English

I was trying to find a PHP function or class that can convert English words / nouns in plural form into their singular form so that wordcrow.com automatically detects and redirects plural lookup to the singular page. After a while searching on Google, I found this class.

This great class (Inflector) was ported from Ruby on Rails to PHP in the Akelos Framework by Akelos Media, S.L. http://www.akelos.com/.

List of Functions

Other than pluralize and singularize, this class has some more functions to convert text strings by certain standards. List below are all the functions this class has:

  • Inflector::pluralize – return the plural form of the given English word, e.g. “search” to “searches”.
  • Inflector::singularize – return the singular form of the given English word, e.g. “searches” to “search”.
  • Inflector::titleize – create a title text from the given string, e.g. “WelcomePage”, “welcome_page” or “welcome page” to “Welcome Page”.
  • Inflector::camelize – return the CamelCased text from the given string, e.g. “send_email” to “SendEmail”, “who’s online” to “WhoSOnline”.
  • Inflector::underscore – return a underscored text from the given string, e.g. “CamelCased” or “ordinary Word” to “underscored_word” that is lowercased.
  • Inflector::humanize – return a human-readable text from the given string, e.g., by replacing underscores with spaces, and by upper-casing the initial character by default.
  • Inflector::variablize – same as camelize but first char is underscored.
  • Inflector::tableize – converts a class name to its table name by rails naming conventions.
  • Inflector::classify – converts a table name to its class name by rails naming conventions.
  • Inflector::ordinalize – converts a natural number to its ordinal form in English, e.g. “2” to “2nd”, “15” to “15th”, “31” to “31st”.

Inflector Class

<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

// +----------------------------------------------------------------------+
// | Akelos PHP Application Framework                                     |
// +----------------------------------------------------------------------+
// | Copyright (c) 2002-2006, Akelos Media, S.L.  http://www.akelos.com/  |
// | Released under the GNU Lesser General Public License                 |
// +----------------------------------------------------------------------+
// | You should have received the following files along with this library |
// | - COPYRIGHT (Additional copyright notice)                            |
// | - DISCLAIMER (Disclaimer of warranty)                                |
// | - README (Important information regarding this library)              |
// +----------------------------------------------------------------------+

/**
* Inflector for pluralize and singularize English nouns.
*
* This Inflector is a port of Ruby on Rails Inflector.
*
* It can be really helpful for developers that want to
* create frameworks based on naming conventions rather than
* configurations.
*
* It was ported to PHP for the Akelos Framework, a
* multilingual Ruby on Rails like framework for PHP that will
* be launched soon.
*
* @author Bermi Ferrer Martinez 
* @copyright Copyright (c) 2002-2006, Akelos Media, S.L. http://www.akelos.org
* @license GNU Lesser General Public License 
* @since 0.1
* @version $Revision 0.1 $
*/
class Inflector
{
    // ------ CLASS METHODS ------ //

    // ---- Public methods ---- //

    // {{{ pluralize()

    /**
    * Pluralizes English nouns.
    *
    * @access public
    * @static
    * @param    string    $word    English noun to pluralize
    * @return string Plural noun
    */
    function pluralize($word)
    {
        $plural = array(
        '/(quiz)$/i' => '1zes',
        '/^(ox)$/i' => '1en',
        '/([m|l])ouse$/i' => '1ice',
        '/(matr|vert|ind)ix|ex$/i' => '1ices',
        '/(x|ch|ss|sh)$/i' => '1es',
        '/([^aeiouy]|qu)ies$/i' => '1y',
        '/([^aeiouy]|qu)y$/i' => '1ies',
        '/(hive)$/i' => '1s',
        '/(?:([^f])fe|([lr])f)$/i' => '12ves',
        '/sis$/i' => 'ses',
        '/([ti])um$/i' => '1a',
        '/(buffal|tomat)o$/i' => '1oes',
        '/(bu)s$/i' => '1ses',
        '/(alias|status)/i'=> '1es',
        '/(octop|vir)us$/i'=> '1i',
        '/(ax|test)is$/i'=> '1es',
        '/s$/i'=> 's',
        '/$/'=> 's');

        $uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');

        $irregular = array(
        'person' => 'people',
        'man' => 'men',
        'child' => 'children',
        'sex' => 'sexes',
        'move' => 'moves');

        $lowercased_word = strtolower($word);

        foreach ($uncountable as $_uncountable){
            if(substr($lowercased_word,(-1*strlen($_uncountable))) == $_uncountable){
                return $word;
            }
        }

        foreach ($irregular as $_plural=> $_singular){
            if (preg_match('/('.$_plural.')$/i', $word, $arr)) {
                return preg_replace('/('.$_plural.')$/i', substr($arr[0],0,1).substr($_singular,1), $word);
            }
        }

        foreach ($plural as $rule => $replacement) {
            if (preg_match($rule, $word)) {
                return preg_replace($rule, $replacement, $word);
            }
        }
        return false;

    }

    // }}}
    // {{{ singularize()

    /**
    * Singularizes English nouns.
    *
    * @access public
    * @static
    * @param    string    $word    English noun to singularize
    * @return string Singular noun.
    */
    function singularize($word)
    {
        $singular = array (
        '/(quiz)zes$/i' => '\1',
        '/(matr)ices$/i' => '\1ix',
        '/(vert|ind)ices$/i' => '\1ex',
        '/^(ox)en/i' => '\1',
        '/(alias|status)es$/i' => '\1',
        '/([octop|vir])i$/i' => '\1us',
        '/(cris|ax|test)es$/i' => '\1is',
        '/(shoe)s$/i' => '\1',
        '/(o)es$/i' => '\1',
        '/(bus)es$/i' => '\1',
        '/([m|l])ice$/i' => '\1ouse',
        '/(x|ch|ss|sh)es$/i' => '\1',
        '/(m)ovies$/i' => '\1ovie',
        '/(s)eries$/i' => '\1eries',
        '/([^aeiouy]|qu)ies$/i' => '\1y',
        '/([lr])ves$/i' => '\1f',
        '/(tive)s$/i' => '\1',
        '/(hive)s$/i' => '\1',
        '/([^f])ves$/i' => '\1fe',
        '/(^analy)ses$/i' => '\1sis',
        '/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis',
        '/([ti])a$/i' => '\1um',
        '/(n)ews$/i' => '\1ews',
        '/s$/i' => '',
        );

        $uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');

        $irregular = array(
        'person' => 'people',
        'man' => 'men',
        'child' => 'children',
        'sex' => 'sexes',
        'move' => 'moves');

        $lowercased_word = strtolower($word);
        foreach ($uncountable as $_uncountable){
            if(substr($lowercased_word,(-1*strlen($_uncountable))) == $_uncountable){
                return $word;
            }
        }

        foreach ($irregular as $_plural=> $_singular){
            if (preg_match('/('.$_singular.')$/i', $word, $arr)) {
                return preg_replace('/('.$_singular.')$/i', substr($arr[0],0,1).substr($_plural,1), $word);
            }
        }

        foreach ($singular as $rule => $replacement) {
            if (preg_match($rule, $word)) {
                return preg_replace($rule, $replacement, $word);
            }
        }

        return $word;
    }

    // }}}
    // {{{ titleize()

    /**
    * Converts an underscored or CamelCase word into a English
    * sentence.
    *
    * The titleize function converts text like "WelcomePage",
    * "welcome_page" or  "welcome page" to this "Welcome
    * Page".
    * If second parameter is set to 'first' it will only
    * capitalize the first character of the title.
    *
    * @access public
    * @static
    * @param    string    $word    Word to format as tile
    * @param    string    $uppercase    If set to 'first' it will only uppercase the
    * first character. Otherwise it will uppercase all
    * the words in the title.
    * @return string Text formatted as title
    */
    function titleize($word, $uppercase = '')
    {
        $uppercase = $uppercase == 'first' ? 'ucfirst' : 'ucwords';
        return $uppercase(Inflector::humanize(Inflector::underscore($word)));
    }

    // }}}
    // {{{ camelize()

    /**
    * Returns given word as CamelCased
    *
    * Converts a word like "send_email" to "SendEmail". It
    * will remove non alphanumeric character from the word, so
    * "who's online" will be converted to "WhoSOnline"
    *
    * @access public
    * @static
    * @see variablize
    * @param    string    $word    Word to convert to camel case
    * @return string UpperCamelCasedWord
    */
    function camelize($word)
    {
        return str_replace(' ','',ucwords(preg_replace('/[^A-Z^a-z^0-9]+/',' ',$word)));
    }

    // }}}
    // {{{ underscore()

    /**
    * Converts a word "into_it_s_underscored_version"
    *
    * Convert any "CamelCased" or "ordinary Word" into an
    * "underscored_word".
    *
    * This can be really useful for creating friendly URLs.
    *
    * @access public
    * @static
    * @param    string    $word    Word to underscore
    * @return string Underscored word
    */
    function underscore($word)
    {
        return  strtolower(preg_replace('/[^A-Z^a-z^0-9]+/','_',
        preg_replace('/([a-zd])([A-Z])/','1_2',
        preg_replace('/([A-Z]+)([A-Z][a-z])/','1_2',$word))));
    }

    // }}}
    // {{{ humanize()

    /**
    * Returns a human-readable string from $word
    *
    * Returns a human-readable string from $word, by replacing
    * underscores with a space, and by upper-casing the initial
    * character by default.
    *
    * If you need to uppercase all the words you just have to
    * pass 'all' as a second parameter.
    *
    * @access public
    * @static
    * @param    string    $word    String to "humanize"
    * @param    string    $uppercase    If set to 'all' it will uppercase all the words
    * instead of just the first one.
    * @return string Human-readable word
    */
    function humanize($word, $uppercase = '')
    {
        $uppercase = $uppercase == 'all' ? 'ucwords' : 'ucfirst';
        return $uppercase(str_replace('_',' ',preg_replace('/_id$/', '',$word)));
    }

    // }}}
    // {{{ variablize()

    /**
    * Same as camelize but first char is underscored
    *
    * Converts a word like "send_email" to "sendEmail". It
    * will remove non alphanumeric character from the word, so
    * "who's online" will be converted to "whoSOnline"
    *
    * @access public
    * @static
    * @see camelize
    * @param    string    $word    Word to lowerCamelCase
    * @return string Returns a lowerCamelCasedWord
    */
    function variablize($word)
    {
        $word = Inflector::camelize($word);
        return strtolower($word[0]).substr($word,1);
    }

    // }}}
    // {{{ tableize()

    /**
    * Converts a class name to its table name according to rails
    * naming conventions.
    *
    * Converts "Person" to "people"
    *
    * @access public
    * @static
    * @see classify
    * @param    string    $class_name    Class name for getting related table_name.
    * @return string plural_table_name
    */
    function tableize($class_name)
    {
        return Inflector::pluralize(Inflector::underscore($class_name));
    }

    // }}}
    // {{{ classify()

    /**
    * Converts a table name to its class name according to rails
    * naming conventions.
    *
    * Converts "people" to "Person"
    *
    * @access public
    * @static
    * @see tableize
    * @param    string    $table_name    Table name for getting related ClassName.
    * @return string SingularClassName
    */
    function classify($table_name)
    {
        return Inflector::camelize(Inflector::singularize($table_name));
    }

    // }}}
    // {{{ ordinalize()

    /**
    * Converts number to its ordinal English form.
    *
    * This method converts 13 to 13th, 2 to 2nd ...
    *
    * @access public
    * @static
    * @param    integer    $number    Number to get its ordinal value
    * @return string Ordinal representation of given string.
    */
    function ordinalize($number)
    {
        if (in_array(($number % 100),range(11,13))){
            return $number.'th';
        }else{
            switch (($number % 10)) {
                case 1:
                return $number.'st';
                break;
                case 2:
                return $number.'nd';
                break;
                case 3:
                return $number.'rd';
                default:
                return $number.'th';
                break;
            }
        }
    }

    // }}}

}

?>

Usage Examples

/* Singular to plural / Plural to singular */

echo Inflector::pluralize('search'); // outputs searches
echo Inflector::singularize('cases'); // outputs case
echo Inflector::pluralize('query'); // outputs queries
echo Inflector::singularize('queries'); // outputs query
echo Inflector::pluralize('ability'); // outputs abilities
echo Inflector::singularize('abilities'); // outputs ability
echo Inflector::pluralize('analysis'); // outputs analyses
echo Inflector::singularize('analyses'); // outputs analysis
echo Inflector::pluralize('information'); // outputs information
echo Inflector::singularize('information'); // outputs information
echo Inflector::pluralize('mouse'); // outputs mice
echo Inflector::singularize('mice'); // outputs mouse

/* CamelCase to underscore / underscore to CamelCase */

echo Inflector::underscore('SpecialGuest'); // outputs special_guest
echo Inflector::camelize('special_guest'); // outputs SpecialGuest
echo Inflector::underscore('FreeBSD'); // outputs free_bsd
echo Inflector::camelize('free_bsd'); // outputs FreeBsd
echo Inflector::underscore('HTML'); // outputs html
echo Inflector::camelize('html'); // outputs Html

/* Underscore to "human-text" / "Human-text" to Underscore */

echo Inflector::humanize('employee_salary'); // outputs Employee salary
echo Inflector::underscore('Employee salary'); // outputs employee_salary

/* Examples of titleize() */

echo Inflector::titleize('ActiveRecord'); // outputs Active Record
echo Inflector::titleize('action web service'); // outputs Action Web Service

/* Examples of ordinalize() */

echo Inflector::ordinalize(1); // outputs 1st
echo Inflector::ordinalize(2); // outputs 2nd
echo Inflector::ordinalize(3); // outputs 3rd
echo Inflector::ordinalize(4); // outputs 4th
echo Inflector::ordinalize(5); // outputs 5th
echo Inflector::ordinalize(20); // outputs 20th
echo Inflector::ordinalize(21); // outputs 21st
Categories
Free PHP Website Scripts

Free PHP Business Directory Script

Simple PHP Script is a website scripts arsenal for Kavoir readers. My plan is to write many simple yet useful website scripts and release them in SPS for you to download and use. Some of them will be commercial and some of them will be free. The first script is a business directory website script in PHP and MySQL that I’m releasing free here.

Homepage layout

free php directory script screenshot
For the back-end administration control panel, use the demo account to log in.

How to download?

If you are interested in obtaining a copy of the script and use it for your own website, please sign up with our email list by the form in the right sidebar or the one immediately after this post.

After you have subscribed to the mailing list, not only can you download the script free, but you will also be notified of more free PHP website script releases in future.

What are the features?

This business directory script has a handy multi-step installation module to help you deploy the script on your server. PHP 5 is required. For now, you have to install it at the root of a dedicated domain or subdomain such as http://dir.example.com or http://www.example.com. You cannot install it in sub-directories such as http://www.example.com/dir.

It also comes with a user registration / contribution system and a full-fledged administration control panel. You can create and edit up to 2 tiers of categories. You and registered users can add business listings with business names, phone numbers, website URLs and postal addresses. You can choose to approve all the listings before they appear publicly or you can enable the users to instantly publish them on your site.

Paid inclusion is not available in this version yet. Nor is a usable template system. However these are already on my list of wanted features for this product.

Those who subscribes to Kavoir email list will receive all future upgrades for free. Just download the package again with the FreeCode that will be sent to your inbox after you have confirmed subscription.

Buy A Word Directory

Back a few years ago I also made this script: http://w3ec.com/ – the PHP link directory script that sells English words as links, $1 per letter. You can purchase a word and make it link back to your website. Feature the word on the homepage for an extra fee.

You can buy the script here: http://w3ec.com/script.php

Categories
Free Webmaster Resources Internet Tools My Products & Services

Create Contact and Survey Forms with FormKid.com the Free Online Form Builder

I just finished creating yet another web application that may be useful to fellow webmasters, FormKid.com. It helps you create professional online web forms for your website. Check out what I created just now, a contact form for Kavoir.com. You can contact me by filling out and submitting the form from now on!

Currently you can add 8 different types of input controls to your forms, namely

  1. Single Line Text
  2. Paragraph Text
  3. Check Boxes
  4. Radio Buttons
  5. Dropdown Selection
  6. Section Break
  7. Arbitrary HTML
  8. Captcha

Captcha is for recognizing and capturing spams and uses one of the 3 available approaches at your choice. The reCaptcha service that’s recently acquired by Google is one of them. So you can be rest assured that your form will stay clear of online spamming.

I’m planning to add more features such as advanced entries management in future but not until this application proves itself to be useful and popular. Before that, a lot of work need to be done to make the whole thing smooth, safe and frustration-free. Please join in the forum and let me know of your ideas.

If all you need is a simple PHP contact form, our company Simple PHP Script has it.

Categories
Free Webmaster Resources Internet Tools My Products & Services Web Design Tips and Insights

How to convert .png, .gif, .bmp or .jpg images to .ico icons to make favicon.ico for your website?

image conversion tool Over a year ago I created this online web application Convert Hub by the help of the splendid open source image manipulation library Netpbm. Give it a try, upload an image and convert it to another format. But not just that, it’s also capable of resizing an image, rotating or flipping it.

I love it. It’s simple yet adequately useful. The best part of it for a webmaster like me is that it can convert other image formats such as .bmp, .jpg, .gif and .png to .ico so I can use them as favicon.ico for my sites. Try these US state flags and convert them in any way you want!

It’s a great tool and gained tremendous popularity. I know this because one day DreamHost warned me of overwhelming server resource usage and took it down for good reasons. I had to move it elsewhere and Linode is where it currently resides on.

Server side computing is too expensive for a free application like this. After a few ideas and thoughts, I decided to create a client side software program to do the job instead. It’s called Batch Image Converter. And it proves to be much better. It doesn’t come with a daily limit on the number of conversions allowed per IP but you can do as many conversions as you want. The whole software consists of one single executable file, there’s even no need to go through any installation steps. It’s totally green to your system. What’s best, it can work in batches which means you are able to perform operations such as format conversion and dimension resizing on a lot of images by a single click.

All you need is to download it there. It’s free. The problem is that it only supports Windows for now. I’m planning on rolling out versions for other platforms but this may not happen soon.

Please do let me know what you think of the application in the forum.

Categories
Free Web Templates

A simple business web template with PHP contact form

The other day I created a simple website template in PHP for one of my friends and he eventually decided that he’s not going to need the website any more so I’m releasing it here for just $2.5 a copy. You are free to use it on any sites that you own.

Just purchase it at here: http://www.winkcart.com/store/phpscripts/foo-business-website-template/ and use the coupon code: SPECIAL5 to claim the $5 discount. You will be immediately downloading the template after paying via PayPal. Totally automatic.

I wanted to set up a demo for this template but it only works in the root directory of the domain so I’m going to save the trouble. If you decide that you don’t like it after paying and downloading, just let me know via the contact from on the sales page and I’ll issue the refund. No questions asked. 😉

Update: We have also a business directory script and a contact form script readily to be deployed to your website. Very easy to use and install.

Categories
Free PHP Classes & Library PHP Tips & Tutorials

A Simple PHP Contact Form Script

Update: Other than using the code outlined on this page, you may also want to download the Kavoir Contact Form script to be readily usable on your website.

It’s also a free one and a rather easy one too. You should be able to do it yourself. To create a working contact form, you need the front end and the back end. The front end presents the contact form to the website user and the back end accepts the data sent from the form by the user and take any necessary actions such as relaying the message to your email.

Visit FormKid.com for hosted free contact form solution.

Front end (HTML)

Simply copy this HTML form and paste it into your web pages where you want it to be, such as on the sidebar so a visitor can send you a contact message on any page.

<form action="/cf.php" method="post">
	<p><label for="input-email">Your Email: </label><br/><input type="text" name="email" id="input-email" size="40"/></p>
	<p><label for="input-message">Your Message: </label><br/><textarea type="text" name="message" id="input-message" rows="10" cols="40"></textarea></p>
	<p><button type="submit" name="submit">Send</button></p>
</form>

You may also want to style this form a little bit to make it look fancier. But make sure you don’t change any of the properties inside the tags such as action=”…” and name=”…”.

Back end (PHP)

Copy and paste these PHP code into a file named cf.php, change youremail@yoursite.com to your own email address that you wish to receive the messages. Put the file at the root directory of your domain so that everyone can access it at http://www.yoursite.com/cf.php.

<?php

if (isset($_GET['success'])) {

	?><p><span style="color:green;">Message successfully sent.</span> Thank you!</p><?php

} else {

	if (!empty($_POST['email']) && !empty($_POST['message'])) {

		$to = 'youremail@yoursite.com'; // your email address, can be @gmail.com, etc.
		$subject = 'Contact from yoursite.com'; // change yoursite.com to your own domain name
		$message = $_POST['message']."\r\n\r\nSender IP: ".$_SERVER["REMOTE_ADDR"];
		$headers = 'From: '.$_POST['email']."\r\n".
					'Reply-To: '.$_POST['email']."\r\n";
		mail($to, $subject, $message, $headers);

		header("Location: /cf.php?success"); // redirects the sender to success page so he or she doesn't accidentally send multiple identical messages

	} else {

		?><p><span style="color:red;">Error detected.</span> Please make sure you have filled all fields. Press back button to go back.</p><?php

	}

}

?>

Should be functioning properly. Thus far this contact form script has been successfully tested on Rackspace Cloud, DreamHost and Linode.

There are a lot more that can be done to create a sophisticated contact form. For starters, you can implement a spam catcher and a file upload control that sends the user uploaded file as attachment to your email. You could also have on-page error detection but that’d need a lot more coding.