<?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>ViralPatel.net &#187; PHP</title> <atom:link href="http://viralpatel.net/blogs/category/php/feed" rel="self" type="application/rss+xml" /><link>http://viralpatel.net/blogs</link> <description>Tutorials, Java, J2EE, Struts, AJAX, JavaScript, CSS, Web 2.0, MySQL, Articles</description> <lastBuildDate>Tue, 24 Jan 2012 13:45:10 +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>WAMP Server not getting started problem</title><link>http://viralpatel.net/blogs/2223/wamp-server-not-getting-started-problem</link> <comments>http://viralpatel.net/blogs/2223/wamp-server-not-getting-started-problem#comments</comments> <pubDate>Tue, 22 Nov 2011 04:09:12 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[server error]]></category> <category><![CDATA[skype]]></category> <category><![CDATA[WAMP]]></category> <category><![CDATA[webserver]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/2223</guid> <description><![CDATA[I was trying to start WAMP server on my local machine and strangely it was not getting started! Everytime I tried to click &#8220;Start All Services&#8221; it just ignored it. I checked Windows Logs under Event Viewer: Control Panel > Administrative Tools > Event Viewer > Windows Logs > Application It seems the Apache service [...]]]></description> <content:encoded><![CDATA[<p><a href="http://viralpatel.net/blogs/wp-content/uploads/2009/09/wamp5_logo.gif"><img src="http://viralpatel.net/blogs/wp-content/uploads/2009/09/wamp5_logo.gif" alt="wamp server logo" title="wamp server logo" width="152" height="144" class="alignright size-full wp-image-1754" /></a>I was trying to start WAMP server on my local machine and strangely it was not getting started! Everytime I tried to click &#8220;Start All Services&#8221; it just ignored it.</p><p>I checked Windows Logs under Event Viewer:</p><p><strong>Control Panel > Administrative Tools > Event Viewer > Windows Logs > Application</strong></p><p>It seems the Apache service was not getting started and following log was getting printed.</p><pre class="brush: xml; gutter: false; title: ; notranslate">
The Apache service named  reported the following error:
&gt;&gt;&gt; Unable to open logs
</pre><p>Whenever the webserver is not getting started the first culprit is to see if the default http port (80) is already in use by some other service.</p><p>Well the guess is correct in this case. <strong>Skype</strong> was the culprit! By default, Skype tries to use port 80 (http) and 443 (https) for incoming connections. Disable this option in skype and your WAMP server is all set to go.</p><p>In Skype, goto <strong>Tools > Options&#8230; > Advanced > Connection</strong> and uncheck the checkbox which says <em>&#8220;Use Port 80 and 443 as alternatives for incoming connections&#8221;</em></p><p><img src="http://viralpatel.net/blogs/wp-content/uploads/2011/11/skype-port-80-443-incoming-connection.png" alt="skype-port-80-443-incoming-connection" title="skype-port-80-443-incoming-connection" width="547" height="401" class="aligncenter size-full wp-image-2227" /></p><p>Restart Skype after doing above changes and restart WAMPserver. Your WAMP is up again!! <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/09/how-to-setup-multiple-virtual-hosts-in-wamp.html" title="How to: Setup Multiple Virtual Hosts in WAMP Server">How to: Setup Multiple Virtual Hosts in WAMP Server</a></li><li><a href="http://viralpatel.net/blogs/2009/08/running-multiple-instance-apache-tomcat-single-server.html" title="Run Multiple Instance of Apache Tomcat in Single Server">Run Multiple Instance of Apache Tomcat in Single Server</a></li><li><a href="http://viralpatel.net/blogs/2009/08/turn-off-wordpress-image-thumbnails.html" title="Save Webserver Space by turning off Image Thumbnails in Wordpress">Save Webserver Space by turning off Image Thumbnails in Wordpress</a></li><li><a href="http://viralpatel.net/blogs/2009/02/handling-session-timeout-server-errors-http-ajax-session-ajax-session-timeout-problem.html" title="Handling Session timeout &#038; other server http errors in AJAX">Handling Session timeout &#038; other server http errors in AJAX</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2223/wamp-server-not-getting-started-problem/feed</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Dynamic unread count Favicon in PHP</title><link>http://viralpatel.net/blogs/2011/01/dynamic-unread-count-favicon-in-php.html</link> <comments>http://viralpatel.net/blogs/2011/01/dynamic-unread-count-favicon-in-php.html#comments</comments> <pubDate>Wed, 26 Jan 2011 10:23:10 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[dynamic elements]]></category> <category><![CDATA[favicon]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2140</guid> <description><![CDATA[Gmail has just launched small but really useful feature in Gmail Labs. Dynamic Favicon showing unread email counts directly in your browser tab icon. If your browser window has lots and lots of tabs open at anytime, this might be really a wonderful feature that lets user know of any unread item. Here is a [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2011/01/dynamic-favicon-gmail.png" alt="Dynamic Unread count favicon in PHP" title="dynamic-favicon-gmail" width="239" height="173" class="alignright size-full wp-image-2141" />Gmail <a rel="nofollow" target="_blank" href="http://techcrunch.com/2011/01/25/gmail-favicon/">has just launched</a> small but really useful feature in Gmail Labs. Dynamic Favicon showing unread email counts directly in your browser tab icon. If your browser window has lots and lots of tabs open at anytime, this might be really a wonderful feature that lets user know of any unread item.</p><p>Here is a small and powerful script in PHP that lets you create your own <strong>Dynamic favicon</strong>. We will use PHP GD library to manipulate the favicon image and add text into it.</p><p>Below is the simple script that reads a favicon image add add some text character on it.</p><p><em>File: favicon.php</em></p><pre class="brush: php; title: ; notranslate">
&lt;?php

//Read the favicon template from favicon.png
//file from current directory
$im = imagecreatefrompng(&quot;favicon.png&quot;);
//$im = imagecreatefromjpg(&quot;favicon.jpg&quot;);   //using this function to load favicon of jpeg type
//$im = imagecreatefrombmp(&quot;favicon.bmp&quot;); //using this function to load favicon of bmp type

/* Read the character which needs to be added in favicon from
 * get request
 */
if(isset($_GET['char']) &amp;&amp; !empty($_GET['char'])) {
	$string = $_GET['char'];
} else {
	/* If no character is specified; add some default value */
	$string = 'V';
}

/* background color for the favicon */
$bg = imagecolorallocate($im, 255, 255, 255);

/* foreground (font) color for the favicon */
$black = imagecolorallocate($im, 0, 0, 0);

/* Write the character in favicon
 * arguements: image, fontsize, x-coordinate,
 *				y-coordinate, characterstring, color
 */
imagechar($im, 2, 5, 1, $string, $black);

header('Content-type: image/png');

imagepng($im);

