<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Kavoir &#187; Free PHP Classes &amp; Library</title>
	<atom:link href="http://www.kavoir.com/category/free-webmaster-resources/free-php-classes/feed" rel="self" type="application/rss+xml" />
	<link>http://www.kavoir.com</link>
	<description>Just another dumbass webmaster, goofing around...</description>
	<lastBuildDate>Thu, 09 Feb 2012 01:59:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>PHP: Crontab Class to Add, Edit and Remove Cron Jobs</title>
		<link>http://www.kavoir.com/2011/10/php-crontab-class-to-add-and-remove-cron-jobs.html</link>
		<comments>http://www.kavoir.com/2011/10/php-crontab-class-to-add-and-remove-cron-jobs.html#comments</comments>
		<pubDate>Sun, 30 Oct 2011 02:49:06 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[Free PHP Classes & Library]]></category>
		<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2011/10/php-crontab-class-to-add-and-remove-cron-jobs.html</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>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.</p>

<p>Don’t know what crontab is and how it works? <a href="http://en.wikipedia.org/wiki/Cron">Read here</a> and <a href="http://net.tutsplus.com/tutorials/php/managing-cron-jobs-with-php-2/">here</a>. With this class, you or your users can easily set up crontab jobs and automate tasks by schedule with the web interface.</p>
<h2>The Crontab Class</h2>
<pre><code>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 &quot;'.$job.'&quot;) | crontab -');

	static private function stringToArray($jobs = '') {
		$array = explode(&quot;\r\n&quot;, trim($jobs)); // trim() gets rid of the last \r\n
		foreach ($array as $key =&gt; $item) {
			if ($item == '') {
				unset($array[$key]);
			}
		}
		return $array;
	}

	static private function arrayToString($jobs = array()) {
		$string = implode(&quot;\r\n&quot;, $jobs);
		return $string;
	}

	static public function <strong>getJobs</strong>() {
		$output = shell_exec('crontab -l');
		return self::stringToArray($output);
	}

	static public function <strong>saveJobs</strong>($jobs = array()) {
		$output = shell_exec('echo &quot;'.self::arrayToString($jobs).'&quot; | crontab -');
		return $output;
	}

	static public function <strong>doesJobExist</strong>($job = '') {
		$jobs = self::getJobs();
		if (in_array($job, $jobs)) {
			return true;
		} else {
			return false;
		}
	}

	static public function <strong>addJob</strong>($job = '') {
		if (self::doesJobExist($job)) {
			return false;
		} else {
			$jobs = self::getJobs();
			$jobs[] = $job;
			return self::saveJobs($jobs);
		}
	}

	static public function <strong>removeJob</strong>($job = '') {
		if (self::doesJobExist($job)) {
			$jobs = self::getJobs();
			unset($jobs[array_search($job, $jobs)]);
			return self::saveJobs($jobs);
		} else {
			return false;
		}
	}

}</code></pre>
<h2>Public Methods</h2>
<p>You may well ignore the private methods that do the internal chores. And keep in mind that <strong>any cron job is a text string</strong>.</p>
<ol>
<li><strong>getJobs</strong>() – returns an array of existing / current cron jobs. Each array item is a string (cron job).</li>
<li><strong>saveJobs</strong>($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.</li>
<li><strong>doesJobExist</strong>($job = &#8221;) – check if a specific job exist in crontab.</li>
<li><strong>addJob</strong>($job = &#8221;) – add a cron job to the crontab.</li>
<li><strong>removeJob</strong>($job = &#8221;) – remove a cron job from crontab.</li>
</ol>
<p>This class has been tested on <a href="http://www.rackspacecloudreview.com/">Rackspace Cloud</a> and <a href="http://www.wiredtreereviews.org/">Wiredtree</a>. Feel free to post your comments below and let me know how it works on other <a href="http://www.hostingkids.com/">web hosts</a>.</p>
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2009/08/php-email-attachment-class.html" rel="bookmark" title="August 6, 2009">PHP: Email Attachment Class</a></li>
<li><a href="http://www.kavoir.com/2009/06/php-differences-between-exec-system-and-passthru.html" rel="bookmark" title="June 2, 2009">PHP: Differences between exec(), shell_exec(), system() and passthru()</a></li>
<li><a href="http://www.kavoir.com/2009/01/php-resize-image-and-store-to-file.html" rel="bookmark" title="January 15, 2009">PHP: Resize Image and Store to File</a></li>
<li><a href="http://www.kavoir.com/2010/09/php-checking-text-strings-against-reserved-or-censored-words.html" rel="bookmark" title="September 27, 2010">PHP: Checking Text Strings against Reserved or Censored Words</a></li>
<li><a href="http://www.kavoir.com/2009/01/php-file-upload-class.html" rel="bookmark" title="January 15, 2009">PHP: File Upload Script (HTML Form + PHP Handler Class)</a></li>
</ul>
<p><!-- Similar Posts took 3.610 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2011/10/php-crontab-class-to-add-and-remove-cron-jobs.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP Class: Convert Plural to Singular or Vice Versa in English</title>
		<link>http://www.kavoir.com/2011/04/php-class-converting-plural-to-singular-or-vice-versa-in-english.html</link>
		<comments>http://www.kavoir.com/2011/04/php-class-converting-plural-to-singular-or-vice-versa-in-english.html#comments</comments>
		<pubDate>Sun, 03 Apr 2011 01:26:20 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[Free PHP Classes & Library]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2011/04/php-class-converting-plural-to-singular-or-vice-versa-in-english.html</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>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 <a href="http://www.wordcrow.com" _mce_href="http://www.wordcrow.com">wordcrow.com</a> automatically detects and redirects plural lookup to the singular page. After a while searching on Google, I found this class.</p>

<p>This great class (Inflector) was ported from Ruby on Rails to PHP in the <a href="http://www.akelos.org/" _mce_href="http://www.akelos.org/">Akelos Framework</a> by Akelos Media, S.L. <a href="http://www.akelos.com/" _mce_href="http://www.akelos.com/">http://www.akelos.com/</a>.</p>
<h2>List of Functions</h2>
<p>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:</p>
<ul>
<li>Inflector::<strong>pluralize </strong>- return the plural form of the given English word, e.g. &#8220;search&#8221; to &#8220;searches&#8221;.</li>
<li>Inflector::<strong>singularize </strong>- return the singular form of the given English word, e.g. &#8220;searches&#8221; to &#8220;search&#8221;.</li>
<li>Inflector::<strong>titleize </strong>- create a title text from the given string, e.g. &#8220;WelcomePage&#8221;, &#8220;welcome_page&#8221; or &#8220;welcome page&#8221; to &#8220;Welcome Page&#8221;.</li>
<li>Inflector::<strong>camelize </strong>- return the CamelCased text from the given string, e.g. &#8220;send_email&#8221; to &#8220;SendEmail&#8221;, &#8220;who&#8217;s online&#8221; to &#8220;WhoSOnline&#8221;.</li>
<li>Inflector::<strong>underscore </strong>- return a underscored text from the given string, e.g. &#8220;CamelCased&#8221; or &#8220;ordinary Word&#8221; to &#8220;underscored_word&#8221; that is lowercased.</li>
<li>Inflector::<strong>humanize </strong>- 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.</li>
<li>Inflector::<strong>variablize </strong>- same as camelize but first char is underscored.</li>
<li>Inflector::<strong>tableize </strong>- converts a class name to its table name by rails naming conventions.</li>
<li>Inflector::<strong>classify </strong>- converts a table name to its class name by rails naming conventions.</li>
<li>Inflector::<strong>ordinalize </strong>- converts a natural number to its ordinal form in English, e.g. &#8220;2&#8243; to &#8220;2nd&#8221;, &#8220;15&#8243; to &#8220;15th&#8221;, &#8220;31&#8243; to &#8220;31st&#8221;.</li>
</ul>
<h2>Inflector Class</h2>
<pre><code>&lt;?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 <bermi com="" akelos="">
* @copyright Copyright (c) 2002-2006, Akelos Media, S.L. http://www.akelos.org
* @license GNU Lesser General Public License <http: lesser.html="" copyleft="" www.gnu.org="">
* @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 <strong>pluralize</strong>($word)
    {
        $plural = array(
        '/(quiz)$/i' =&gt; '1zes',
        '/^(ox)$/i' =&gt; '1en',
        '/([m|l])ouse$/i' =&gt; '1ice',
        '/(matr|vert|ind)ix|ex$/i' =&gt; '1ices',
        '/(x|ch|ss|sh)$/i' =&gt; '1es',
        '/([^aeiouy]|qu)ies$/i' =&gt; '1y',
        '/([^aeiouy]|qu)y$/i' =&gt; '1ies',
        '/(hive)$/i' =&gt; '1s',
        '/(?:([^f])fe|([lr])f)$/i' =&gt; '12ves',
        '/sis$/i' =&gt; 'ses',
        '/([ti])um$/i' =&gt; '1a',
        '/(buffal|tomat)o$/i' =&gt; '1oes',
        '/(bu)s$/i' =&gt; '1ses',
        '/(alias|status)/i'=&gt; '1es',
        '/(octop|vir)us$/i'=&gt; '1i',
        '/(ax|test)is$/i'=&gt; '1es',
        '/s$/i'=&gt; 's',
        '/$/'=&gt; 's');

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

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

        $lowercased_word = strtolower($word);

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

        foreach ($irregular as $_plural=&gt; $_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 =&gt; $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 <strong>singularize</strong>($word)
    {
        $singular = array (
        '/(quiz)zes$/i' =&gt; '\1',
        '/(matr)ices$/i' =&gt; '\1ix',
        '/(vert|ind)ices$/i' =&gt; '\1ex',
        '/^(ox)en/i' =&gt; '\1',
        '/(alias|status)es$/i' =&gt; '\1',
        '/([octop|vir])i$/i' =&gt; '\1us',
        '/(cris|ax|test)es$/i' =&gt; '\1is',
        '/(shoe)s$/i' =&gt; '\1',
        '/(o)es$/i' =&gt; '\1',
        '/(bus)es$/i' =&gt; '\1',
        '/([m|l])ice$/i' =&gt; '\1ouse',
        '/(x|ch|ss|sh)es$/i' =&gt; '\1',
        '/(m)ovies$/i' =&gt; '\1ovie',
        '/(s)eries$/i' =&gt; '\1eries',
        '/([^aeiouy]|qu)ies$/i' =&gt; '\1y',
        '/([lr])ves$/i' =&gt; '\1f',
        '/(tive)s$/i' =&gt; '\1',
        '/(hive)s$/i' =&gt; '\1',
        '/([^f])ves$/i' =&gt; '\1fe',
        '/(^analy)ses$/i' =&gt; '\1sis',
        '/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' =&gt; '\1\2sis',
        '/([ti])a$/i' =&gt; '\1um',
        '/(n)ews$/i' =&gt; '\1ews',
        '/s$/i' =&gt; '',
        );

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

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

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

        foreach ($irregular as $_plural=&gt; $_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 =&gt; $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 <strong>titleize</strong>($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 <strong>camelize</strong>($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 <strong>underscore</strong>($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 <strong>humanize</strong>($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 <strong>variablize</strong>($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 <strong>tableize</strong>($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 <strong>classify</strong>($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 <strong>ordinalize</strong>($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;
            }
        }
    }

    // }}}

}

?&gt;</http:></bermi></code></pre>
<h2>Usage Examples</h2>
<pre><code>/* <strong>Singular to plural / Plural to singular</strong> */

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

/* <strong>CamelCase to underscore / underscore to CamelCase</strong> */

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

/* <strong>Underscore to "human-text" / "Human-text" to Underscore</strong> */

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

/* <strong>Examples of titleize()</strong> */

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

/* <strong>Examples of ordinalize()</strong> */

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</code></pre>
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2012/01/php-check-if-a-string-contain-only-uppercase-capital-letters.html" rel="bookmark" title="January 20, 2012">PHP: Check if A String Contain Only Uppercase / Capital Letters</a></li>
<li><a href="http://www.kavoir.com/2011/10/php-crontab-class-to-add-and-remove-cron-jobs.html" rel="bookmark" title="October 30, 2011">PHP: Crontab Class to Add, Edit and Remove Cron Jobs</a></li>
<li><a href="http://www.kavoir.com/2009/07/php-count-words-in-a-string.html" rel="bookmark" title="July 29, 2009">PHP: Count Words in a String</a></li>
<li><a href="http://www.kavoir.com/2009/04/php-string-case-uppercase-all-letters-or-lowercase-all-letters-in-a-string-uppercase-first-letter-of-a-string-uppercase-first-letter-of-all-words-in-a-string.html" rel="bookmark" title="April 23, 2009">PHP String Case: Uppercase all Letters or Lowercase all Letters in a String | Uppercase First Letter of a String | Uppercase First Letter of all Words in a String</a></li>
<li><a href="http://www.kavoir.com/2010/09/regular-expression-for-natural-numbers-or-positive-integers-1-2-3-11-12.html" rel="bookmark" title="September 29, 2010">Regular Expressions for Natural Numbers or Positive Integers (1, 2, 3, &hellip;), Negative Integers and Non-negative Integers</a></li>
</ul>
<p><!-- Similar Posts took 4.283 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2011/04/php-class-converting-plural-to-singular-or-vice-versa-in-english.html/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>A Simple PHP Contact Form Script</title>
		<link>http://www.kavoir.com/2009/12/a-basic-php-contact-form-script.html</link>
		<comments>http://www.kavoir.com/2009/12/a-basic-php-contact-form-script.html#comments</comments>
		<pubDate>Thu, 10 Dec 2009 01:04:00 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[Free PHP Classes & Library]]></category>
		<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/?p=1531</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p></p><p><strong style="color:green">Update:</strong> Other than using the code outlined on this page, you may also want to download the <a href="http://www.simplephpscript.com/catalog/contact-form/">Kavoir Contact Form</a> script to be readily usable on your website.</p>

<p>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 <strong>front end</strong> presents <a href="http://www.usabledatabases.com/contact/">the contact form</a> to the website user and the <strong>back end</strong> accepts the data sent from the form by the user  and take any necessary actions such as relaying the message to your email.</p>
<p>Visit FormKid.com for hosted <a href="http://www.formkid.com/">free contact form</a> solution.</p>
<h3>Front end (HTML)</h3>
<p>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.</p>
<pre><code>&lt;form action="/cf.php" method="post"&gt;
	&lt;p&gt;&lt;label for="input-email"&gt;Your Email: &lt;/label&gt;&lt;br/&gt;&lt;input type="text" name="email" id="input-email" size="40"/&gt;&lt;/p&gt;
	&lt;p&gt;&lt;label for="input-message"&gt;Your Message: &lt;/label&gt;&lt;br/&gt;&lt;textarea type="text" name="message" id="input-message" rows="10" cols="40"&gt;&lt;/textarea&gt;&lt;/p&gt;
	&lt;p&gt;&lt;button type="submit" name="submit"&gt;Send&lt;/button&gt;&lt;/p&gt;
&lt;/form&gt;</code></pre>
<p>You may also want to style this form a little bit to make it look fancier. But make sure you don&#8217;t change any of the properties inside the tags such as <strong>action=&#8221;&#8230;&#8221;</strong> and <strong>name=&#8221;&#8230;&#8221;</strong>.</p>
<h3>Back end (PHP)</h3>
<p>Copy and paste these PHP code into a file named <strong>cf.php</strong>, change <strong>youremail@yoursite.com</strong> 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 <strong>http://www.yoursite.com/cf.php</strong>.</p>
<pre><code>&lt;?php

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

	?&gt;&lt;p&gt;&lt;span style="color:green;"&gt;Message successfully sent.&lt;/span&gt; Thank you!&lt;/p&gt;&lt;?php

} else {

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

		$to = '<strong>youremail@yoursite.com</strong>'; // your email address, can be @gmail.com, etc.
		$subject = 'Contact from <strong>yoursite.com</strong>'; // 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 {

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

	}

}

?&gt;</code></pre>
<p>Should be functioning properly. Thus far this contact form script has been successfully tested on <a href="http://www.kavoir.com/2009/01/web-hosting-mosso-discount-coupon-code-control-panel-demo-email-demo.html">Rackspace Cloud</a>, <a href="http://www.kavoir.com/2009/05/dreamhost-review-pros-and-cons-plus-uptime-charts.html">DreamHost</a> and <a href="http://www.kavoir.com/2009/09/moving-from-slicehost-to-linode-an-initial-vps-hosting-review.html">Linode</a>.</p>
<p>There are a lot more that can be done to create a sophisticated contact form. For starters, you can implement a <a href="http://recaptcha.net/">spam catcher</a> and a <a href="http://www.kavoir.com/2009/01/php-file-upload-class.html">file upload</a> control that <a href="http://www.kavoir.com/2009/08/php-email-attachment-class.html">sends the user uploaded file as attachment</a> to your email. You could also have on-page error detection but that&#8217;d need a lot more coding.<br />
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2009/02/styling-file-upload-select-input-control-input-typefile.html" rel="bookmark" title="February 8, 2009">CSS: Styling File Upload / Select Input Control &lt;input type=&quot;file&quot; &hellip; /&gt;</a></li>
<li><a href="http://www.kavoir.com/2009/04/php-send-html-email-mail.html" rel="bookmark" title="April 23, 2009">PHP: Send HTML Email (mail)</a></li>
<li><a href="http://www.kavoir.com/2009/01/php-file-upload-class.html" rel="bookmark" title="January 15, 2009">PHP: File Upload Script (HTML Form + PHP Handler Class)</a></li>
<li><a href="http://www.kavoir.com/2009/04/php-read-from-keyboard-get-user-input-from-keyboard-console-by-typing.html" rel="bookmark" title="April 22, 2009">PHP: Read from Keyboard &#8211; Get User Input from Keyboard Console by Typing</a></li>
<li><a href="http://www.kavoir.com/2009/01/how-to-pass-variable-values-in-url-from-page-to-page-with-php.html" rel="bookmark" title="January 5, 2009">How to pass variable values in URL from page to page with PHP?</a></li>
</ul>
<p><!-- Similar Posts took 2.952 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2009/12/a-basic-php-contact-form-script.html/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>PHP: Email Attachment Class</title>
		<link>http://www.kavoir.com/2009/08/php-email-attachment-class.html</link>
		<comments>http://www.kavoir.com/2009/08/php-email-attachment-class.html#comments</comments>
		<pubDate>Thu, 06 Aug 2009 01:25:17 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[Free PHP Classes & Library]]></category>
		<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2009/08/php-email-attachment-class.html</guid>
		<description><![CDATA[You can send emails very easily with PHP by the help of mail() function, but how does one send attachment attached to that email? You’ll still use mail() function, but with a little more twists in the header argument – yes, the content of the attached file is actually encoded into the header of the [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>You can send emails very easily with PHP by the help of <strong>mail</strong>() function, but how does one send attachment attached to that email?</p>

<p>You’ll still use <strong>mail</strong>() function, but with a little more twists in the header argument – yes, the content of the attached file is actually encoded into the header of the email, can you believe that. Big head.</p>
<p>Unfortunately, it’s a pain in the ass every time you have to get through all the chores needed to attach and encode the file into the email header. You have to know the size of the file, <strong>base64_encode</strong>() it, <strong>chunk_split</strong>() it and set all the configurations required in the header so that the email client can recognize that something’s in the header and can extract it out as an attachment.</p>
<p>Anyway, I’ve made this class <strong>AttachmentEmail</strong> that you can email an attachment with PHP more easily. All the chores are taken care of. It’s written in a hurry so the structure can sure be better. Other than this, it works like a charm.</p>
<h4>The Class:</h4>
<pre><code>class AttachmentEmail {
	private $from = 'yours@email.com';
	private $from_name = 'Your Name';
	private $reply_to = 'yours@email.com';
	private $to = '';
	private $subject = '';
	private $message = '';
	private $attachment = '';
	private $attachment_filename = '';

	public function __construct($to, $subject, $message, $attachment = '', $attachment_filename = '') {
		$this -&gt; to = $to;
		$this -&gt; subject = $subject;
		$this -&gt; message = $message;
		$this -&gt; attachment = $attachment;
		$this -&gt; attachment_filename = $attachment_filename;
	}

	public function <strong>mail</strong>() {
		if (!empty($this -&gt; attachment)) {
			$filename = empty($this -&gt; attachment_filename) ? basename($this -&gt; attachment) : $this -&gt; attachment_filename ;
			$path = dirname($this -&gt; attachment);
			$mailto = $this -&gt; to;
			$from_mail = $this -&gt; from;
			$from_name = $this -&gt; from_name;
			$replyto = $this -&gt; reply_to;
			$subject = $this -&gt; subject;
			$message = $this -&gt; message;

			$file = $path.'/'.$filename;
			$file_size = filesize($file);
			$handle = fopen($file, "r");
			$content = fread($handle, $file_size);
			fclose($handle);
			$content = chunk_split(base64_encode($content));
			$uid = md5(uniqid(time()));
			$name = basename($file);
			$header = "From: ".$from_name." &lt;".$from_mail."&gt;\r\n";
			$header .= "Reply-To: ".$replyto."\r\n";
			$header .= "MIME-Version: 1.0\r\n";
			$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
			$header .= "This is a multi-part message in MIME format.\r\n";
			$header .= "--".$uid."\r\n";
			$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
			$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
			$header .= $message."\r\n\r\n";
			$header .= "--".$uid."\r\n";
			$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use diff. tyoes here
			$header .= "Content-Transfer-Encoding: base64\r\n";
			$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
			$header .= $content."\r\n\r\n";
			$header .= "--".$uid."--";

			if (<strong>mail</strong>($mailto, $subject, "", $header)) {
				return true;
			} else {
				return false;
			}
		} else {
			$header = "From: ".($this -&gt; from_name)." &lt;".($this -&gt; from)."&gt;\r\n";
			$header .= "Reply-To: ".($this -&gt; reply_to)."\r\n";

			if (<strong>mail</strong>($this -&gt; to, $this -&gt; subject, $this -&gt; message, $header)) {
				return true;
			} else {
				return false;
			}

		}
	}
}</code></pre>
<h4>The Usage:</h4>
<p>For example, there&#8217;s this file residing on your web server at the path: <strong>/home/racker/gift.jpg</strong> and you want it attached to an email you are sending to Marry:</p>
<pre><code>$sendit = new <strong>AttachmentEmail</strong>('marry@example.com', 'Merry Christmas!', 'Hi', '<strong>/home/racker/gift.jpg</strong>');
$sendit -&gt; mail();</code></pre>
<p>The last argument ($attachment_filename) can be left empty if a filename is included in the second to last argument ($attachment). Otherwise you have to make clear what the file name is so the class can grab it and send it via attachment.</p>
<p>It returns <strong>true</strong> if the delivery is successful, otherwise <strong>false</strong>.<br />
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2009/04/php-send-html-email-mail.html" rel="bookmark" title="April 23, 2009">PHP: Send HTML Email (mail)</a></li>
<li><a href="http://www.kavoir.com/2009/12/a-basic-php-contact-form-script.html" rel="bookmark" title="December 10, 2009">A Simple PHP Contact Form Script</a></li>
<li><a href="http://www.kavoir.com/2009/05/php-hide-the-real-file-url-and-provide-download-via-a-php-script.html" rel="bookmark" title="May 18, 2009">PHP: Hide the Real File URL and Provide Download via a PHP Script</a></li>
<li><a href="http://www.kavoir.com/2010/09/php-true-empty-function-to-check-if-a-string-is-empty-or-zero-in-length.html" rel="bookmark" title="September 29, 2010">PHP: True empty() function to check if a string is empty or zero in length</a></li>
<li><a href="http://www.kavoir.com/2009/01/php-file-upload-class.html" rel="bookmark" title="January 15, 2009">PHP: File Upload Script (HTML Form + PHP Handler Class)</a></li>
</ul>
<p><!-- Similar Posts took 3.031 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2009/08/php-email-attachment-class.html/feed</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<item>
		<title>Generating PDF documents with PHP</title>
		<link>http://www.kavoir.com/2009/03/generating-pdf-documents-with-php.html</link>
		<comments>http://www.kavoir.com/2009/03/generating-pdf-documents-with-php.html#comments</comments>
		<pubDate>Wed, 18 Mar 2009 14:49:03 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[Free PHP Classes & Library]]></category>
		<category><![CDATA[PDF Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2009/03/generating-pdf-documents-with-php.html</guid>
		<description><![CDATA[I generate, oh no, I mean PHP generates the PDF version of all the blog posts I have here by this library, but I think this one&#8216;s a lot easier! Giving it a try sometime later, thanks Dan for the find! Yeah, yeah, I know I know, I could have posted this to twitter by [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I generate, oh no, I mean PHP generates the PDF version of all the blog posts I have here by <a href="http://www.digitaljunkies.ca/dompdf/">this library</a>, but I think <a href="http://chir.ag/tech/download/pdfb/">this one</a>&#8216;s a lot easier!</p>

<p>Giving it a try sometime later, thanks <a href="http://www.djc.com.au">Dan</a> for the find!</p>
<p>Yeah, yeah, I know I know, I could have posted this to twitter by nature of microblogging. I&#8217;m just trying to be more casual and to be myself for a while.</p>
<p>I hate most of the social medias that are no more than just pompous distractions providing little value if at all.</p>
<p><strong><span style="color:green;">Update:</span></strong> Better libraries to accomplish the job of converting HTML/CSS to PDF documents might be <a href="http://www.tufat.com/s_html2ps_html2pdf.htm">HTML2PDF</a> and <a href="http://princexml.com/samples/">PrinceXML</a>.</p>
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2009/11/how-to-recover-lost-firefox-bookmarks-where-is-my-firefox-bookmarks-folder.html" rel="bookmark" title="November 12, 2009">How to recover lost Firefox bookmarks? Where is my Firefox bookmarks folder?</a></li>
<li><a href="http://www.kavoir.com/2009/06/how-to-transfer-move-wordpress-blog-from-one-domain-to-another.html" rel="bookmark" title="June 15, 2009">How to Transfer / Move WordPress Blog from One Domain to Another</a></li>
<li><a href="http://www.kavoir.com/2009/06/mysql-string-function-to-replace-substring-and-change-part-of-the-field-value.html" rel="bookmark" title="June 14, 2009">MySQL: String Function to Replace Substring and Change Part of the Field Value</a></li>
<li><a href="http://www.kavoir.com/2011/11/www-facebook-com-facts.html" rel="bookmark" title="November 26, 2011">www.facebook.com facts</a></li>
<li><a href="http://www.kavoir.com/2011/12/turn-your-blog-or-business-into-a-marketing-machine.html" rel="bookmark" title="December 1, 2011">Turn Your Blog or Business Into A Marketing Machine</a></li>
</ul>
<p><!-- Similar Posts took 2.898 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2009/03/generating-pdf-documents-with-php.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PHP: File Upload Script (HTML Form + PHP Handler Class)</title>
		<link>http://www.kavoir.com/2009/01/php-file-upload-class.html</link>
		<comments>http://www.kavoir.com/2009/01/php-file-upload-class.html#comments</comments>
		<pubDate>Thu, 15 Jan 2009 14:44:04 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[Free PHP Classes & Library]]></category>
		<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2009/01/php-file-upload-class.html</guid>
		<description><![CDATA[It’s sometimes cumbersome to handle uploaded files – checking if it is really uploaded, moving and renaming. Why not writing all these chores into a class and make our own file upload script? First we are going to create a simple class to handle uploaded files and move them to some place we designate for [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>It’s sometimes cumbersome to handle uploaded files – checking if it is really uploaded, moving and renaming. Why not writing all these chores into a class and make our own file upload script?</p>

<p>First we are going to create a simple class to handle uploaded files and move them to some place we designate for convenient access.</p>
<h5>The PHP Class (PHP5, Uploaded.class.php)</h5>
<pre><code>&lt;?php
class <strong>Uploaded</strong> {
	private $field_name = '';
	// <strong>$field_name</strong> is the name of the input in uploading form
	public function __construct(<strong>$field_name</strong>) {
		$this -&gt; field_name = <strong>$field_name</strong>;
	}
	// <strong>$path is</strong> the path to the directory where
	// the uploaded file you want stored.
	// <strong>$primary_name</strong> is the primary part of the
	// file name you want the new name of the uploaded file to be
	// such as 'song' with 'song.mp3'. The extensions part of the
	// new name will be determined from that of the uploaded one.
	public function getFileName(<strong>$path</strong>, <strong>$primary_name</strong> = '') {
		if (empty($path)) {
			return false;
		}
		if (empty($primary_name)) {
			// Use microtime() as temporary file name if no $primary_name is given
			$primary_name = microtime();
		}
		if (<strong>is_uploaded_file</strong>(<strong>$_FILES</strong>[$this -&gt; field_name]['tmp_name'])) {
			$client_name = basename($_FILES[$this -&gt; field_name]['name']);
			$ext = substr($client_name, strrpos($client_name, '.'));
			$server_name = $primary_name.$ext;
			if (<strong>file_exists</strong>($path.$server_name)) {
				// deleting any existing files with the same name here
				// so that the old file can be updated this way.
				unlink($path.$server_name);
			}
			if (<strong>move_uploaded_file</strong>($_FILES[$this -&gt; field_name]['tmp_name'], $path.$server_name)) {
				// The new name of the uploaded file will be returned
				// for access and retrieval of it.
				return <strong>$server_name</strong>;
			}
		}
		return false;
	}
}
?&gt;</code></pre>
<p>To adapt this class to PHP4, <a href="http://www.kavoir.com/2009/01/php4-class-differences-from-php5.html">read this</a>.</p>
<h5>The HTML</h5>
<pre><code>&lt;form enctype="multipart/form-data" method="post" action="upload.php"&gt;
	&lt;input type="file" name="<strong>photo</strong>" /&gt;
	&lt;button type="submit" name="<strong>submit</strong>"&gt;Submit&lt;/button&gt;
&lt;/form&gt;</code></pre>
<p>Fair enough, now we know browsers are going to send <strong>upload.php</strong> a file accessible in $_FILES via ‘<strong>photo</strong>’.</p>
<h5>The PHP (upload.php)</h5>
<p>Now we will use the <strong>Uploaded</strong> class (Uploaded.class.php) to handle the file sent from the HTML uploading form above.</p>
<pre><code>&lt;?php
require_once('Uploaded.class.php');
if (isset($_POST['<strong>submit</strong>'])) {
	$myPhoto = new Uploaded('<strong>photo</strong>');
	$photoFileName = $myPhoto -&gt; getFileName('uploaded/photos/', 'new_name');
}
?&gt;</code></pre>
<p>The uploaded file will now be all ready and accessible in <strong>uploaded/photos/new_name.ext</strong> (<strong>ext</strong> is whatever file extension the original file has) with <strong>$photoFileName</strong> containing its new name.<br />
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2009/08/php-email-attachment-class.html" rel="bookmark" title="August 6, 2009">PHP: Email Attachment Class</a></li>
<li><a href="http://www.kavoir.com/2009/01/check-for-file-size-with-javascript-before-uploading.html" rel="bookmark" title="January 1, 2009">Check for file size with JavaScript before uploading</a></li>
<li><a href="http://www.kavoir.com/2010/02/php-why-you-should-use-dirname__file__-include-php-instead-of-just-include-php.html" rel="bookmark" title="February 9, 2010">PHP: Why you should use dirname(__FILE__).&lsquo;/include.php&rsquo; instead of just &lsquo;include.php&rsquo;</a></li>
<li><a href="http://www.kavoir.com/2009/01/php-resize-image-and-store-to-file.html" rel="bookmark" title="January 15, 2009">PHP: Resize Image and Store to File</a></li>
<li><a href="http://www.kavoir.com/2009/02/styling-file-upload-select-input-control-input-typefile.html" rel="bookmark" title="February 8, 2009">CSS: Styling File Upload / Select Input Control &lt;input type=&quot;file&quot; &hellip; /&gt;</a></li>
</ul>
<p><!-- Similar Posts took 3.039 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2009/01/php-file-upload-class.html/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>PHP: Resize Image and Store to File</title>
		<link>http://www.kavoir.com/2009/01/php-resize-image-and-store-to-file.html</link>
		<comments>http://www.kavoir.com/2009/01/php-resize-image-and-store-to-file.html#comments</comments>
		<pubDate>Thu, 15 Jan 2009 13:52:31 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[Free PHP Classes & Library]]></category>
		<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2009/01/php-resize-image-and-store-to-file.html</guid>
		<description><![CDATA[While there are a lot of methods for you to resize images with php, we will be using extension gd this time. Make sure you or your hosting company has installed it in the php distribution by running &#60;?php if (extension_loaded('gd')) { // return true if the extension’s loaded. echo 'Installed.'; } else { if [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>While there are a lot of methods for you to resize images with php, we will be using extension <a href="http://www.php.net/gd">gd</a> this time. Make sure you or your hosting company has installed it in the php distribution by running</p>

<pre><code>&lt;?php
if (<strong>extension_loaded</strong>('gd')) { // return true if the extension’s loaded.
	echo 'Installed.';
} else {
	if (<strong>dl</strong>('gd.so')) { // dl() loads php extensions on the fly.
		echo 'Installed.';
	} else {
		echo 'Not installed.';
	}
}
?&gt;</code></pre>
<p>If the output is ‘Installed.’, let’s proceed to resize some images in php.</p>
<p>This image resize script is meant for shot photos because it works better with bitmap images such as <strong>.jpg</strong> and <strong>.bmp</strong>. If you need to keep transparency in the output, the code below will not help you.</p>
<h4>PHP Resize Image Class</h4>
<p>Basically, this class is created with the source image (<strong>$originalFile</strong>, the full path to the image) to be resized. When you initiate method resize() which takes in 2 parameters, new width (<strong>$newWidth</strong>) and the target file (<strong>$targetFile</strong>, full path to the destination image file) that would be storing the resized image, it goes like this:</p>
<ol>
<li>Get the original width and height of the image. </li>
<li>Calculate the new height given the new width &#8211; you could easily tweak the code yourself to resize the image by a new height. </li>
<li>Resize the image by the help of <a href="http://www.php.net/gd">gd</a>. </li>
<li>Store the resized image in <strong>$targetFile</strong>, optionally erasing the old file before dumping the data because chances are you just want to resize the image and don&#8217;t need the old version anymore. However, if it&#8217;s just a temporary resize, make <strong>$targetFile</strong> different from <strong>$originalFile</strong>. </li>
</ol>
<h5>Class (PHP5):</h5>
<pre><code>class ImgResizer {
	private $originalFile = '';
	public function __construct($originalFile = '') {
		$this -&gt; originalFile = $originalFile;
	}
	public function resize($newWidth, $targetFile) {
		if (empty($newWidth) || empty($targetFile)) {
			return false;
		}
		$src = <strong>imagecreatefromjpeg</strong>($this -&gt; originalFile);
		list($width, $height) = <strong>getimagesize</strong>($this -&gt; originalFile);
		$newHeight = ($height / $width) * $newWidth;
		$tmp = <strong>imagecreatetruecolor</strong>($newWidth, $newHeight);
		<strong>imagecopyresampled</strong>($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
		if (file_exists($targetFile)) {
			unlink($targetFile);
		}
		<strong>imagejpeg</strong>($tmp, $targetFile, 85); // 85 is my choice, make it between 0 – 100 for output image quality with 100 being the most luxurious
	}
}</code></pre>
<h5>Class (PHP4):</h5>
<pre><code>class ImgResizer {
	var $originalFile = '';
	function ImgResizer($originalFile = '') {
		$this -&gt; originalFile = $originalFile;
	}
	function resize($newWidth, $targetFile) {
		if (empty($newWidth) || empty($targetFile)) {
			return false;
		}
		$src = imagecreatefromjpeg($this -&gt; originalFile);
		list($width, $height) = getimagesize($this -&gt; originalFile);
		$newHeight = ($height / $width) * $newWidth;
		$tmp = imagecreatetruecolor($newWidth, $newHeight);
		imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
		if (file_exists($targetFile)) {
			unlink($targetFile);
		}
		imagejpeg($tmp, $targetFile, 85);
	}
}</code></pre>
<h5>Class usage</h5>
<pre><code>&lt;?php

$work = new <strong>ImgResizer</strong>('img/me.jpg'); // me.jpg (800x600) is in directory ‘img’ in the same path as this php script.
$work -&gt; <strong>resize</strong>(400, 'img/me.jpg'); // the old me.jpg (800x600) is now replaced and overwritten with a smaller me.jpg (400x300).

// To store resized image to a new file thus retaining the 800x600 version of me.jpg, go with this instead:
// $work -&gt; resize(400, 'img/me_smaller.jpg');

?&gt;</code></pre>
<p>As I have said, you might want to resize the image by a new height and calculate the width instead of going the other way around as I’ve done thus far, and it&#8217;s easy to make your tweak in the class above because height and width are fundamentally the same in dimensions, and no one’s more privileged over the other.</p>
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2010/09/php-true-empty-function-to-check-if-a-string-is-empty-or-zero-in-length.html" rel="bookmark" title="September 29, 2010">PHP: True empty() function to check if a string is empty or zero in length</a></li>
<li><a href="http://www.kavoir.com/2011/12/php-get-mime-type-of-a-file-and-encoding.html" rel="bookmark" title="December 25, 2011">PHP: Get Mime Type of a File (and Encoding)</a></li>
<li><a href="http://www.kavoir.com/2009/03/html-table-size-control-and-change-the-size-of-table-and-table-cells.html" rel="bookmark" title="March 5, 2009">HTML Table Size – Control and Change the Size of Table and Table Cells</a></li>
<li><a href="http://www.kavoir.com/2009/01/extended-css-sprites-for-foreground-images-img.html" rel="bookmark" title="January 9, 2009">Extended CSS Sprites for Foreground Images &lt;img&gt;</a></li>
<li><a href="http://www.kavoir.com/2009/02/styling-file-upload-select-input-control-input-typefile.html" rel="bookmark" title="February 8, 2009">CSS: Styling File Upload / Select Input Control &lt;input type=&quot;file&quot; &hellip; /&gt;</a></li>
</ul>
<p><!-- Similar Posts took 4.348 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2009/01/php-resize-image-and-store-to-file.html/feed</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>What is PHP framework &amp; Who are the Best PHP Frameworks?</title>
		<link>http://www.kavoir.com/2007/08/a-small-introduction-to-php-frameworks.html</link>
		<comments>http://www.kavoir.com/2007/08/a-small-introduction-to-php-frameworks.html#comments</comments>
		<pubDate>Mon, 06 Aug 2007 05:52:06 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[Free PHP Classes & Library]]></category>
		<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2007/08/a-small-introduction-to-php-frameworks.html</guid>
		<description><![CDATA[Basically, PHP frameworks are programming layers that are promoted above PHP itself and that are much easier and quicker to deploy, normalizing and packaging 80% of the routines one is expected to work on without them, such as database interfaces. Therefore they free you from the chores of coding from very scratch line by line [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Basically, PHP frameworks are programming layers that are promoted above PHP  itself and that are much easier and quicker to deploy, normalizing and packaging  80% of the routines one is expected to work on without them, such as database  interfaces. Therefore they free you from the chores of coding from very scratch  line by line and do the common tasks that are shared among most of the projects  for you.</p>

<p>Like many other frameworks, PHP frameworks such as the <a href="http://codeigniter.com/" target="_blank">Code Igniter</a> and <a href="http://www.cakephp.org/" target="_blank">CakePHP</a> are built upon the <strong>MVC  model</strong>. MVC stands for Model, View and Controller.</p>
<p><strong>Model</strong> is  essentially a prototype of all similar entities bearing shared descriptive  properties. In the database, a table can almost always be interpreted as a  model.</p>
<p><strong>View</strong> prescribes how the data(models) are presented(in the  browser, as webpages for example). In most cases, a view is a webpage  template.</p>
<p><strong>Controller</strong> is the control hub that can be directly  manipulated to control other stuff, namely models and views. It&#8217;s where the  logic lies in your PHP applications.</p>
<p><span style="font-size: large;"><span style="color: darkgreen;">3 major PHP frameworks:</span></span></p>
<p>1. <a href="http://codeigniter.com/" target="_blank">Code Igniter</a>, is well  documented and has a shorter learning curve, thus more appealing to  beginners.<br />
2. <a href="http://www.cakephp.org/" target="_blank">CakePHP</a>, is  more of cup of tea for veteran PHP developers. As intuitive to use as CI, but  not as well documented and the learning curve might be a little too long.<br />
3.  <a href="http://smarty.php.net/" target="_blank">Smarty</a>, I don&#8217;t know much  about this one and only tried it once. It&#8217;s more like a templating system than a  framework, I think. If you don&#8217;t plan to add registration functionalities, session management and things like that, you can go with Smarty, though CI and cake can also do a good job in templating.</p>
<p><strong><span style="color: #008000;">Update:</span></strong> There&#8217;s also a 4th greatly renowned php framework that is <a href="http://framework.zend.com/">Zend Framework</a>. All seems well done and I&#8217;m gonna try it out for one of my recent projects soon.<br />
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2009/05/what-is-a-programming-framework.html" rel="bookmark" title="May 2, 2009">What is a programming framework?</a></li>
<li><a href="http://www.kavoir.com/2009/07/be-simple.html" rel="bookmark" title="July 6, 2009">Being simple as a bless for development cost</a></li>
<li><a href="http://www.kavoir.com/2009/07/a-few-suggestions-of-good-practices-for-accelerating-php-development.html" rel="bookmark" title="July 6, 2009">A few suggestions of good practices for accelerating PHP development</a></li>
<li><a href="http://www.kavoir.com/2009/06/best-mysql-books-to-learn-mysql-database-php-applications.html" rel="bookmark" title="June 17, 2009">Best MySQL Books to Learn MySQL Database Programming and Development (+ PHP Applications)</a></li>
<li><a href="http://www.kavoir.com/2009/05/dreamhost-review-pros-and-cons-plus-uptime-charts.html" rel="bookmark" title="May 9, 2009">DreamHost Review: Pros and Cons plus Uptime Charts</a></li>
</ul>
<p><!-- Similar Posts took 2.939 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2007/08/a-small-introduction-to-php-frameworks.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

