<?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; PHP Tips &amp; Tutorials</title>
	<atom:link href="http://www.kavoir.com/category/programming/php-tips/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: Check if A String Contain Only Uppercase / Capital Letters</title>
		<link>http://www.kavoir.com/2012/01/php-check-if-a-string-contain-only-uppercase-capital-letters.html</link>
		<comments>http://www.kavoir.com/2012/01/php-check-if-a-string-contain-only-uppercase-capital-letters.html#comments</comments>
		<pubDate>Fri, 20 Jan 2012 06:32:44 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/?p=2663</guid>
		<description><![CDATA[Sometimes you would want to check if a string is an acronym or an abbreviation by testing if it only contains capitalized letters from A to Z and nothing else. There are 2 ways to accomplish this simple task in PHP. ctype_upper() Use the native ctype_upper() function and you will know if the provided string [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Sometimes you would want to check if a string is an acronym or an abbreviation by testing if it only contains capitalized letters from <strong>A to Z</strong> and nothing else. There are 2 ways to accomplish this simple task in PHP.</p>

<h2>ctype_upper()</h2>
<p>Use the native <a href="http://php.net/manual/en/function.ctype-upper.php">ctype_upper</a>() function and you will know if the provided string contains only uppercase letters:</p>
<pre><code>if (<strong>ctype_upper</strong>($string)) {
	echo $string.' is all uppercase letters.';
} else {
	echo $string.' is not all uppercase letters.';
}</code></pre>
<p>The <a href="http://www.php.net/manual/en/ref.ctype.php">Ctype functions</a> would turn out to be very handy when you want to test a string against different character types – digits, alphabetic, alpha-numeric, lowercase letters, uppercase letter, and even punctuations, etc. See the full list here: <a href="http://www.php.net/manual/en/ref.ctype.php">http://www.php.net/manual/en/ref.ctype.php</a></p>
<h2>strtoupper()</h2>
<p>Use the <strong>strtoupper</strong>() function to transform the string into all uppercase characters that’s capitalized letters, and then compare the transformed string against the original one to see if they are identical. If they are, then you are pretty sure the original string was also a string consisting of ONLY capital letters.</p>
<pre><code>if (<strong>strtoupper($string) == $string</strong>) {
	echo $string.' is all uppercase letters.';
}</code></pre>
<h2>Check if A String Consists of Only Lowercase Letters</h2>
<p>The same goes true if you want to do the test other way around. Just use <strong>ctype_lower</strong>() and <strong>strtolower</strong>() instead.</p>
<h3>Related Posts:</h3>
<ul class="similar-posts">
<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/2011/04/php-class-converting-plural-to-singular-or-vice-versa-in-english.html" rel="bookmark" title="April 3, 2011">PHP Class: Convert Plural to Singular or Vice Versa in English</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/06/php-change-array-key-case-all-array-keys-to-lowercase-or-uppercase.html" rel="bookmark" title="June 2, 2009">PHP: Change Array Key Case &#8211; All Array Keys to Lowercase or Uppercase</a></li>
<li><a href="http://www.kavoir.com/2009/06/php-create-an-array-of-a-range-of-characters-numbers-or-letters-or-multiple-identical-values.html" rel="bookmark" title="June 2, 2009">PHP: Create an Array of A Range of Characters (Numbers or Letters) or Multiple Identical Values</a></li>
</ul>
<p><!-- Similar Posts took 2.388 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2012/01/php-check-if-a-string-contain-only-uppercase-capital-letters.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP: Get Mime Type of a File (and Encoding)</title>
		<link>http://www.kavoir.com/2011/12/php-get-mime-type-of-a-file-and-encoding.html</link>
		<comments>http://www.kavoir.com/2011/12/php-get-mime-type-of-a-file-and-encoding.html#comments</comments>
		<pubDate>Sun, 25 Dec 2011 04:22:31 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2011/12/php-get-mime-type-of-a-file-and-encoding.html</guid>
		<description><![CDATA[While you can somewhat rely on the name extension of a file to determine the mime type, it may not always be accurate. For example, .jpg and .jpeg files are very probably image/jpeg files and .png files are very probably image/png files, but there’s always an exception because file extensions can be faked. To accurately [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>While you can somewhat rely on the name extension of a file to determine the mime type, it may not always be accurate. For example, .jpg and .jpeg files are very probably <strong>image/jpeg</strong> files and .png files are very probably <strong>image/png</strong> files, but there’s always an exception because file extensions can be faked. To accurately find the mime type of a specific file in PHP, you should use the <a href="http://www.php.net/manual/en/ref.fileinfo.php">Fileinfo extension</a>.</p>

<p>Find out if the extension is enabled with the code outlined in the beginning part of the <a href="http://www.kavoir.com/2009/01/php-resize-image-and-store-to-file.html">resize image in PHP</a> post.</p>
<p>With the <strong>php_fileinfo</strong> extension enabled in php.ini, this is the function I come up with:</p>
<pre><code>$finfo = new finfo(FILEINFO_MIME); // return mime type
if ($finfo) {
	$file_name = &quot;/absolute/path/to/some.jpg&quot;; /* Must use absolute path */
	$file_info = $finfo-&gt;file($file_name);
	$mime_type = substr($file_info, 0, strpos($file_info, ';'));
	echo $mime_type;
}</code></pre>
<p>Which will get you this:</p>
<pre><code>image/jpeg</code></pre>
<p>The reason it gets complicated in the echo line is that the standard output of FILEINFO_MIME information output by the file() function of the $finfo object is something like this:</p>
<pre><code>image/jpeg; charset=binary</code></pre>
<p>Therefore, you have to literally get everything before the semi-colon to get the mime type information.</p>
<p>If it was a CSS file, the output of the $finfo-&gt;file() method would be like this:</p>
<pre><code>text/plain; charset=utf-8</code></pre>
<p>Cool, huh! <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-winkingsmile" alt="Winking smile" src="http://www.kavoir.com/wp-content/uploads/2011/12/wlEmoticon-winkingsmile1.png" /></p>
<h3>Related Posts:</h3>
<ul class="similar-posts">
<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/2011/01/linux-how-to-find-only-text-files.html" rel="bookmark" title="January 22, 2011">Linux: How to &#8216;find&#8217; and search ONLY text files?</a></li>
<li><a href="http://www.kavoir.com/2009/01/php-run-html-as-php.html" rel="bookmark" title="January 19, 2009">PHP: Run HTML as PHP</a></li>
<li><a href="http://www.kavoir.com/2009/04/php-get-directory-or-filename-from-a-full-path-or-url.html" rel="bookmark" title="April 22, 2009">PHP: Getting Directory Path and Filename from A Full Path or URL</a></li>
<li><a href="http://www.kavoir.com/2011/05/php-explore-display-contents-of-directory-recursively.html" rel="bookmark" title="May 10, 2011">PHP: Display Files and Sub-directories of A Directory Recursively as A Tree</a></li>
</ul>
<p><!-- Similar Posts took 2.650 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2011/12/php-get-mime-type-of-a-file-and-encoding.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Redirect 404 Error to Home Page</title>
		<link>http://www.kavoir.com/2011/12/redirect-404-error-to-home-page.html</link>
		<comments>http://www.kavoir.com/2011/12/redirect-404-error-to-home-page.html#comments</comments>
		<pubDate>Sun, 25 Dec 2011 03:15:19 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[CSS & HTML Tips]]></category>
		<category><![CDATA[HTTP Tips & Tutorials]]></category>
		<category><![CDATA[PHP Tips & Tutorials]]></category>
		<category><![CDATA[WordPress How To]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2011/12/redirect-404-error-to-home-page.html</guid>
		<description><![CDATA[Other than making your 404 error page user friendly, you can redirect it to your index pages such as the homepage, sitemap, or search page, to make it useful for the users. Instead of relying on them to correct the error themselves, you offer the new orientation. How to redirect a 404 error page to [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Other than making your <a href="http://www.smashingmagazine.com/2007/08/17/404-error-pages-reloaded/">404 error page</a> <a href="http://www.alistapart.com/articles/perfect404/">user friendly</a>, you can redirect it to your index pages such as the homepage, sitemap, or search page, to make it useful for the users. Instead of relying on them to correct the error themselves, you offer the new orientation.</p>

<h2>How to redirect a 404 error page to the home page?</h2>
<p>There are essentially 3 ways to do this depending on the technology your site is built on.</p>
<h3>The .htaccess and HTML solution</h3>
<p>This works across all sites that are served by the Apache web server with .htaccess enabled. Add this line in the .htaccess file in the root directory of your domain:</p>
<pre><code>ErrorDocument 404 /404.html</code></pre>
<p>And in 404.html, add a meta tag in the HTML head section: </p>
<pre><code>&lt;meta http-equiv=&quot;Refresh&quot; content=&quot;1; URL=http://www.example.com/&quot;&gt;</code></pre>
<p>So when there’s an 404 Not Found error the user would be first redirected to /404.html and in turn, he or she would be redirected to the homepage http://www.example.com/ (or whatever you change it to) by the meta <strong>Refresh</strong> actions.</p>
<h3>The PHP solution</h3>
<p>If you are using PHP to code your site, chances are you know this solution. You can always use the previous solution (The .htaccess and HTML solution) to redirect 404 error page to your home page on a PHP site, but you can also try the pure PHP approach instead.</p>
<p>Whenever a user types in a URL request that you do not recognize, render this:</p>
<pre><code>header(&quot;HTTP/1.1 404 Not Found&quot;);
header(&quot;Location: /&quot;);
exit();</code></pre>
<p>Which would redirect the user who has hit a 404 error to the homepage / or any other page URL you specify there.</p>
<h3>The WordPress solution</h3>
<p>If you are using WordPress for your site, make a 404.php file in your theme directory with the following content:</p>
<pre><code>&lt;?php
header(&quot;HTTP/1.1 301 Moved Permanently&quot;);
header(&quot;Location: &quot;.get_bloginfo('url'));
exit();</code></pre>
<p>WordPress would automatically use 404.php as the default 404 Not Found error page and when a user hits that page, he or she would then be taken to the home page your WordPress blog.</p>
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2009/09/how-to-redirect-the-visitor-to-another-page-or-website.html" rel="bookmark" title="September 3, 2009">How to redirect the visitor to another page or website?</a></li>
<li><a href="http://www.kavoir.com/2009/08/javascript-stop-and-prevent-others-from-framing-your-site-and-page.html" rel="bookmark" title="August 30, 2009">PHP, JavaScript: Stop and prevent others from framing your site or web page</a></li>
<li><a href="http://www.kavoir.com/2011/08/html-make-a-page-refresh-every-xx-seconds.html" rel="bookmark" title="August 28, 2011">HTML: Make a Page Refresh Every xx Seconds</a></li>
<li><a href="http://www.kavoir.com/2009/06/javascript-open-or-redirect-to-another-page-site-location.html" rel="bookmark" title="June 16, 2009">JavaScript: Open or Redirect to Another Page / Site / Location</a></li>
<li><a href="http://www.kavoir.com/2009/09/best-way-to-hide-and-cloak-your-affiliate-links.html" rel="bookmark" title="September 19, 2009">Best way to hide and cloak your affiliate links?</a></li>
</ul>
<p><!-- Similar Posts took 2.457 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2011/12/redirect-404-error-to-home-page.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP: Store Array in File &#8211; Read / Write Arrays in File</title>
		<link>http://www.kavoir.com/2011/12/php-store-array-in-file-read-write-arrays-in-file.html</link>
		<comments>http://www.kavoir.com/2011/12/php-store-array-in-file-read-write-arrays-in-file.html#comments</comments>
		<pubDate>Thu, 22 Dec 2011 05:15:34 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2011/12/php-store-array-in-file-read-write-arrays-in-file.html</guid>
		<description><![CDATA[You can save re-usable data in database such as MySQL so you can load them among different scripts / script sessions, though it may be a bit overwhelming for simple tasks because you have to set up a whole database and the connection credentials, etc.. File system is probably a better approach with regards to [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>You can save re-usable data in database such as <a href="http://www.kavoir.com/2011/03/mysql-performance-tips.html">MySQL</a> so you can load them among different scripts / script sessions, though it may be a bit overwhelming for simple tasks because you have to set up a whole database and the connection credentials, etc.. File system is probably a better approach with regards to storing and retrieving simple tabular data, for not-so-important projects or test projects.</p>

<p>Then should we opt for XML or JSON? XML is bit too formal for teensy jobs. <a href="http://www.json.org/">JSON</a>, on the other hand, is the star of simplicity and capable or dealing with both tabular data and objects quite handily.</p>
<p>So we will store tabular data such as an PHP Array to JSON text which would then be stored as a ASCII text file. When we need to use the array again, be it in another PHP script or at a later time, we would just load the JSON string in the file and decode it into an array in PHP.</p>
<p>How can we do this? As simple as abc.</p>
<h2>Store PHP Array in File</h2>
<pre><code>file_put_contents('array.txt', <strong>json_encode</strong>($your_array));</code></pre>
<h2>Read Array from File</h2>
<pre><code>$your_array = <strong>json_decode</strong>(file_get_contents('array.txt'), true);</code></pre>
<h2>Serialize()</h2>
<p>Another approach is to use the <a href="http://php.net/serialize">serialize</a>() and <a href="http://php.net/unserialize">unserialize</a>() functions of PHP. You may want to read this to choose between them: <a href="http://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize">http://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize</a><br />
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2009/04/php-reading-a-file-into-a-string-or-reading-the-file-into-an-array.html" rel="bookmark" title="April 22, 2009">PHP: Reading a File into a String or Reading the File into an Array</a></li>
<li><a href="http://www.kavoir.com/2009/06/php-create-an-array.html" rel="bookmark" title="June 2, 2009">PHP: Create an Array</a></li>
<li><a href="http://www.kavoir.com/2009/06/mysql-php-display-mysql-table-fields-and-data.html" rel="bookmark" title="June 6, 2009">MySQL, PHP: Display MySQL table fields and data</a></li>
<li><a href="http://www.kavoir.com/2009/04/php-randomizing-all-lines-of-a-file-shuffle-lines-in-a-text-file.html" rel="bookmark" title="April 22, 2009">PHP: Randomizing All Lines of a File &ndash; Shuffle Lines in a Text File</a></li>
<li><a href="http://www.kavoir.com/2009/06/php-create-an-array-of-a-range-of-characters-numbers-or-letters-or-multiple-identical-values.html" rel="bookmark" title="June 2, 2009">PHP: Create an Array of A Range of Characters (Numbers or Letters) or Multiple Identical Values</a></li>
</ul>
<p><!-- Similar Posts took 4.262 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2011/12/php-store-array-in-file-read-write-arrays-in-file.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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 4.535 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>4 Tips for Zend Studio 8 (Eclipse)</title>
		<link>http://www.kavoir.com/2011/09/3-tips-for-zend-studio-8-eclipse.html</link>
		<comments>http://www.kavoir.com/2011/09/3-tips-for-zend-studio-8-eclipse.html#comments</comments>
		<pubDate>Wed, 14 Sep 2011 06:02:44 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[PHP Tips & Tutorials]]></category>
		<category><![CDATA[Programming Tips & Insights]]></category>
		<category><![CDATA[Web Applications & Online Software]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2011/09/3-tips-for-zend-studio-8-eclipse.html</guid>
		<description><![CDATA[I coded a lot in Zend Studio 5.5.1, the gold old version that’s insanely popular because it made it so easy to code in PHP. As PHP evolves, ZS 5.5.1 gradually falls behind of the edge and it simply becomes imperative that you switch to the latest version of Zend Studio, the 8. The IDE [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I coded a lot in Zend Studio 5.5.1, the gold old version that’s insanely popular because it made it so easy to code in PHP. As PHP evolves, ZS 5.5.1 gradually falls behind of the edge and it simply becomes imperative that you switch to the latest version of <a href="http://www.zend.com/products/studio/">Zend Studio</a>, the 8.</p>

<p>The IDE is built on <a href="http://www.eclipse.org/">Eclipse</a>, which I have never used before. It’s great but one still needs some time to learn the curves before he or she can jump in and swim like a whale. Today I gave it a test drive and have some tips to share with you when you are just starting out with Zend Studio 8.</p>
<h2>1. Change Default Character Encoding</h2>
<p>Before you create your project or editing any existing PHP files, you may need to change the default encoding of the Zend Studio Workspace, or make sure it is what you usually work in.</p>
<p>By default, the encoding is that of the container (your operating system). I’m using a Chinese Windows 7 so the default encoding is GBK and it is everything but good because I primarily develop English projects.</p>
<p>For North America users, the default encoding should be ISO-8859-1. If you open up a file that’s encoded in UTF8 without changing the encoding accordingly, you may <a href="http://www.dotvoid.com/2008/10/two-weeks-with-zend-studio-for-eclipse/">end up screwing up the file</a>. And <a href="http://forums.zend.com/viewtopic.php?f=59&amp;t=16388">another victim</a>.</p>
<p>To change the default encoding of Zend Studio: <strong>Windows</strong> –&gt; <strong>Preferences</strong> –&gt; <strong>General</strong> –&gt; <strong>Workspace</strong> –&gt; <strong>Text file encoding</strong>, switch to “Other” and select the encoding you normally use.</p>
<h2>2. Display Function Parameters Hint on Demand</h2>
<p>In 5.5.1, function parameters hint is automatically displayed when you place the cursor in the parentheses. However in 8, the hint is only automatically shown after you immediately finish typing the function name. When the focus moves away or you click anywhere else in the window, the hint disappears and if you don’t know the correct shortcut keys, you wouldn’t be able to get it back.</p>
<p>After a few searches, I found out the key combinations to get the parameters hint re-appear: <strong>Alt + Shift + /</strong></p>
<p><a href="http://files.zend.com/help/Zend-Studio/working_with_code_assist.htm#MiniTOCBookMark4">Some pages</a> say it’s <strong>Ctrl + Shift + Space</strong> but it didn’t work out for me. Maybe it’s a version thing?</p>
<h2>3. Display Potential Function Candidates / Auto-complete Function Names</h2>
<p>Along with the previous tip, this one is pretty important in modern IDE because they are essential in boosting one’s coding productivity. Can’t live without them.</p>
<p>When you are typing the function name, Zend Studio would guess what you mean and display a list of possible candidates for you to choose from.</p>
<p>If you want it to appear again, just place the cursor on the function name and use <strong>Alt + /</strong> to make Zend Studio makes a guess again.</p>
<h2>4. Display All Shortcut Key Combinations</h2>
<p>You can use a lot of shortcut keys in Zend Studio 8 to make things happen quickly and intuitively, just press <strong>Ctrl + Shift + L</strong> to bring up the key map to see the full list. Here&#8217;s a list of the commonly used commands:</p>
<p><a href="http://www.kavoir.com/wp-content/uploads/2011/09/zend-studio-keymap.png" rel="lightbox[2336]" title="4 Tips for Zend Studio 8 (Eclipse)"><img class="alignnone size-full wp-image-2345" src="http://www.kavoir.com/wp-content/uploads/2011/09/zend-studio-keymap.png" alt="zend studio 8 key assist - commonly used commands" width="600" height="738" /></a><br />
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2009/06/work-around-zend-studio-5-5-php-class-object-method-auto-complete-problem.html" rel="bookmark" title="June 20, 2009">Work Around Zend Studio 5.5 PHP Class / Object / Method Auto-complete Problem</a></li>
<li><a href="http://www.kavoir.com/2011/02/www-gmail-com.html" rel="bookmark" title="February 20, 2011">www.gmail.com &#8211; Tips</a></li>
<li><a href="http://www.kavoir.com/2009/06/php-change-array-key-case-all-array-keys-to-lowercase-or-uppercase.html" rel="bookmark" title="June 2, 2009">PHP: Change Array Key Case &#8211; All Array Keys to Lowercase or Uppercase</a></li>
<li><a href="http://www.kavoir.com/2009/08/one-simple-way-to-encrypt-obfuscate-hide-or-protect-your-php-code.html" rel="bookmark" title="August 4, 2009">One Simple Way to Encrypt, Obfuscate, Hide or Protect Your PHP Code</a></li>
<li><a href="http://www.kavoir.com/2012/01/customize-wordpress-post-editor-css-styles.html" rel="bookmark" title="January 19, 2012">Customize WordPress Post Editor CSS Styles</a></li>
</ul>
<p><!-- Similar Posts took 5.506 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2011/09/3-tips-for-zend-studio-8-eclipse.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP: Display Files and Sub-directories of A Directory Recursively as A Tree</title>
		<link>http://www.kavoir.com/2011/05/php-explore-display-contents-of-directory-recursively.html</link>
		<comments>http://www.kavoir.com/2011/05/php-explore-display-contents-of-directory-recursively.html#comments</comments>
		<pubDate>Tue, 10 May 2011 07:35:23 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2011/05/php-explore-display-contents-of-directory-recursively.html</guid>
		<description><![CDATA[Given a directory, how to display the contents (directories and files under it) of it recursively and exhaustively? Here’s the code: $dir = '/path/to/directory'; // without trailing slash, can be absolute paths such as '/home/jim/public_html' or relative paths such as 'samples' getDirContents($dir); function getDirContents($dir) { if (is_dir($dir)) { $dirs = explode('/', $dir); $last_dir = $dirs[count($dirs) [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Given a directory, how to display the contents (directories and files under it) of it recursively and exhaustively? Here’s the code:<span id="more-2239"></span></p>
<pre><code>$dir = '/path/to/directory'; // without trailing slash, can be absolute paths such as '/home/jim/public_html' or relative paths such as 'samples'

<strong>getDirContents</strong>($dir);

function <strong>getDirContents</strong>($dir) {
	if (is_dir($dir)) {
		$dirs = explode('/', $dir);
		$last_dir = $dirs[count($dirs) - 1];
		echo '&lt;strong&gt;'.$last_dir.'&lt;/strong&gt;';
	    if ($dh = opendir($dir)) {
	    	echo '&lt;ul&gt;';
	        while (($file = readdir($dh)) !== false) {
	        	if ($file == '.' || $file == '..') {} else {
		        	echo '&lt;li&gt;';
		        	if (<strong>is_dir</strong>($dir.'/'.$file)) {
		        		<strong>getDirContents</strong>($dir.'/'.$file);
		        	} else {
		        		echo $file;
		        	}
		        	echo '&lt;/li&gt;';
	        	}
	        }
	        echo '&lt;/ul&gt;';
	        closedir($dh);
	    }
	}
	return false;
}</code></pre>
<p>Recursively, the function <strong>getDirContents</strong>() explores every entry in the directory. If the entry is a file, it simply prints it; if it is a directory, it opens another subroutine of itself to explore that directory; and so forth, until every branch and sub-branches, etc. are all printed out.<br />
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2010/08/how-to-get-all-the-sub-directories-of-a-given-directory-in-php.html" rel="bookmark" title="August 1, 2010">How to get all the sub-directories of a given directory in PHP?</a></li>
<li><a href="http://www.kavoir.com/2010/05/simplest-php-hit-counter-or-download-counter-count-the-number-of-times-of-access-visits-or-downloads.html" rel="bookmark" title="May 19, 2010">Simplest PHP Hit Counter or Download Counter &ndash; Count the Number of Times of Access (Page Views or File Downloads)</a></li>
<li><a href="http://www.kavoir.com/2009/04/php-reading-a-file-into-a-string-or-reading-the-file-into-an-array.html" rel="bookmark" title="April 22, 2009">PHP: Reading a File into a String or Reading the File into an Array</a></li>
<li><a href="http://www.kavoir.com/2009/09/linux-check-how-much-disk-storage-each-directory-takes-up-disk-usage-command-du.html" rel="bookmark" title="September 2, 2009">Linux: Check how much disk storage each directory takes up (Disk Usage command &#8211; du)</a></li>
<li><a href="http://www.kavoir.com/2009/04/php-open-remote-file.html" rel="bookmark" title="April 22, 2009">PHP: Open Remote File</a></li>
</ul>
<p><!-- Similar Posts took 4.106 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2011/05/php-explore-display-contents-of-directory-recursively.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Checklist slides to learn the new features in PHP 5.3 with examples</title>
		<link>http://www.kavoir.com/2010/12/checklist-slides-to-learn-new-features-in-php-5-3.html</link>
		<comments>http://www.kavoir.com/2010/12/checklist-slides-to-learn-new-features-in-php-5-3.html#comments</comments>
		<pubDate>Fri, 10 Dec 2010 14:31:45 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2010/12/checklist-slides-to-learn-new-features-in-php-5-3.html</guid>
		<description><![CDATA[One of my old Internet friends Brad made a very nice online slide that introduces to you some of the exciting new features of PHP 5.3. I&#8217;m most interested in namespace that would make coding in a large project and code reuse much easier, especially for people who find keeping naming conventions a challenge in [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>One of my old Internet friends Brad made a very nice online slide that introduces to you some of the exciting new features of PHP 5.3. I&#8217;m most interested in namespace that would make coding in a large project and code reuse much easier, especially for people who find keeping naming conventions a challenge in the team.</p>

<p>Here&#8217;s the original post and slide: <a href="http://bradley-holt.com/2010/11/new-features-in-php-53/">http://bradley-holt.com/2010/11/new-features-in-php-53/</a></p>
<div id="__ss_5827399" style="width: 425px;"><strong><a title="New Features in PHP 5.3" href="http://www.slideshare.net/bradley.holt/new-features-in-php-53">New Features in PHP 5.3</a></strong><object id="__sse5827399" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="355" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="src" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=newfeaturesinphp5-3-101118145553-phpapp01&amp;stripped_title=new-features-in-php-53&amp;userName=bradley.holt" /><param name="name" value="__sse5827399" /><param name="allowfullscreen" value="true" /><embed id="__sse5827399" type="application/x-shockwave-flash" width="425" height="355" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=newfeaturesinphp5-3-101118145553-phpapp01&amp;stripped_title=new-features-in-php-53&amp;userName=bradley.holt" name="__sse5827399" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<div style="padding-right: 0px; padding-left: 0px; padding-bottom: 12px; padding-top: 5px;">View more <a href="http://www.slideshare.net/">presentations</a> from <a href="http://www.slideshare.net/bradley.holt">Bradley Holt</a>.</div>
</div>
<p>All the new stuff and concepts are presented in a practical manner that&#8217;s extremely straightforward. Programmers should find them a breeze to crunch.<br />
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2011/07/microsoft-office-365-review-screenshots-what-will-you-get.html" rel="bookmark" title="July 15, 2011">Microsoft Office 365 Review &#038; Screenshots &#8211; What will you get?</a></li>
<li><a href="http://www.kavoir.com/2009/08/one-simple-way-to-encrypt-obfuscate-hide-or-protect-your-php-code.html" rel="bookmark" title="August 4, 2009">One Simple Way to Encrypt, Obfuscate, Hide or Protect Your PHP Code</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/2010/03/use-relative-protocol-url-address-to-automatically-determine-web-address-protocol-http-or-https.html" rel="bookmark" title="March 6, 2010">Use Relative Protocol URL Address to Automatically Determine Web Address Protocol (HTTP or HTTPS)</a></li>
<li><a href="http://www.kavoir.com/2010/09/free-php-business-directory-script.html" rel="bookmark" title="September 29, 2010">Free PHP Business Directory Script</a></li>
</ul>
<p><!-- Similar Posts took 9.132 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2010/12/checklist-slides-to-learn-new-features-in-php-5-3.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PHP: Get Human Readable Time from Seconds</title>
		<link>http://www.kavoir.com/2010/09/php-get-human-readable-time-from-seconds.html</link>
		<comments>http://www.kavoir.com/2010/09/php-get-human-readable-time-from-seconds.html#comments</comments>
		<pubDate>Wed, 29 Sep 2010 08:56:26 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2010/09/php-get-human-readable-time-from-seconds.html</guid>
		<description><![CDATA[Linux timestamp is a number of seconds from the Epoch of Linux, large number of seconds. When you are counting the time interval between 2 times or 2 dates, the result is usually in seconds as well. Understandably, it’s everything but user friendly to just present the number of seconds to the users, e.g. 153297 [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Linux timestamp is a number of seconds from the Epoch of Linux, large number of seconds. When you are counting the time interval between 2 times or 2 dates, the result is usually in seconds as well. Understandably, it’s everything but user friendly to just present the number of seconds to the users, e.g. 153297 s since last visit.</p>

<p>To display the time interval in a human readable format instead of in seconds, you can use the following function:</p>
<pre><code>function getHumanTime($s) {
	$m = $s / 60;
	$h = $s / 3600;
	$d = $s / 86400;
	if ($m &gt; 1) {
		if ($h &gt; 1) {
			if ($d &gt; 1) {
				return (int)$d.' d';
			} else {
				return (int)$h.' h';
			}
		} else {
			return (int)$m.' m';
		}
	} else {
		return (int)$s.' s';
	}
}</code></pre>
<p>This is what I used for <a href="http://www.usabledatabases.com/">Usable Databases</a> to display length of time since the user’s last visit to a certain page. d indicates day, h hour, m minute and s seconds. This function requires a number of seconds as input and convert it into human readable time periods such as x hours or x days.</p>
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2009/06/php-mysql-calculate-number-of-days-between-2-dates-or-now.html" rel="bookmark" title="June 13, 2009">PHP, MySQL: Calculate Number of Days between 2 Dates or Number of Hours, Minutes and Seconds</a></li>
<li><a href="http://www.kavoir.com/2010/07/php-delay-function-that-halt-code-execution-temporarily-and-then-resume-it.html" rel="bookmark" title="July 18, 2010">PHP: Delay Function that Halt Code Execution Temporarily and Then Resume It</a></li>
<li><a href="http://www.kavoir.com/2010/04/javascript-confirmation-warning-before-leaving-or-navigating-away-from-a-page.html" rel="bookmark" title="April 27, 2010">JavaScript: Confirmation / Warning before Leaving or Navigating Away from a Page</a></li>
<li><a href="http://www.kavoir.com/2011/08/html-make-a-page-refresh-every-xx-seconds.html" rel="bookmark" title="August 28, 2011">HTML: Make a Page Refresh Every xx Seconds</a></li>
<li><a href="http://www.kavoir.com/2009/09/mysql-select-and-show-all-mysql-users.html" rel="bookmark" title="September 3, 2009">MySQL: Select and Show all MySQL Users</a></li>
</ul>
<p><!-- Similar Posts took 4.456 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2010/09/php-get-human-readable-time-from-seconds.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Regular Expression for Date and Time Strings</title>
		<link>http://www.kavoir.com/2010/09/regular-expression-for-date-and-time-strings.html</link>
		<comments>http://www.kavoir.com/2010/09/regular-expression-for-date-and-time-strings.html#comments</comments>
		<pubDate>Wed, 29 Sep 2010 08:40:19 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[PHP Tips & Tutorials]]></category>
		<category><![CDATA[Regular Expression Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2010/09/regular-expression-for-date-and-time-strings.html</guid>
		<description><![CDATA[Often we need the users to enter a valid string of date or time in the form. But how do you validate the strings with regular expressions? In PHP, you can use these functions and regular expressions. RegExp and function to validate against date string: // Default: YYYY-MM-DD function isDate($subject, $separator = '-') { return [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Often we need the users to enter a valid string of date or time in the form. But how do you validate the strings with regular expressions? In PHP, you can use these functions and regular expressions.<span id="more-2048"></span></p>
<h4>RegExp and function to validate against date string:</h4>
<pre><code>// Default: <strong>YYYY-MM-DD</strong>
function isDate($subject, $separator = '-') {
	return preg_match('@^\d{4}'.$separator.'(0[1-9]|1[0-2])'.$separator.'(0[1-9]|1[0-9]|2[0-9]|3[0-1])$@', $subject);
}</code></pre>
<h4>RegExp and function to validate against time string:</h4>
<pre><code>// Default: <strong>HH:MM:SS</strong>
function isTime($subject, $separator = ':') {
	return preg_match('@^(0[1-9]|1[0-9]|2[0-4])'.$separator.'(0[1-9]|[1-5][0-9])'.$separator.'(0[1-9]|[1-5][0-9])$@', $subject);
}</code></pre>
<p>If you need to validate against a different format, just change the $separator.</p>
<p>Now that you have the functions to validate date and time, you can combine them to verify date time strings such as <strong>2016-04-30 18:19:05</strong>:</p>
<pre><code>function isDateTime($subject) {
	$subject_array = explode(' ', $subject);
	if (count($subject_array) == 2) {
		return isDate($subject_array[0]) &amp;&amp; :isTime($subject_array[1]) || $subject == '0000-00-00 00:00:00';
	}
	return false;
}</code></pre>
<p>At <a href="http://www.formkid.com/">Form Kid</a>, these are functions I use for fields that need validation of the date and time.<br />
<h3>Related Posts:</h3>
<ul class="similar-posts">
<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>
<li><a href="http://www.kavoir.com/2009/12/php-regular-expression-matching-input-subject-string-length-limit.html" rel="bookmark" title="December 12, 2009">PHP: Subject String Length Limit of Regular Expression Matching Functions</a></li>
<li><a href="http://www.kavoir.com/2010/03/php-check-or-validate-url-and-email-addresses-an-easier-way-than-regular-expressions-the-filter_var-function.html" rel="bookmark" title="March 4, 2010">PHP: Check or Validate URL and Email Addresses &ndash; an Easier Way than Regular Expressions, the filter_var() Function</a></li>
<li><a href="http://www.kavoir.com/2009/04/php-getting-the-current-date-and-time.html" rel="bookmark" title="April 22, 2009">PHP: Getting the Current Date and Time</a></li>
<li><a href="http://www.kavoir.com/2009/07/instantly-boost-sql-query-efficiency-of-regexp-or-rlike-by-2000.html" rel="bookmark" title="July 23, 2009">Instantly Boost SQL Query Efficiency of REGEXP or RLIKE by 2000%</a></li>
</ul>
<p><!-- Similar Posts took 6.790 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2010/09/regular-expression-for-date-and-time-strings.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Regular Expressions for Natural Numbers or Positive Integers (1, 2, 3, &#8230;), Negative Integers and Non-negative Integers</title>
		<link>http://www.kavoir.com/2010/09/regular-expression-for-natural-numbers-or-positive-integers-1-2-3-11-12.html</link>
		<comments>http://www.kavoir.com/2010/09/regular-expression-for-natural-numbers-or-positive-integers-1-2-3-11-12.html#comments</comments>
		<pubDate>Wed, 29 Sep 2010 07:18:30 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[PHP Tips & Tutorials]]></category>
		<category><![CDATA[Regular Expression Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2010/09/regular-expression-for-natural-numbers-or-positive-integers-1-2-3-11-12.html</guid>
		<description><![CDATA[When I&#8217;m developing the online form creator that enables the users to create form fields that accept only certain type of numbers, I need to verify if a given string is a valid natural number such as 1, 2, 3, 4, …. I’m writing the code / functions in PHP but you can literally use [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>When I&#8217;m developing the <a href="http://www.formkid.com/">online form creator</a> that enables the users to create form fields that accept only certain type of numbers, I need to verify if a given string is a valid natural number such as 1, 2, 3, 4, …. I’m writing the code / functions in PHP but you can literally use the regular expression in other programming languages as well. I use the following function to distinguish strings if they are natural numbers or positive integers.</p>

<pre><code>function isNaturalNumber($subject) {
	return preg_match('|<strong>^[1-9][0-9]*$</strong>|', $subject);
}</code></pre>
<p>You can add for a leading plus sign as well:</p>
<pre><code>^+?[1-9][0-9]*$</code></pre>
<h3>Regular Expression for Negative Integers?</h3>
<p>Negative integers are –1, –2, –3, …. Just add a minus sign before the regular expression for positive integers:</p>
<pre><code>^-[1-9][0-9]*$</code></pre>
<h3>Regular Expression for Non-negative Integers?</h3>
<p>That is, 0, 1, 2, 3, 4, …. By a little help of the isNaturalNumber function, you can use this function to check if a string is a legal non-negative integer:</p>
<pre><code>function isNonNegativeInteger($subject) {
	// @^(0|[1-9][0-9]*)$@
	if ($subject == '0' || isNaturalNumber($subject)) {
		return true;
	}
}</code></pre>
<p>Or if you insist on using a regular expression:</p>
<pre><code>function isNonNegativeInteger($subject) {
	return preg_match('@<strong>^(0|[1-9][0-9]*)$</strong>@', $subject);
}</code></pre>
<h3>PHP functions to check if a string is a valid integer?</h3>
<p>Just use the above functions in combination or the native <strong>is_integer</strong>() function of PHP.</p>
<pre><code>function isInteger() {
	return isNegativeInteger($subject) || isNonNegativeInteger($subject);
}</code></pre>
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2010/09/regular-expression-for-date-and-time-strings.html" rel="bookmark" title="September 29, 2010">Regular Expression for Date and Time Strings</a></li>
<li><a href="http://www.kavoir.com/2009/12/php-regular-expression-matching-input-subject-string-length-limit.html" rel="bookmark" title="December 12, 2009">PHP: Subject String Length Limit of Regular Expression Matching Functions</a></li>
<li><a href="http://www.kavoir.com/2010/12/a-small-mistake-in-a-regular-expression-caused-connection-to-reset.html" rel="bookmark" title="December 4, 2010">A small mistake in a regular expression caused connection to reset &ndash; (.+)+</a></li>
<li><a href="http://www.kavoir.com/2009/04/php-number-format-function-to-format-numbers-in-php-integer-or-float.html" rel="bookmark" title="April 23, 2009">PHP: Number Format Function to Format Numbers in PHP (Integer or Float)</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>
</ul>
<p><!-- Similar Posts took 2.973 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2010/09/regular-expression-for-natural-numbers-or-positive-integers-1-2-3-11-12.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP: True empty() function to check if a string is empty or zero in length</title>
		<link>http://www.kavoir.com/2010/09/php-true-empty-function-to-check-if-a-string-is-empty-or-zero-in-length.html</link>
		<comments>http://www.kavoir.com/2010/09/php-true-empty-function-to-check-if-a-string-is-empty-or-zero-in-length.html#comments</comments>
		<pubDate>Wed, 29 Sep 2010 07:11:16 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2010/09/php-true-empty-function-to-check-if-a-string-is-empty-or-zero-in-length.html</guid>
		<description><![CDATA[The strange thing is that the native empty() function of PHP treats a string of ‘0’ as empty: $str = '0'; echo empty($str) ? 'empty' : 'non-empty'; And it will output &#8216;empty&#8217;. Therefore if you need to examine if a string is truly an empty string with zero length, you have to use: echo strlen($str) [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>The strange thing is that the native empty() function of PHP treats a string of ‘0’ as empty:</p>

<pre><code>$str = '0';
echo empty($str) ? 'empty' : 'non-empty';</code></pre>
<p>And it will output &#8216;empty&#8217;. Therefore if you need to examine if a string is truly an empty string with zero length, you have to use:</p>
<pre><code>echo strlen($str) == 0 ? 'empty' : 'non-empty';</code></pre>
<p>Or you can use this function:</p>
<pre><code>function isNonEmpty($subject) {
	return !empty($subject) || is_numeric($subject);
}</code></pre>
<p>Which checks if the input string $subject is a numeric value (which makes it non-empty) or if it’s non-empty with empty() function when it’s not a numeric value.</p>
<h3>Related Posts:</h3>
<ul class="similar-posts">
<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/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/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/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>
<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>
</ul>
<p><!-- Similar Posts took 3.002 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2010/09/php-true-empty-function-to-check-if-a-string-is-empty-or-zero-in-length.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP: Checking Text Strings against Reserved or Censored Words</title>
		<link>http://www.kavoir.com/2010/09/php-checking-text-strings-against-reserved-or-censored-words.html</link>
		<comments>http://www.kavoir.com/2010/09/php-checking-text-strings-against-reserved-or-censored-words.html#comments</comments>
		<pubDate>Mon, 27 Sep 2010 05:56:03 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[Anti Spam Tips & Tricks]]></category>
		<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2010/09/php-checking-text-strings-against-reserved-or-censored-words.html</guid>
		<description><![CDATA[I created a free online web form builder a while back and since it went well in search engine rankings, spammers and phishers found it and started to use it creating forms to collect email account usernames and passwords through phishing attempts. I’ve got to do something before my host closes down my site because [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I created a <a href="http://www.formkid.com">free online web form builder</a> a while back and since it went well in search engine rankings, spammers and phishers found it and started to use it creating forms to collect email account usernames and passwords through phishing attempts. I’ve got to do something before my host closes down my site because of all the complaints and alerts from security department of the universities. They’ve got good reasons. I’m hosting all the phishing forms.</p>

<p>Phishers tend to use URL slugs that include words such as ‘admin’, ‘webmail’ or ‘account’ so that the form seems authoritative at first glance. After they have <a href="http://www.formkid.com/">signed up</a>, they will create forms with fields labeled ‘Password’ or something. So what I’m going to do is to list all such words as reserved words and prohibit the users from doing anything with them.</p>
<p>A function will be needed to examine a subject string against an array of reserved words that will be censored when users use them as input. Listed is a my function:</p>
<pre><code>public static function isStringLegal($subjectString = '', $disallowedWords = array()) {
	$alphabetSubject = <strong>preg_replace</strong>('|[^a-zA-Z]+|', '', $subjectString);
	foreach ($disallowedWords as $disallowedWord) {
		if (<strong>stripos</strong>($alphabetSubject, $disallowedWord) !== false) {
			return false;
		}
	}
	return true;
}</code></pre>
<p>The PHP function <strong>stripos</strong>() returns a numeric value if it finds $disallowedWord in $alphabetSubject, case-insensitive. If it fails to find anything, it returns false.</p>
<p>A sample disallowed words list:</p>
<pre><code>$slugDisallowedWords = array(
	'formkid',
	'kavoir',
	'mail',
	'admin',
	'account',
	'password'
);</code></pre>
<p>The disallowed words list can only contain alphabet letters. If you need a phrase such as ‘no way’, you have to add it in the array as ‘noway’. This is to prevent illegal attempts to add any word or phrase in manners such as ‘<strong>a-d-m-i-n</strong>’ or ‘<strong>Pa_ss Word</strong>’. All the non-alphabet letters / characters are first gotten rid of and then the deprived string which contains only alphabet letters are checked against each word in the disallowed words list.</p>
<h3>Related Posts:</h3>
<ul class="similar-posts">
<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/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/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/2009/06/javascript-split-and-divide-text-string-by-a-delimiter.html" rel="bookmark" title="June 16, 2009">JavaScript: Split and Divide Text String by A Delimiter</a></li>
</ul>
<p><!-- Similar Posts took 4.887 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2010/09/php-checking-text-strings-against-reserved-or-censored-words.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to create / generate .htpasswd password with PHP dynamically?</title>
		<link>http://www.kavoir.com/2010/09/how-to-create-generate-htpasswd-password-with-php-dynamically.html</link>
		<comments>http://www.kavoir.com/2010/09/how-to-create-generate-htpasswd-password-with-php-dynamically.html#comments</comments>
		<pubDate>Sat, 18 Sep 2010 05:42:13 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[Information Security]]></category>
		<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2010/09/how-to-create-generate-htpasswd-password-with-php-dynamically.html</guid>
		<description><![CDATA[The easy way to add a username and password pair in the .htpasswd file is to use an online password generator tool that converts the clear text password into its hash, a.k.a. the encrypted password. The problem with this approach is that you have to manually create the pair and append it to .htpasswd. Is [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>The easy way to add a username and password pair in the .htpasswd file is to use an online password generator tool that converts the clear text password into its hash, a.k.a. the encrypted password. The problem with this approach is that you have to manually create the pair and append it to .htpasswd. Is there a way to dynamically generate encrypted passwords for .htpasswd in PHP?</p>

<p>According to <a href="http://httpd.apache.org/docs/2.2/misc/password_encryptions.html">http://httpd.apache.org/docs/2.2/misc/password_encryptions.html</a>, we have come up with the following solution:</p>
<pre><code>$pass = 'YourClearTextPasswordString';
$hash = base64_encode(sha1($pass, true));
$encoded = '{SHA}'.$hash;
echo $encoded;</code></pre>
<p>And <code>$encoded</code> is the result we need, which would look something like:</p>
<pre><code>{SHA}hNz9UE9WLiMlzYI+LRtwr0U+DHY=</code></pre>
<p>Suppose the username is ‘manager’ and you can add the following line at the end of your .htpasswd file to make the credentials in effect:</p>
<pre><code>manager:{SHA}hNz9UE9WLiMlzYI+LRtwr0U+DHY=</code></pre>
<p>You can also write / append this to the file by PHP but that’s not covered here.</p>
<p>What’s better, the SHA1 algorithm is much more advanced than DES which most of the online .htpasswd generation tool still uses to generate the hash string of the clear password for you. DES supports only 8 digits and that’s where lengthy passwords fail.</p>
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2009/04/the-secure-way-to-store-passwords-with-php.html" rel="bookmark" title="April 20, 2009">The Secure Way to Store Passwords with PHP</a></li>
<li><a href="http://www.kavoir.com/2009/04/php-what-is-hash-hashing-a-string-generate-hash-of-strings.html" rel="bookmark" title="April 22, 2009">PHP: What is Hash? | Hashing a String | Generate Hash of Strings</a></li>
<li><a href="http://www.kavoir.com/2010/03/just-hashing-is-far-from-enough-how-to-position-against-dictionary-and-rainbow-attacks.html" rel="bookmark" title="March 4, 2010">Just Hashing is Far from Enough for Storing Passwords &ndash; How to Position against Dictionary and Rainbow Table Attacks</a></li>
<li><a href="http://www.kavoir.com/2007/03/essential-ssh.html" rel="bookmark" title="March 29, 2007">Essential SSH &#8211; 19 Linux SSH Commands You Simply Cannot Live Without</a></li>
<li><a href="http://www.kavoir.com/2009/04/paircom-hosting-coupons-and-promo-codes-bonus-paircom-control-panel-screenshots.html" rel="bookmark" title="April 19, 2009">Pair.com Hosting Coupons and Promo Codes (Bonus: Pair.com Control Panel Screenshots)</a></li>
</ul>
<p><!-- Similar Posts took 8.328 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2010/09/how-to-create-generate-htpasswd-password-with-php-dynamically.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Check how much memory your PHP script is using. (PHP script memory usage)</title>
		<link>http://www.kavoir.com/2010/09/check-how-much-memory-your-php-script-is-using-php-script-memory-usage.html</link>
		<comments>http://www.kavoir.com/2010/09/check-how-much-memory-your-php-script-is-using-php-script-memory-usage.html#comments</comments>
		<pubDate>Sat, 18 Sep 2010 02:36:41 +0000</pubDate>
		<dc:creator>Yang Yang</dc:creator>
				<category><![CDATA[PHP Tips & Tutorials]]></category>

		<guid isPermaLink="false">http://www.kavoir.com/2010/09/check-how-much-memory-your-php-script-is-using-php-script-memory-usage.html</guid>
		<description><![CDATA[Depending on the web server software you use, your PHP script will be consuming significantly different amount of memory (RAM). If you are using Apache without proper optimization, the simplest request that does nothing but returns a status code will need 150kB of memory. Multiply this by 2000 visits per day and by 10 sites [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Depending on the web server software you use, your <a href="http://www.kavoir.com/2009/06/best-php-books-for-learning-php-and-mysql.html">PHP</a> script will be consuming significantly different amount of memory (RAM). If you are using <a href="http://www.kavoir.com/category/manage-your-own-server/apache-web-server">Apache</a> without proper optimization, the simplest request that does nothing but returns a status code will need 150kB of memory. Multiply this by 2000 visits per day and by 10 sites in a single Linux VPS box, you will have some serious OOM (Out Of Memory) problems.</p>

<p>However if you are using simplistic web server software such as Lighttpd, the situation will get a lot better. But you would still like some improvements to your PHP script itself. So does one first know how much memory a PHP script consumes at run time?</p>
<p>The answer is the <a href="http://php.net/manual/en/function.memory-get-peak-usage.php">memory_get_peak_usage</a>() function. At the end of your PHP script (footer script for a PHP site, you get the idea), put this line:</p>
<pre><code>echo memory_get_peak_usage();</code></pre>
<p>Or you can write the data down in a text file:</p>
<pre><code>file_put_contents('mu.txt', memory_get_peak_usage());</code></pre>
<p>The output is in bytes. Better yet, you can record down the URL request, HTTP request type and memory usage in the mu.txt file so that you can examine it regularly to make adjustments to your server and PHP scripts:</p>
<pre><code>$mu = fopen('mu.txt', 'a');
fwrite($mu, $_SERVER['REQUEST_URI'].', '.$_SERVER['REQUEST_METHOD'].', '.memory_get_peak_usage().&quot;\n&quot;);</code></pre>
<h3>Related Posts:</h3>
<ul class="similar-posts">
<li><a href="http://www.kavoir.com/2009/04/php-open-remote-file.html" rel="bookmark" title="April 22, 2009">PHP: Open Remote File</a></li>
<li><a href="http://www.kavoir.com/2008/04/one-ssi-directive-to-save-all-programming-muggles-effort-and-time.html" rel="bookmark" title="April 1, 2008">One SSI directive to save all programming muggle&#8217;s effort and time</a></li>
<li><a href="http://www.kavoir.com/2010/04/css-how-to-write-css-rules-to-detect-or-target-chrome-safari-or-opera-browsers-only.html" rel="bookmark" title="April 1, 2010">CSS: How to write CSS rules to detect or target Chrome, Safari or Opera browsers only?</a></li>
<li><a href="http://www.kavoir.com/2009/04/php-reading-a-file-into-a-string-or-reading-the-file-into-an-array.html" rel="bookmark" title="April 22, 2009">PHP: Reading a File into a String or Reading the File into an Array</a></li>
<li><a href="http://www.kavoir.com/2011/12/php-store-array-in-file-read-write-arrays-in-file.html" rel="bookmark" title="December 22, 2011">PHP: Store Array in File &#8211; Read / Write Arrays in File</a></li>
</ul>
<p><!-- Similar Posts took 2.773 ms --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kavoir.com/2010/09/check-how-much-memory-your-php-script-is-using-php-script-memory-usage.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