?&gt;
</pre><p>The above code is pretty much self explanatory. We read a character from GET request and add it into the favicon image. Note here that we are using a template favicon image which me modify. You can place any favicon of your choice near favicon.php file.</p><h2>Download Source Code</h2><p><a href="http://viralpatel.net/blogs/demo/php/dynamic-favicon/dynafavicon.zip">Click here to download complete source code (ZIP, 3kb)</a></p><h2>Online Demo</h2><p><a target="_blank" href="http://viralpatel.net/blogs/demo/php/dynamic-favicon/">Click here to view online demo</a></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/12/password-protect-your-webpages-using-htaccess.html" title="Password Protect your webpages using htaccess">Password Protect your webpages using htaccess</a></li><li><a href="http://viralpatel.net/blogs/2009/11/php-fatal-error-time-htaccess.html" title="PHP Fatal Error Maximum Execution Time Issue &#038; htaccess">PHP Fatal Error Maximum Execution Time Issue &#038; htaccess</a></li><li><a href="http://viralpatel.net/blogs/2009/09/how-to-setup-multiple-virtual-hosts-in-wamp.html" title="How to: Setup Multiple Virtual Hosts in WAMP Server">How to: Setup Multiple Virtual Hosts in WAMP Server</a></li><li><a href="http://viralpatel.net/blogs/2009/08/server-php-variable-php-self-server-request-uri.html" title="Knowing $_SERVER PHP Variable in a better way">Knowing $_SERVER PHP Variable in a better way</a></li><li><a href="http://viralpatel.net/blogs/2009/06/restful-web-service-tutorial-introduction-rest-restful.html" title="RESTful Web Service tutorial: An Introduction for beginners">RESTful Web Service tutorial: An Introduction for beginners</a></li><li><a href="http://viralpatel.net/blogs/2009/06/21-very-useful-htaccess-tips-tricks.html" title="21 very useful htaccess tips &#038; tricks">21 very useful htaccess tips &#038; tricks</a></li><li><a href="http://viralpatel.net/blogs/2009/06/smarty-templates-creating-smarty-custom-functions.html" title="Smarty templates: Creating smarty custom functions">Smarty templates: Creating smarty custom functions</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/01/dynamic-unread-count-favicon-in-php.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Password Protect your webpages using htaccess</title><link>http://viralpatel.net/blogs/2010/12/password-protect-your-webpages-using-htaccess.html</link> <comments>http://viralpatel.net/blogs/2010/12/password-protect-your-webpages-using-htaccess.html#comments</comments> <pubDate>Sun, 26 Dec 2010 15:37:57 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[apache]]></category> <category><![CDATA[htaccess]]></category> <category><![CDATA[security]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2120</guid> <description><![CDATA[Recently a serious security flaw was discovered on one of my webpage where a folder which was intended to be accessed just by admin was open for access to anyone. I somehow ignored that folder as it was lying there for years. Fortunately before those sensitive information could compromised, one of the site follower sent [...]]]></description> <content:encoded><![CDATA[<p>Recently a serious security flaw was discovered on one of my webpage where a folder which was intended to be accessed just by admin was open for access to anyone. I somehow ignored that folder as it was lying there for years.</p><p>Fortunately before those sensitive information could compromised, one of the site follower sent me an email describing the serious flaw in security. I acted promptly and secured those folders with passwords.</p><p>It is always a good idea to add password protection to any of the folders / webpages of your website if you want restricted access on them.</p><p>Here I will describe an easiest way to add password protection to your webpages.</p><h2>1. Easy and Automated Way</h2><p>First, let us see the easy way of adding password protection to a webpage. In the CPanel of your sites hosting server you can configure folders and add passwords to those folders/pages.</p><p>Login to your CPanel and scroll down to see the Security box<br /> <img src="http://img.viralpatel.net/2010/12/cpanel-security-block.png" alt="cpanel-security-block" title="cpanel-security-block" width="501" height="105" class="aligncenter size-full wp-image-2121" /></p><p>Select <strong>Password Protect Directories</strong> under <strong>Security</strong>. It will open up a page where all the folders will be listed.<br /> <img src="http://img.viralpatel.net/2010/12/security-password-protection-cpanel.png" alt="security-password-protection-cpanel" title="security-password-protection-cpanel" width="490" height="232" class="aligncenter size-full wp-image-2122" /></p><p>Click on any of the folder name where you want to add password protection. If you want to add password to a subfolder like /myweb/mysecretfolder/ than click on the folder icon and it will list all the subfolders under it. Once you select a folder, it will ask for username / password and foldername. Check the following snapshot.<br /> <img src="http://img.viralpatel.net/2010/12/set-password-cpanel.png" alt="set-password-cpanel" title="set-password-cpanel" width="456" height="443" class="aligncenter size-full wp-image-2123" /></p><p>Select the checkbox &#8220;Password protect this directory&#8221; and also provide a name for protected directory. The directory name that you provide here will be used in the password prompt dialog box when user tries to access this folder.</p><p>And that&#8217;s it. All you have to do is to try accessing the secure folder from internet. As soon as the secure folder is requested, user will be asked to enter username/password. If user is successfully authenticated the content will be served. Otherwise an Unauthorized error (401) is generated.<br /> <img src="http://img.viralpatel.net/2010/12/password-dialog-box-apache.png" alt="password-dialog-box-apache" title="password-dialog-box-apache" width="576" height="169" class="aligncenter size-full wp-image-2124" /></p><p>The above method that we used to protect any webpage using CPanel&#8217;s Password Protect Directories option uses Apache&#8217;s Basic authentication mechanism. Behind the scene it generates 2 files, first one a password file which stores the username/encrypted password pairs for all authorized users and second file is .htaccess file which contains the rule for authentication, the path to the password file and other details.</p><h2>2. Manual Way</h2><p>As mentioned earlier the above (Easy and Automated) method generates the password file and rules in the htaccess file which set the authentication mechanism on the folder. Let us see the manual way of doing this. The advantage is that things are clear and you know exactly what is going on in the background. You also get some additional functionality such as password protecting single or multiple files.</p><p>There are two things we need to do here.</p><ol><li>Generate the password file</li><li>Add authentication rules in htaccess file</li></ol><h3>1. Generate the password file</h3><p>All the username/passwords that we need to give access to the folder goes in a file. The format of this file is simple, you have <username>:<encrypted password> pairs on each line for each user.<br /> For example:</p><pre class="brush: xml; title: ; notranslate">
john:#343Jjdsk&amp;^#nsnsdj
jil:$%24334nke43$*#@4m
</pre><p>The trick here is to generate the encrypted passwords for this file. Fortunately we lot of online tools that can be used to generate these encrypted values. Use any of the below tools to generate your encrypted passwords.</p><ul><li><a rel="nofollow" target="_blank" href="http://www.4webhelp.net/us/password.php">4WebHelp&#8217;s online .htpasswd encryption tool</a></li><li><a rel="nofollow" target="_blank" href="http://shop.alterlinks.com/htpasswd/htpasswd.php">Alterlinks .htaccess password generator</a></li></ul><p>Save the username/password in file <strong>.htpasswd</strong>. We need to protect this file so keep it anywhere but not in <strong>public_html</strong> or web root. Most of the hosting providers a folder .htpasswds under your user home directory. Store the file <strong>.htpasswd</strong> in <strong>.htpasswds</strong> folder. If you dont have this folder then you can store the file anywhere. The apache mostly restricts the direct access to files starting with .ht. So feel free to put the file at location of your choice.</p><p>For this example lets assume the location of password file is: <em>/home/username/.htpasswds/.htpasswd</em></p><h3>2. Add authentication rules in htaccess file</h3><p>Now as we have created the password file, let us add the htaccess rules for authentication the htaccess file.<br /> Open the .htaccess file inside the folder that you want to protect with password. Create one if not already exists. Copy following code into it.</p><pre class="brush: xml; title: ; notranslate">
AuthName &quot;My Secret Folder&quot;
AuthType Basic
AuthUserFile /home/username/.htpasswds/.htpasswd
Require valid-user
</pre><p>Change the AuthName to anything you like to be shown in password dialog box when this folder is accessed. Also change the AuthUserFile to the full path of password file that we created in step 1.</p><p>And that&#8217;s it. Try to access the folder from internet and apache will prompt you for username/password. If successfully authenticated, user will be served with appropriate content.</p><h4>Protecting a single file</h4><p>To password protect just a single file in a folder, use the following .htaccess file:</p><pre class="brush: xml; title: ; notranslate">
AuthUserFile /home/username/.htpasswds/.htpasswd
AuthType Basic
AuthName &quot;My Secret Page&quot;

&lt;Files &quot;mypage.html&quot;&gt;
  Require valid-user
&lt;/Files&gt;
</pre><p>This will password protect just the <em>mypage.html</em> file in the folder where you put the <em>.htaccess</em> file.</p><h4>Protecting multiple files</h4><p>To password protect more than one file in the same folder, just create more <code><Files></Files></code> blocks within the same .htaccess file &#8211; for example:</p><pre class="brush: xml; title: ; notranslate">
AuthUserFile /home/username/.htpasswds/.htpasswd
AuthType Basic
AuthName &quot;My Secret Page&quot;

&lt;Files &quot;mypage.html&quot;&gt;
  Require valid-user
&lt;/Files&gt;

&lt;Files &quot;mysecondpage.html&quot;&gt;
  Require valid-user
&lt;/Files&gt;
</pre><h2>Disabling password protection for localhost</h2><p>You may have setup a website in production and a development environment on your localhost. While it is desirable to have password protection for production version, but at same time it is very annoying if on localhost (dev environment) it keeps on asking for password everytime. Add following rule in your <em>.htaccess </em>file and the server will never ask for password if you are running the website on localhost.</p><pre class="brush: xml; title: ; notranslate">
Require valid-user
Allow from 127.0.0.1
Satisfy Any
</pre><p>For more info: <a rel="nofollow" target="_blank" href="http://httpd.apache.org/docs/2.0/mod/core.html#satisfy">http://httpd.apache.org/docs/2.0/mod/core.html#satisfy</a></p><h2>Disabling password protection for subfolder</h2><p>It may happen that sometime we have a requirement where to add password protection to a folder but not for a particuler subfolder.<br /> - /mysecret/* should be protected by password<br /> - /mysecret/mypublic/* should be open to all</p><p>This can be achieved by creating a new .htaccess file in subfolder (mypublic) and add following line into it.</p><pre class="brush: xml; title: ; notranslate">
Satisfy Any
</pre><p>I hope things are clear from above tutorial. If you think you have a better way of doing this, share your experiences <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/06/21-very-useful-htaccess-tips-tricks.html" title="21 very useful htaccess tips &#038; tricks">21 very useful htaccess tips &#038; tricks</a></li><li><a href="http://viralpatel.net/blogs/2009/11/php-fatal-error-time-htaccess.html" title="PHP Fatal Error Maximum Execution Time Issue &#038; htaccess">PHP Fatal Error Maximum Execution Time Issue &#038; htaccess</a></li><li><a href="http://viralpatel.net/blogs/2009/02/compress-php-css-js-javascript-optimize-website-performance.html" title="Compress PHP, CSS, JavaScript(JS) &#038; Optimize website performance.">Compress PHP, CSS, JavaScript(JS) &#038; Optimize website performance.</a></li><li><a href="http://viralpatel.net/blogs/2011/07/google-plus-homepage-redirect.html" title="Redirect your homepage /+ URL to your Google + profile">Redirect your homepage /+ URL to your Google + profile</a></li><li><a href="http://viralpatel.net/blogs/2011/01/dynamic-unread-count-favicon-in-php.html" title="Dynamic unread count Favicon in PHP">Dynamic unread count Favicon in PHP</a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html" title="Calculate Free Disk Space in Java using Apache Commons IO">Calculate Free Disk Space in Java using Apache Commons IO</a></li><li><a href="http://viralpatel.net/blogs/2010/01/simplest-virus-fork-bomb.html" title="Simplest Virus – Fork Bomb">Simplest Virus – Fork Bomb</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2010/12/password-protect-your-webpages-using-htaccess.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>PHP Fatal Error Maximum Execution Time Issue &amp; htaccess</title><link>http://viralpatel.net/blogs/2009/11/php-fatal-error-time-htaccess.html</link> <comments>http://viralpatel.net/blogs/2009/11/php-fatal-error-time-htaccess.html#comments</comments> <pubDate>Mon, 30 Nov 2009 13:18:48 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[htaccess]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1918</guid> <description><![CDATA[Lot of times it happen that we get some weird error in PHP. One of such errors is a Fatal Error that usually occurs when Uploading big files in PHP. This error has to do something with the Maximum timeout setting. When we upload a large file it may happen that the timeout occurs and [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/11/php-upload-big-files-htaccess.png" alt="php-upload-big-files-htaccess" title="php-upload-big-files-htaccess" width="248" height="129" class="alignleft size-full wp-image-1919" />Lot of times it happen that we get some weird error in PHP. One of such errors is a Fatal Error that usually occurs when Uploading big files in PHP.</p><p>This error has to do something with the Maximum timeout setting. When we upload a large file it may happen that the timeout occurs and result in failure. This is commonly seen while upgrading plugins in WordPress.</p><p>So how to avoid these errors? Well, htaccess comes to rescue in such problems.<br /> <strong>Related:</strong> <a target="_new" href="http://viralpatel.net/blogs/2009/06/21-very-useful-htaccess-tips-tricks.html">21 Very Useful htaccess Tips &#038; Tricks</a></p><p>The default value of file upload size for most of the webservers is 2MB. This limit a user from uploading large files to the server. Add following lines in your .htaccess file to change the default size for upload. If .htaccess file is not present in your root directory, create one.</p><pre class="brush: bash; title: ; notranslate">
#Set the Maximum Input time
php_value max_input_time 200

#Maximum size allowed in Post method
php_value post_max_size 20M

#Set the Maximum Execution Time for Script
php_value max_execution_time 200

#Set the Maximum Upload Filesize
php_value upload_max_filesize 15M
</pre><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/12/password-protect-your-webpages-using-htaccess.html" title="Password Protect your webpages using htaccess">Password Protect your webpages using htaccess</a></li><li><a href="http://viralpatel.net/blogs/2009/06/21-very-useful-htaccess-tips-tricks.html" title="21 very useful htaccess tips &#038; tricks">21 very useful htaccess tips &#038; tricks</a></li><li><a href="http://viralpatel.net/blogs/2009/02/compress-php-css-js-javascript-optimize-website-performance.html" title="Compress PHP, CSS, JavaScript(JS) &#038; Optimize website performance.">Compress PHP, CSS, JavaScript(JS) &#038; Optimize website performance.</a></li><li><a href="http://viralpatel.net/blogs/2011/07/google-plus-homepage-redirect.html" title="Redirect your homepage /+ URL to your Google + profile">Redirect your homepage /+ URL to your Google + profile</a></li><li><a href="http://viralpatel.net/blogs/2011/01/dynamic-unread-count-favicon-in-php.html" title="Dynamic unread count Favicon in PHP">Dynamic unread count Favicon in PHP</a></li><li><a href="http://viralpatel.net/blogs/2009/11/avoid-image-hotlinking-bandwidth-theft-website.html" title="How To Avoid Image Hotlinking &#038; Bandwidth Theft In Your Website">How To Avoid Image Hotlinking &#038; Bandwidth Theft In Your Website</a></li><li><a href="http://viralpatel.net/blogs/2009/09/how-to-setup-multiple-virtual-hosts-in-wamp.html" title="How to: Setup Multiple Virtual Hosts in WAMP Server">How to: Setup Multiple Virtual Hosts in WAMP Server</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/11/php-fatal-error-time-htaccess.html/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>How to: Setup Multiple Virtual Hosts in WAMP Server</title><link>http://viralpatel.net/blogs/2009/09/how-to-setup-multiple-virtual-hosts-in-wamp.html</link> <comments>http://viralpatel.net/blogs/2009/09/how-to-setup-multiple-virtual-hosts-in-wamp.html#comments</comments> <pubDate>Wed, 09 Sep 2009 09:21:44 +0000</pubDate> <dc:creator>Gaurav Patel</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[WAMP]]></category> <category><![CDATA[webserver]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1752</guid> <description><![CDATA[WAMP, or Windows Apache MySQL PHP has been a very server for lots of PHP developers who uses Windows environment. These are mainly the freelancers who mostly uses laptops as their local development machines. Whatever may be the reason, but when you use WAMP, it becomes difficult to manage multiple application installed in same root. [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/09/wamp5_logo.gif" alt="wamp5_logo" title="wamp5_logo" width="152" height="144" class="alignleft size-full wp-image-1754" />WAMP, or Windows Apache MySQL PHP has been a very server for lots of PHP developers who uses Windows environment. These are mainly the freelancers who mostly uses laptops as their local development machines. Whatever may be the reason, but when you use WAMP, it becomes difficult to manage multiple application installed in same root.</p><p>For example while we use WAMP as a development environment, we have different client specific projects residing in different folders in the root and whenever these projects needs to be uploaded in production environment, the absolute paths has to be manually change.</p><p>What if we want to have different root folder for each client? Well, this is possible in WAMP using Virtual  Hosts. Let us see how to setup the virtual hosts.</p><p>First we need to modify two files to create virtual hosts:</p><ol><li><strong>hosts file</strong>: This file is in the c:\windows\system32\drivers\etc\ folder</li><li><strong>httpd.conf file</strong>: This is in your Apache install&#8217;s &#8216;conf&#8217; folder &#8211; e.g. c:\wamp\Apache2\conf\httpd.conf</li></ol><p>The hosts files has entries which maps IP Address to a name. By default the name &#8220;localhost&#8221; is mapped to 127.0.0.1 IP Address.</p><pre class="brush: xml; title: ; notranslate">
127.0.0.1        localhost
</pre><p>Now what we have to do is to simply add few more entries per client in this file. You may want to use your clients domain name as mapping key (e.g. viralpatel.local)</p><pre class="brush: xml; title: ; notranslate">
127.0.0.1        client1.local
</pre><p>Add as many entries as you want in hosts file. Whenever you enter &#8220;client1.local&#8221; in your web browser, windows will first look into hosts file and if it gets the corresponding entry, it sends the request to that IP Address.</p><p>Now we have to change httpd.conf. Open the httpd.conf file and search for something like:</p><pre class="brush: xml; title: ; notranslate">
'DocumentRoot 'c:/wamp/www''
</pre><p>Add following code after the &#8216;DocumentRoot &#8220;c:/wamp/www&#8221;&#8216;  entry in  httpd.conf file.</p><pre class="brush: xml; title: ; notranslate">
NameVirtualHost 127.0.0.1
&lt;VirtualHost 127.0.0.1&gt;
    ServerName localhost
    DocumentRoot 'C:\wamp\www'
&lt;/VirtualHost&gt;
&lt;VirtualHost 127.0.0.1&gt;
    ServerName myclient.local
    DocumentRoot 'C:\wamp\www\ClientsMyClient'
&lt;/VirtualHost&gt;
</pre><p>And now you need to modify the code a bit to match the server name with the one from your ‘hosts’ file and the DocumentRoot with your clients file path.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2223/wamp-server-not-getting-started-problem" title="WAMP Server not getting started problem">WAMP Server not getting started problem</a></li><li><a href="http://viralpatel.net/blogs/2011/01/dynamic-unread-count-favicon-in-php.html" title="Dynamic unread count Favicon in PHP">Dynamic unread count Favicon in PHP</a></li><li><a href="http://viralpatel.net/blogs/2010/12/password-protect-your-webpages-using-htaccess.html" title="Password Protect your webpages using htaccess">Password Protect your webpages using htaccess</a></li><li><a href="http://viralpatel.net/blogs/2009/11/php-fatal-error-time-htaccess.html" title="PHP Fatal Error Maximum Execution Time Issue &#038; htaccess">PHP Fatal Error Maximum Execution Time Issue &#038; htaccess</a></li><li><a href="http://viralpatel.net/blogs/2009/08/server-php-variable-php-self-server-request-uri.html" title="Knowing $_SERVER PHP Variable in a better way">Knowing $_SERVER PHP Variable in a better way</a></li><li><a href="http://viralpatel.net/blogs/2009/08/running-multiple-instance-apache-tomcat-single-server.html" title="Run Multiple Instance of Apache Tomcat in Single Server">Run Multiple Instance of Apache Tomcat in Single Server</a></li><li><a href="http://viralpatel.net/blogs/2009/08/turn-off-wordpress-image-thumbnails.html" title="Save Webserver Space by turning off Image Thumbnails in Wordpress">Save Webserver Space by turning off Image Thumbnails in Wordpress</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/09/how-to-setup-multiple-virtual-hosts-in-wamp.html/feed</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>Knowing $_SERVER PHP Variable in a better way</title><link>http://viralpatel.net/blogs/2009/08/server-php-variable-php-self-server-request-uri.html</link> <comments>http://viralpatel.net/blogs/2009/08/server-php-variable-php-self-server-request-uri.html#comments</comments> <pubDate>Wed, 26 Aug 2009 07:38:02 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[$_SERVER]]></category> <category><![CDATA[php variable]]></category> <category><![CDATA[Tutorial]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1692</guid> <description><![CDATA[$_SERVER array in PHP is very useful in getting lot of information about the PHP script in execution as well as the server/request details. $_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. Following are few very useful attributes of [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/08/php-elephant-logo.jpg" alt="php-elephant-logo" title="php-elephant-logo" width="180" height="116" class="alignleft size-full wp-image-1693" />$_SERVER array in PHP is very useful in getting lot of information about the PHP script in execution as well as the server/request details.  $_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server.</p><p>Following are few very useful attributes of $_SERVER array:</p><h2>$_SERVER['PHP_SELF']</h2><p>This is the filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar  would be /test.php/foo.bar. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. However, unlike $_SERVER['SCRIPT_NAME'], it provides additional path information like $_SERVER['REQUEST_URI'] when the actual php file is present in the path. So when the <strong>$_SERVER['REQUEST_URI']</strong> is /index.php/big/directory/ then $_SERVER['PHP_SELF'] will be /index.php/big/directory/.<br /> However if all the URI&#8217;s under http://www.example.com/ is mapped to http://www.example.com/index.php, then, for example, http://www.example.com/abc/def will return /index.php like <strong>$_SERVER['SCRIPT_NAME']</strong>. Note that $_SERVER['REQUEST_URI'] data is ignored for this request.</p><p>$_SERVER['PHP_SELF'] is supported on all platforms.</p><h2>$_SERVER['SERVER_ADDR']</h2><p>Gives you the IP address of server on which the current script is executing. Thus for printing IP address of server use following code snippet.</p><pre class="brush: php; title: ; notranslate">
&lt;?php echo &quot;Server IP Address is $_SERVER['SERVER_ADDR']&quot; ?&gt;
</pre><h2>$_SERVER['REMOTE_ADDR']</h2><p>$_SERVER['REMOTE_ADDR'] returns the IP address from which the user is viewing the current page. REMOTE_ADDR will not written correct IP address if the client is behind a proxy. In that case use the script mention in this tutorial: <a href="http://viralpatel.net/blogs/2009/05/15-very-useful-php-code-snippets-for-php-developers.html">PHP Code Snippet</a></p><h2>$_SERVER['REQUEST_URI']</h2><p>The actual URI used in HTTP protocol (after GET or POST) to make the request. For example if you access this site with the following command:<br /> <code><br /> GET / HTTP/1.0<br /> Host: viralpatel.net/blogs/<br /> </code><br /> Then $_SERVER['REQUEST_URI'] will be /.<br /> However is you access the same page using:<br /> <code><br /> GET /index.php HTTP/1.0<br /> Host: viralpatel.net/blogs/<br /> </code><br /> Then $_SERVER['REQUEST_URI'] will be <code>/index.php</code>.<br /> Although $_SERVER['SCRIPT_NAME'] and $_SERVER['PHP_SELF'] will be /index.php in both cases. $_SERVER['REQUEST_URI'] is not supported on IIS (with or without SSL).</p><h2>$_SERVER[''HTTP_USER_AGENT']</h2><p>Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: <code>Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586)</code>.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/06/restful-web-service-tutorial-introduction-rest-restful.html" title="RESTful Web Service tutorial: An Introduction for beginners">RESTful Web Service tutorial: An Introduction for beginners</a></li><li><a href="http://viralpatel.net/blogs/2009/05/15-very-useful-php-code-snippets-for-php-developers.html" title="15 very useful PHP code snippets for PHP developers">15 very useful PHP code snippets for PHP developers</a></li><li><a href="http://viralpatel.net/blogs/2009/02/file-upload-in-php-file-upload-php-file-upload-tutorial-securing-things.html" title="Tutorial: File upload in PHP, Securing the things.">Tutorial: File upload in PHP, Securing the things.</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li><li><a href="http://viralpatel.net/blogs/2011/01/spring-roo-implement-masterdetail-forms.html" title="How to implement Master/Detail forms using Spring Roo">How to implement Master/Detail forms using Spring Roo</a></li><li><a href="http://viralpatel.net/blogs/2011/01/dynamic-unread-count-favicon-in-php.html" title="Dynamic unread count Favicon in PHP">Dynamic unread count Favicon in PHP</a></li><li><a href="http://viralpatel.net/blogs/2011/01/first-play-framework-gae-siena-application-tutorial-example.html" title="Your first Play! &#8211; GAE &#8211; Siena application: Tutorial with Example">Your first Play! &#8211; GAE &#8211; Siena application: Tutorial with Example</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/08/server-php-variable-php-self-server-request-uri.html/feed</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>RESTful Web Service tutorial: An Introduction for beginners</title><link>http://viralpatel.net/blogs/2009/06/restful-web-service-tutorial-introduction-rest-restful.html</link> <comments>http://viralpatel.net/blogs/2009/06/restful-web-service-tutorial-introduction-rest-restful.html#comments</comments> <pubDate>Wed, 24 Jun 2009 09:07:19 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[Web 2.0]]></category> <category><![CDATA[rest]]></category> <category><![CDATA[rest php]]></category> <category><![CDATA[restful]]></category> <category><![CDATA[restful java]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[webservices]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1448</guid> <description><![CDATA[REST is a term coined by Roy Fielding in his Ph.D. dissertation to describe an architecture style of networked systems. REST is an acronym standing for Representational State Transfer. Representational State Transfer(REST), a software architecture style used in developing stateless web services. While this style may be used to describe any distributed framework that uses [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/06/restful-web-services-rest.gif" alt="restful-web-services-rest" title="restful-web-services-rest" width="334" height="239" class="alignleft size-full wp-image-1450" />REST is a term coined by <a href="http://en.wikipedia.org/wiki/Roy_Fielding">Roy Fielding</a> in his Ph.D. dissertation to describe an architecture style of networked systems. <strong>REST</strong> is an acronym standing for <strong>Representational State Transfer</strong>. Representational State Transfer(REST), a software architecture style used in developing <strong>stateless web services</strong>. While this style may be used to describe any distributed framework that uses a simple protocol for data transmission and no other additional data transfer rules, the most common use of REST is on on the Web with HTTP being the only protocol used here. In <strong>REST</strong> each service (called &#8220;resource&#8221; in REST) is viewed as resource identified by a URL, and the only operations allowed are the HTTP &#8211; <strong>GET (Read), PUT (Update), POST(Create) and DELETE (Delete)</strong>. You can find this style similar in SQL, thinking of a resource as equivalent to a Table. The main features and constraints of REST architectural style are:</p><ul><li><strong>Client-Server</strong>: A clear separation concerns is the reason behind this constraint. Separating concerns between the Client and Server helps improve portability in the Client and Scalability of the server components.</li><li><strong>Stateless</strong>: All REST resources are required to be stateless. The idea is that the application would be resilient enough to work between server restarts. However, it is not uncommon to see some RESTful web services save states between requests.</li><li><strong>Caching</strong>: Caching is allowed, however it is required that &#8220;response to a request be implicitly or explicitly labeled as cacheable or non-cacheable&#8221;</li><li>As there is no interface definition (like in SOAP), it becomes mandatory for a Client and Server to have a mutual understanding of the messages being transmitted between them.</li></ul><p>Given that every resource in a RESTful service is represented by a URL, it is easy to write a client for such a web service.</p><p>A lot of companies these days (including Amazon and Yahoo!) are exposing their web services in the form of REST resources. At a high level REST is pretty easy to understand, all you’re doing is exposing a web service in the form of a URL. Users can then query this URL, through HTTP methods like GET and POST. REST calls generally return some type of XML or Object Encoding like JSON.</p><h2>REST in PHP</h2><p>An example would be <a rel="nofollow" href="http://developer.yahoo.com/maps/rest/V1/geocode.html">Yahoo!’s Geocoding API</a>, with the following URL:</p><pre class="brush: xml; title: ; notranslate">

http://api.local.yahoo.com/MapsService/V1/geocode?appid=YahooDemo&#038;street=701+First+Street&#038;city=Sunnyvale&#038;state=CA
</pre><p>You will get:</p><pre class="brush: xml; title: ; notranslate">
&lt;Result precision=&quot;address&quot;&gt;
   &lt;Latitude&gt;37.416384&lt;/Latitude&gt;
   &lt;Longitude&gt;-122.024853&lt;/Longitude&gt;
   &lt;Address&gt;701 FIRST AVE&lt;/Address&gt;
   &lt;City&gt;SUNNYVALE&lt;/City&gt;
   &lt;State&gt;CA&lt;/State&gt;
   &lt;Zip&gt;94089-1019&lt;/Zip&gt;
   &lt;Country&gt;US&lt;/Country&gt;
&lt;/Result&gt;
</pre><p>So Yahoo! exposes the Geocode URL and allows you to query this resource using URL parameters like appid and street. Dynamically building your URL to query a given resource is OK, generally that’s what people do, like the following:</p><pre class="brush: php; title: ; notranslate">
$base = 'http://xml.amazon.com/onca/xml3';
$query_string = &quot;&quot;;

$params = array( 'ManufacturerSearch' =&gt; &quot;O'Reilly&quot;,
    'mode'  =&gt; 'books',
    'sort'  =&gt; '+salesrank',
    'page'  =&gt; 1,
    'type'  =&gt; 'lite',
    'f'     =&gt; 'xml',
    't'     =&gt; 'trachtenberg-20' ,
    'dev-t' =&gt; 'XXXXXXXXXXXXXX' ,
);

foreach ($params as $key =&gt; $value) {
    $query_string .= &quot;$key=&quot; . urlencode($value) . &quot;&amp;&quot;;
}

$url = &quot;$base?$query_string&quot;;
$output = file_get_contents($url);
</pre><p>You may want to see the pear package <a rel="nofollow" href="http://pear.php.net/package/HTTP_Request/">HTTP Request</a> for making REST calls, which among many things supports GET/POST/HEAD/TRACE/PUT/DELETE, basic authentication, proxy, proxy authentication, SSL, file uploads and more. Using this package, I got started on a simple wrapper class called RESTclient, which gives intuitive support for making REST resource calls.</p><p>So if we are going to use RESTclient to call the Geocode API above, following will be the source code:</p><pre class="brush: php; title: ; notranslate">
&lt;?php

require_once &quot;RESTclient.php&quot;;

$rest = new RESTclient();

$inputs = array();
$inputs[&quot;appid&quot;] = &quot;YahooDemo&quot;;
$inputs[&quot;street&quot;] = &quot;701 First Street&quot;;
$inputs[&quot;city&quot;] = &quot;Sunnyvale&quot;;
$inputs[&quot;state&quot;] = &quot;CA&quot;;

$url = &quot;http://api.local.yahoo.com/MapsService/V1/geocode/&quot;
$rest-&gt;createRequest(&quot;$url&quot;,&quot;POST&quot;,$inputs);
$rest-&gt;sendRequest();
$output = $rest-&gt;getResponse();
echo $output;

?&gt;
</pre><h2>REST in Java</h2><p>You may want to call the REST web service from Java. Following is the code for a simple Web Service client for the flickr web services interface.</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.rest;

import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class FlickrClient {
	public static void main(String[] args) {
		String flickrURL = &quot;http://api.flickr.com/services/rest/?method=flickr.test.echo&amp;name=value&amp;api_key=[yourflickrkey]&quot;;

		try {
			SocketAddress addr = new InetSocketAddress(&quot;[proxy]&quot;, 9090);
			Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
			URL u = new URL(&quot;http://api.flickr.com/services/rest/?method=flickr.test.echo&amp;name=value&amp;api_key=[yourflickrkey]&quot;);
			HttpURLConnection uc = (HttpURLConnection) u.openConnection(proxy);
			uc.setRequestProperty(&quot;Accept&quot;, &quot;*/*&quot;);
			uc.setRequestProperty(&quot;Accept-Charset&quot;, &quot;ISO-8859-1,utf-8;q=0.7,*;q=0.7&quot;);
			uc.setRequestProperty(&quot;Accept-Language&quot;, &quot;en-us,en;q=0.5&quot;);
			uc.setRequestProperty(&quot;Keep-Alive&quot;, &quot;300&quot;);
			uc.setRequestProperty(&quot;ucection&quot;, &quot;keep-alive&quot;);
			String proxyUser = &quot;[netUserId]&quot;;
			String proxyPassword = &quot;[netPassword]&quot;;
			uc.setRequestProperty(&quot;Proxy-Authorization&quot;, &quot;NTLM &quot; + new sun.misc.BASE64Encoder().encode((proxyUser + &quot;:&quot; + proxyPassword).getBytes()));

			DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = docBuilder.parse(uc.getInputStream());

			System.out.println(doc.getDocumentElement().getTagName());

			System.out.println();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
</pre><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/10/inner-classes-in-java.html" title="Inner classes in Java, the mystery within.">Inner classes in Java, the mystery within.</a></li><li><a href="http://viralpatel.net/blogs/2009/08/server-php-variable-php-self-server-request-uri.html" title="Knowing $_SERVER PHP Variable in a better way">Knowing $_SERVER PHP Variable in a better way</a></li><li><a href="http://viralpatel.net/blogs/2009/05/15-very-useful-php-code-snippets-for-php-developers.html" title="15 very useful PHP code snippets for PHP developers">15 very useful PHP code snippets for PHP developers</a></li><li><a href="http://viralpatel.net/blogs/2009/02/file-upload-in-php-file-upload-php-file-upload-tutorial-securing-things.html" title="Tutorial: File upload in PHP, Securing the things.">Tutorial: File upload in PHP, Securing the things.</a></li><li><a href="http://viralpatel.net/blogs/2008/12/create-jar-file-in-java-eclipse.html" title="Create JAR file in Java &#038; Eclipse">Create JAR file in Java &#038; Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2008/12/implement-ldap-authentication-in-tomcat-jboss-server-for-java-app.html" title="Implement LDAP authentication in Tomcat &#038; JBoss server for Java app">Implement LDAP authentication in Tomcat &#038; JBoss server for Java app</a></li><li><a href="http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html" title="Tutorial: Creating Struts application in Eclipse">Tutorial: Creating Struts application in Eclipse</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/06/restful-web-service-tutorial-introduction-rest-restful.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Smarty templates: Creating smarty custom functions</title><link>http://viralpatel.net/blogs/2009/06/smarty-templates-creating-smarty-custom-functions.html</link> <comments>http://viralpatel.net/blogs/2009/06/smarty-templates-creating-smarty-custom-functions.html#comments</comments> <pubDate>Wed, 03 Jun 2009 08:43:17 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[Smarty]]></category> <category><![CDATA[agots]]></category> <category><![CDATA[smarty custom functions]]></category> <category><![CDATA[smarty templates]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1355</guid> <description><![CDATA[Yesterday I wrote an article about a php method that can convert normal timestamp into &#8220;x Min Ago&#8221; like timestamps. I will call these type of timestamps an &#8220;agots&#8220;. Although the PHP method is straight forward in converting unix timestamps to agotimestamps, I thought of implementing a custom function in smarty that can be used [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/06/smarty-custom-function.png" alt="smarty-custom-function" title="smarty-custom-function" width="220" height="175" class="alignleft size-full wp-image-1356" />Yesterday <a href="http://viralpatel.net/blogs/2009/06/twitter-like-n-min-sec-ago-timestamp-in-php-mysql.html"><strong>I wrote an article</strong></a> about a php method that can convert normal timestamp into &#8220;x Min Ago&#8221; like timestamps. I will call these type of timestamps an &#8220;<strong>agots</strong>&#8220;. Although the PHP method is straight forward in converting unix timestamps to <strong>agotimestamps</strong>, I thought of implementing a custom function in smarty that can be used anywhere in your smarty template to generate <strong>agots</strong>.</p><p>Let us first see the basics of Smarty Custom Functions.</p><h2>What is Custom Function in Smarty?</h2><p><strong>Smarty</strong> comes with lots of inbuilt functions that can be used in our smarty templates and that provides rich set of APIs that can leveraged for easy creation of UI. Although sometimes we may need to create our own functionality and plug it in smarty so that it can be used across all smarty projects. So we can create our own custom smarty functions. <strong>Custom functions</strong> are nothing but a normal PHP function with a given function name and written in a given filename. We will see in next sections how exactly to write a custom function in smarty.</p><h2>Creating a Custom Function</h2><p>As mentioned in previous section, creating <strong>custom function</strong> in smarty is straightforward. Follow the three steps process and there you have your own <strong>smarty custom function</strong>.</p><h3>Step 1: Name the plugin and add a Header</h3><p>Create an empty PHP file and add a commented header to the PHP file. In our case the custom function name will be <strong>agots</strong>, so following will be the header.</p><pre class="brush: php; title: ; notranslate">
/*
 *     Smarty plugin
 * -------------------------------------------------------------
 * File:     	function.agots.php
 * Type:     	function
 * Name:     	agots
 * Description: This TAG creates a &quot;x minute ago&quot; like timestamp.
 *
 * -------------------------------------------------------------
 * @license GNU Public License (GPL)
 *
 * -------------------------------------------------------------
 * Parameter:
 * - ts     	= the email to fetch the gravatar for (required)
 * -------------------------------------------------------------
 * Example usage:
 *
 * &lt;div&gt;{agots ts=&quot;3434323&quot;} ago &lt;/div&gt;
 */
</pre><p>In above header, the Name: attribute is the name of your custom function and the File: attribute is the file name where you are writing this function.</p><h3>Step 2: Write your PHP custom function</h3><p>Once the header is ready, all you have to do is write the PHP function. In our case we have written <strong>agots</strong> function.<br /> One thing you have to take care here is that all smarty custom function names must start with &#8220;<strong>smarty_function_</strong>&#8220;. Thus our agots function&#8217;s name will be smarty_function_agots. Also all smarty custom functions must be defined with two parameters <code>$params</code> and <code>&#038;$smarty</code>. The parameters that we pass in custom functions can be read through the associative array $params. In our case the parameter will be timestamp (ts) so we read this parameter as <code>$params['ts']</code> in our custom function.</p><pre class="brush: php; title: ; notranslate">
function smarty_function_agots($params, &amp;amp;$smarty) {

	if(!isset($params['ts'])) {
		$smarty-&gt;trigger_error(&quot;gravatar: neither 'email' nor 'default' attribute passed&quot;);
		return;
	}
	//return $params['ts'];
    // array of time period chunks
    $chunks = array(
		array(60 * 60 * 24 * 365 , 'year'),
		array(60 * 60 * 24 * 30 , 'month'),
		array(60 * 60 * 24 * 7, 'week'),
		array(60 * 60 * 24 , 'day'),
		array(60 * 60 , 'hour'),
		array(60 , 'min'),
		array(1 , 'sec'),
    );

    $today = time(); /* Current unix time  */
    $since = $today - $params['ts'];

    // $j saves performing the count function each time around the loop
    for ($i = 0, $j = count($chunks); $i &lt; $j; $i++) {

		$seconds = $chunks[$i][0];
		$name = $chunks[$i][1];

		// finding the biggest chunk (if the chunk fits, break)
		if (($count = floor($since / $seconds)) != 0) {
			break;
		}
	}

	$print = ($count == 1) ? '1 '.$name : &quot;$count {$name}s&quot;;

	if ($i + 1 &lt; $j) {
		// now getting the second item
		$seconds2 = $chunks[$i + 1][0];
		$name2 = $chunks[$i + 1][1];

		// add second item if its greater than 0
		if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
			$print .= ($count2 == 1) ? ', 1 '.$name2 : &quot; $count2 {$name2}s&quot;;
		}
	}
	return $print;
}
</pre><h3>Step 3: Save the custom function in Plugins directory</h3><p>We are ready to deploy our custom function to Smarty. All you have to do is just copy the PHP file function.agots.php to <strong>plugins</strong> directory in smarty installation directory. Just make sure that the name of the plugin file is same as the name specified in file header. The good practice is to have name as function.<custom_function>.php.</p><h2>Calling the custom function</h2><p>To call your new function, you simply reference it by its name within curly brackets. And if the function requires a parameter, like ours does, you’d call it like this:</p><pre class="brush: php; title: ; notranslate">
{agots ts='2451254'}
</pre><p>You may want to pass the value of smarty variable to our custom function.</p><pre class="brush: php; title: ; notranslate">
{agots ts=$myunixtimestamp}
</pre><p>Above is a simple example to create your own custom function in smarty. You may extend this and add your own useful functions.</p><p><em>You may want to bookmark this article and share it with others.</em></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/01/dynamic-unread-count-favicon-in-php.html" title="Dynamic unread count Favicon in PHP">Dynamic unread count Favicon in PHP</a></li><li><a href="http://viralpatel.net/blogs/2010/12/password-protect-your-webpages-using-htaccess.html" title="Password Protect your webpages using htaccess">Password Protect your webpages using htaccess</a></li><li><a href="http://viralpatel.net/blogs/2009/11/php-fatal-error-time-htaccess.html" title="PHP Fatal Error Maximum Execution Time Issue &#038; htaccess">PHP Fatal Error Maximum Execution Time Issue &#038; htaccess</a></li><li><a href="http://viralpatel.net/blogs/2009/09/how-to-setup-multiple-virtual-hosts-in-wamp.html" title="How to: Setup Multiple Virtual Hosts in WAMP Server">How to: Setup Multiple Virtual Hosts in WAMP Server</a></li><li><a href="http://viralpatel.net/blogs/2009/08/server-php-variable-php-self-server-request-uri.html" title="Knowing $_SERVER PHP Variable in a better way">Knowing $_SERVER PHP Variable in a better way</a></li><li><a href="http://viralpatel.net/blogs/2009/06/restful-web-service-tutorial-introduction-rest-restful.html" title="RESTful Web Service tutorial: An Introduction for beginners">RESTful Web Service tutorial: An Introduction for beginners</a></li><li><a href="http://viralpatel.net/blogs/2009/06/21-very-useful-htaccess-tips-tricks.html" title="21 very useful htaccess tips &#038; tricks">21 very useful htaccess tips &#038; tricks</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/06/smarty-templates-creating-smarty-custom-functions.html/feed</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Twitter like N min/sec ago timestamp in PHP/MySQL</title><link>http://viralpatel.net/blogs/2009/06/twitter-like-n-min-sec-ago-timestamp-in-php-mysql.html</link> <comments>http://viralpatel.net/blogs/2009/06/twitter-like-n-min-sec-ago-timestamp-in-php-mysql.html#comments</comments> <pubDate>Tue, 02 Jun 2009 10:48:33 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[live stream]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[php code snippet]]></category> <category><![CDATA[web 3.0]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1337</guid> <description><![CDATA[While working on one of the forum project, I had to print the timestamp of a topic in format &#8220;N Seconds ago&#8221; or &#8220;X minutes ago&#8221;.! The Web 2.0 world have changed the way these dates are displayed. The days are gone when the timestamps were displayed like &#8220;12 Jan 2003 10:50 pm&#8221;!!! A paradigm [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/06/x-min-sec-ago-timestamp.png" alt="x-min-sec-ago-timestamp" title="x-min-sec-ago-timestamp" width="274" height="218" class="alignleft size-full wp-image-1338" />While working on one of the forum project, I had to print the timestamp of a topic in format &#8220;N Seconds ago&#8221; or &#8220;X minutes ago&#8221;.! The Web 2.0 world have changed the way these dates are displayed. The days are gone when the timestamps were displayed like &#8220;12 Jan 2003 10:50 pm&#8221;!!! A paradigm shift have changed the world to more &#8220;Live&#8221; stream based systems. Now the Web pages are not just data wrapped in HTML, but they have became more real with realtime interaction between people. And thus the timestamps also got changed to &#8220;2 mins ago&#8221;, &#8220;5 hours ago&#8221; like formats. This identify more lively the streams and you can visualize them as events happened just minutes ago.</p><h2>Enough Gyan, let&#8217;s see the code&#8230;</h2><p>Following is the PHP function that can be used to convert the timestamp into Twitter like &#8220;X min ago&#8221; format.</p><pre class="brush: php; title: ; notranslate">
/* Works out the time since the entry post, takes a an argument in unix time (seconds)
*/
static public function Timesince($original) {
    // array of time period chunks
    $chunks = array(
	array(60 * 60 * 24 * 365 , 'year'),
	array(60 * 60 * 24 * 30 , 'month'),
	array(60 * 60 * 24 * 7, 'week'),
	array(60 * 60 * 24 , 'day'),
	array(60 * 60 , 'hour'),
	array(60 , 'min'),
	array(1 , 'sec'),
    );

    $today = time(); /* Current unix time  */
    $since = $today - $original;

    // $j saves performing the count function each time around the loop
    for ($i = 0, $j = count($chunks); $i &lt; $j; $i++) {

	$seconds = $chunks[$i][0];
	$name = $chunks[$i][1];

	// finding the biggest chunk (if the chunk fits, break)
	if (($count = floor($since / $seconds)) != 0) {
	    break;
	}
    }

    $print = ($count == 1) ? '1 '.$name : &quot;$count {$name}s&quot;;

    if ($i + 1 &lt; $j) {
	// now getting the second item
	$seconds2 = $chunks[$i + 1][0];
	$name2 = $chunks[$i + 1][1];

	// add second item if its greater than 0
	if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
	    $print .= ($count2 == 1) ? ', 1 '.$name2 : &quot; $count2 {$name2}s&quot;;
	}
    }
    return $print;
}
</pre><p>Input to this function will be timestamp in Unix seconds. If your database table has timestamp field than you can convert it into Unix timestamp by using UNIX_TIMESTAMP () method in MySQL.</p><pre class="brush: sql; title: ; notranslate">
SELECT id, username, UNIX_TIMESTAMP(joined_data) from UserTable;
</pre><p>Update: <a href="http://viralpatel.net/blogs/2009/06/smarty-templates-creating-smarty-custom-functions.html"><strong>Download PHP Smarty template custom function to generate twitter like timestamps.</strong></a></p><p>If you think this little code snippet might be useful in future then feel free to bookmark it and share it.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/05/15-very-useful-php-code-snippets-for-php-developers.html" title="15 very useful PHP code snippets for PHP developers">15 very useful PHP code snippets for PHP developers</a></li><li><a href="http://viralpatel.net/blogs/2009/03/generating-tag-cloud-with-php-mysql.html" title="Generating Tag cloud with PHP and MySQL">Generating Tag cloud with PHP and MySQL</a></li><li><a href="http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html" title="How To Reset MySQL Autoincrement Column">How To Reset MySQL Autoincrement Column</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html" title="Hibernate One To Many XML Mapping Tutorial">Hibernate One To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation" title="Hibernate One To One Annotation Mapping Tutorial">Hibernate One To One Annotation Mapping Tutorial</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/06/twitter-like-n-min-sec-ago-timestamp-in-php-mysql.html/feed</wfw:commentRss> <slash:comments>15</slash:comments> </item> <item><title>Gravatar: Manage your user avatars for free</title><link>http://viralpatel.net/blogs/2009/05/gravatar-manage-your-user-avatars-for-free.html</link> <comments>http://viralpatel.net/blogs/2009/05/gravatar-manage-your-user-avatars-for-free.html#comments</comments> <pubDate>Thu, 28 May 2009 09:31:06 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[avatar]]></category> <category><![CDATA[Gravatar]]></category> <category><![CDATA[Web 2.0]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1333</guid> <description><![CDATA[While working on one of the application, I had to manage users who logged in to the application and manage their details. In order to manage user&#8217;s avatar, I had to create a form where user can upload a picture and this photo will get stored on server. Imagine as a user you have to [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/05/avatar.png" alt="avatar" title="avatar" width="181" height="134" class="alignleft size-medium wp-image-1334" />While working on one of the application, I had to manage users who logged in to the application and manage their details. In order to manage user&#8217;s avatar, I had to create a form where user can upload a picture and this photo will get stored on server.</p><p>Imagine as a user you have to manage this across all the websites where you do login. A good idea is to manage avatar at a single place and all the application that you use can take it from there.</p><p>You can achieve this by logging into <a rel="nofollow" href="http://gravatar.com/"><strong>Gravatar</strong></a>. Gravatar is a free service that let you logged in and manage your avatar. Lot of websites and blogs directly take the avatar from Gravatar. Thus is you comment on a blog like ours and your Gravatar will be displayed directly.</p><p>Gravatar does the mapping of user and avatar on basis of email id. Thus when you do login in Gravatar, it stores your avatar on basis of your email address. Hence whenever you provide your email address while you comment on a blog or login to a website, your avatar is taken from gravatar service by mapping your email address.</p><p>Gravatar enabled comment systems and other plugins are already available in different CMS systems like wordpress, drupal, joomla etc. All you need to do is to install the plugin and enable it and it will take care of the avatars of users.</p><p>You may want to add support to Gravatar on your custom build application/blog. For this all you have to do is to call a URL and it will give you avatar of the user. You have to pass MD5 hash of the email address to this URL. For example following can be the PHP code to generate gravatar from an email address.</p><h2>Integrate Gravatar with PHP</h2><pre class="brush: php; title: ; notranslate">
$email = &quot;someone@somewhere.com&quot;;
$default = &quot;http://www.somewhere.com/homestar.jpg&quot;;
$size = 40;

$grav_url = &quot;http://www.gravatar.com/avatar.php?
gravatar_id=&quot;.md5( strtolower($email) ).
&quot;&amp;amp;default=&quot;.urlencode($default).
&quot;&amp;amp;size=&quot;.$size;
</pre><p>The above code creates a $grav_url which contains the md5 hash of email address and the size details. This gravatar url can then be used in an &lt;img src=&#8221;"&gt; tag and the image will be loaded.</p><pre class="brush: xml; title: ; notranslate">
&lt;img src=&quot;&lt;? echo $grav_url ?&gt;&quot;/&gt;
</pre><h2>Integrate Gravatar with Java</h2><p>The following class will provide you with a static method that returns the hex format md5 of an input string:</p><pre class="brush: java; title: ; notranslate">
import java.util.*;
import java.io.*;
import java.security.*;
public class MD5Util {
  public static String hex(byte[] array) {
      StringBuffer sb = new StringBuffer();
      for (int i = 0; i &lt; array.length; ++i) {
	  sb.append(Integer.toHexString((array[i]
	      &amp; 0xFF) | 0x100).substring(1,3));
      }
      return sb.toString();
  }
  public static String md5Hex (String message) {
      try {
	  MessageDigest md =
	      MessageDigest.getInstance(&quot;MD5&quot;);
	  return hex (md.digest(message.getBytes(&quot;CP1252&quot;)));
      } catch (NoSuchAlgorithmException e) {
      } catch (UnsupportedEncodingException e) {
      }
      return null;
  }
}
</pre><p>This class can then be used to return the MD5 hash of an email address like this:</p><pre class="brush: java; title: ; notranslate">
String email = &quot;someone@somewhere.com&quot;;
String hash = MD5Util.md5Hex(email);
</pre><p>With the hex string that is returned, you can construct your gravatar URL.</p><p>Thus Gravatar makes it easy for us to manage the avatars at a single place.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/01/dynamic-unread-count-favicon-in-php.html" title="Dynamic unread count Favicon in PHP">Dynamic unread count Favicon in PHP</a></li><li><a href="http://viralpatel.net/blogs/2010/12/password-protect-your-webpages-using-htaccess.html" title="Password Protect your webpages using htaccess">Password Protect your webpages using htaccess</a></li><li><a href="http://viralpatel.net/blogs/2010/10/introduction-html5-domstorage-api-example.html" title="Introduction to HTML5 DOMStorage API with Example">Introduction to HTML5 DOMStorage API with Example</a></li><li><a href="http://viralpatel.net/blogs/2010/06/facebook-facts-you-didnt-know.html" title="Facebook: Facts you probably didnt know">Facebook: Facts you probably didnt know</a></li><li><a href="http://viralpatel.net/blogs/2010/01/oembed-open-format-web-developers.html" title="oEmbed: An Open Format Every Developer Should Know About">oEmbed: An Open Format Every Developer Should Know About</a></li><li><a href="http://viralpatel.net/blogs/2009/11/php-fatal-error-time-htaccess.html" title="PHP Fatal Error Maximum Execution Time Issue &#038; htaccess">PHP Fatal Error Maximum Execution Time Issue &#038; htaccess</a></li><li><a href="http://viralpatel.net/blogs/2009/09/how-to-setup-multiple-virtual-hosts-in-wamp.html" title="How to: Setup Multiple Virtual Hosts in WAMP Server">How to: Setup Multiple Virtual Hosts in WAMP Server</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/05/gravatar-manage-your-user-avatars-for-free.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced

Served from: viralpatel.net @ 2012-02-08 21:15:17 -->
