<?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>Web Developer Plus &#187; PHP</title>
	<atom:link href="http://webdeveloperplus.com/category/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://webdeveloperplus.com</link>
	<description>The Ultimate Web Developer&#039;s Resource</description>
	<lastBuildDate>Sun, 04 Jul 2010 11:38:25 +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>AJAX User Poll Using jQuery and PHP</title>
		<link>http://webdeveloperplus.com/php/ajax-user-poll-using-jquery-and-php/</link>
		<comments>http://webdeveloperplus.com/php/ajax-user-poll-using-jquery-and-php/#comments</comments>
		<pubDate>Thu, 15 Oct 2009 07:49:54 +0000</pubDate>
		<dc:creator>Satbir</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[user poll]]></category>

		<guid isPermaLink="false">http://webdeveloperplus.com/?p=494</guid>
		<description><![CDATA[Today, we&#8217;ll be creating a nice user poll script using jQuery and PHP utilizing AJAX and animation effects of jQuery to spice up the user interface and provide a rich user experience. Let&#8217;s get started. Set up the database For storing poll questions, options and votes, we&#8217;ll be using a MySQL database. Here is the [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://webdeveloperplus.com/wp-content/uploads/2009/10/ajax-poll-jquery.png" alt="AJAX User Poll Using jQuery, PHP" title="AJAX User Poll Using jQuery, PHP" width="599" height="376" class="alignnone size-full wp-image-495" /><br />
Today, we&#8217;ll be creating a nice user poll script using jQuery and PHP utilizing  AJAX and animation effects of jQuery to spice up the user interface and provide a rich user experience. Let&#8217;s get started.</p>
<h3>Set up the database</h3>
<p>For storing poll questions, options and votes, we&#8217;ll be using a MySQL database. Here is the database structure required.<span id="more-494"></span><br />
<img src="http://webdeveloperplus.com/wp-content/uploads/2009/10/ajax-poll-database-structure.jpg" alt="Database Structure" title="Database Structure" width="460" height="192" class="alignnone size-full wp-image-496" /><br />
There are three tables:</p>
<ul>
<li><strong>questions</strong> table stores the poll questions.</li>
<li><strong>options</strong> table stores the options of a particular question.</li>
<li><strong>votes</strong> table stores information about each vote cast by the user.</li>
</ul>
<p>The required SQL code with sample data is provided in source code(below).</p>
<h3>The PHP Code</h3>
<h4>Displaying the poll form</h4>
<p>We&#8217;ll display the most recent poll question from the database and allow the user to vote for it. Here&#8217;s the required PHP code to generate poll form for latest poll question.</p>
<pre name="code" class="php" >
$conn=mysql_connect('localhost', 'root', 'password') or die(&quot;Can't connect to mysql host&quot;);
mysql_select_db(&quot;polls&quot;);
$query=mysql_query(&quot;SELECT id, ques FROM questions ORDER BY id DESC LIMIT 1&quot;);
while($row=mysql_fetch_assoc($query)){
	//display question
	echo &quot;&lt;p class=\&quot;pollques\&quot; &gt;&quot;.$row[&quot;ques&quot;].&quot;&lt;/p&gt;&quot;;
	$poll_id=$row[&quot;id&quot;];
}
//display options with radio buttons
$query=mysql_query(&quot;SELECT id, value FROM options WHERE ques_id=$poll_id&quot;);
if(mysql_num_rows($query)){
		echo '&lt;div id=&quot;formcontainer&quot; &gt;&lt;form method=&quot;post&quot; id=&quot;pollform&quot; action=&quot;'.$_SERVER['PHP_SELF'].'&quot; &gt;';
		echo '&lt;input type=&quot;hidden&quot; name=&quot;pollid&quot; value=&quot;'.$poll_id.'&quot; /&gt;';
		while($row=mysql_fetch_assoc($query)){
			echo '&lt;p&gt;&lt;input type=&quot;radio&quot; name=&quot;poll&quot; value=&quot;'.$row['id'].'&quot; id=&quot;option-'.$row['id'].'&quot; /&gt;
			&lt;label for=&quot;option-'.$row['id'].'&quot; &gt;'.$row['value'].'&lt;/label&gt;&lt;/p&gt;';
		}
		echo '&lt;p&gt;&lt;input type=&quot;submit&quot;  value=&quot;Submit&quot; /&gt;&lt;/p&gt;&lt;/form&gt;';
}
</pre>
<h4>Processing the Submitted Vote</h4>
<p>When user selects an answer and submits the form, we add the information to the <em>votes</em> table about the option selected and also set a cookie in user&#8217;s browser to identify that he has voted for the poll. </p>
<pre name="code" class="php" >
$query=mysql_query(&quot;SELECT * FROM options WHERE id='&quot;.intval($_POST[&quot;poll&quot;]).&quot;'&quot;);
if(mysql_num_rows($query)){
	$query=&quot;INSERT INTO votes(option_id, voted_on, ip) VALUES('&quot;.$_POST[&quot;poll&quot;].&quot;', '&quot;.date('Y-m-d H:i:s').&quot;', '&quot;.$_SERVER['REMOTE_ADDR'].&quot;')&quot;;
	if(mysql_query($query))
	{
		//Vote added to database
		setcookie(&quot;voted&quot;.$_POST['pollid'], 'yes', time()+86400*300);
	}
	else
		echo &quot;There was some error processing the query: &quot;.mysql_error();
}
</pre>
<p>In this case we first check to see if the answer to poll question has been provided and whether the user hasnot already voted(<em>code omitted for simplicity</em>) the selected option is there in database or not. Also here we are using <code>intval()</code> function to make sure only integer value for selected option passes through. After checking the information, the user vote is added to the <em>votes</em> table.</p>
<h4>Displaying the Results</h4>
<p>Once the user has voted, it&#8217;s time to display the results to him. We&#8217;ll be using the easy way out to display the result using CSS. Here&#8217;s the code for that.</p>
<pre name="code" class="php" >
$query=mysql_query(&quot;SELECT COUNT(*) as totalvotes FROM votes WHERE option_id IN(SELECT id FROM options WHERE ques_id='$poll_id')&quot;);
while($row=mysql_fetch_assoc($query))
	$total=$row['totalvotes'];
$query=mysql_query(&quot;SELECT options.id, options.value, COUNT(*) as votes FROM votes, options WHERE votes.option_id=options.id AND votes.option_id IN(SELECT id FROM options WHERE ques_id='$poll_id') GROUP BY votes.option_id&quot;);
while($row=mysql_fetch_assoc($query)){
	$percent=round(($row['votes']*100)/$total);
	echo '&lt;div class=&quot;option&quot; &gt;&lt;p&gt;'.$row['value'].' (&lt;em&gt;'.$percent.'%, '.$row['votes'].' votes&lt;/em&gt;)&lt;/p&gt;';
	echo '&lt;div class=&quot;bar ';
	if($_POST['poll']==$row['id']) echo ' yourvote';
	echo '&quot; style=&quot;width: '.$percent.'%; &quot; &gt;&lt;/div&gt;&lt;/div&gt;';
}
echo '&lt;p&gt;Total Votes: '.$total.'&lt;/p&gt;';
</pre>
<p>To display the results from the information we have in <strong>votes</strong> table, we will use a <strong>GROUP BY</strong> query to find out votes per option and then set the width of display bar based on percentage of votes each option received.</p>
<p>All the PHP code is in <strong>poll.php</strong> file.</p>
<h3>HTML Structure</h3>
<p>HTML structure is quite simple as jQuery will do the heavy lifting. We only need to define a container that will hold the poll form or display the results.</p>
<pre name="code" class="html" >
&lt;div id=&quot;container&quot; &gt;
	&lt;h1&gt;User Poll&lt;/h1&gt;
	&lt;div id=&quot;pollcontainer&quot; &gt;
	&lt;/div&gt;
	&lt;p id=&quot;loader&quot; &gt;Loading...&lt;/p&gt;
&lt;/div&gt;
</pre>
<h3>The JavaScript Code</h3>
<h4>Loading the Poll Form</h4>
<p>On page load, we will load and display the poll form to user and if user has already voted, then results will be displayed.</p>
<pre name="code" class="js">
var loader=$('#loader');
	var pollcontainer=$('#pollcontainer');
	loader.fadeIn();
	//Load the poll form
	$.get('poll.php', '', function(data, status){
		pollcontainer.html(data);
		animateResults(pollcontainer);
		pollcontainer.find('#viewresult').click(function(){
			//if user wants to see result
			loader.fadeIn();
			$.get('poll.php', 'result=1', function(data,status){
				pollcontainer.fadeOut(1000, function(){
					$(this).html(data);
					animateResults(this);
				});
				loader.fadeOut();
			});
			//prevent default behavior
			return false;
		})
</pre>
<h4>Processing User Vote</h4>
<p>To process the user vote, we first check to see if user has selected one of the options and then post the form data to <strong>poll.php</strong> and then display the results to the user in a nice animated way using the function <code>animateResults</code>. </p>
<pre name="code" class="js" >
('#pollform').submit(function(){
			var selected_val=$(this).find('input[name=poll]:checked').val();
			if(selected_val!=''){
				//post data only if a value is selected
				loader.fadeIn();
				$.post('poll.php', $(this).serialize(), function(data, status){
					$('#formcontainer').fadeOut(100, function(){
						$(this).html(data);
						animateResults(this);
						loader.fadeOut();
					});
				});
			}
			//prevent form default behavior
			return false;
		});
</pre>
<p>Download the complete source code and try it out for yourself.</p>
<div class="demo" ><a href="http://demo.webdeveloperplus.com/source-code/ajax-poll.zip" >Download</a></div>
<p><strong>Remember to set up database and tables using <em>polls.sql</em> file provided in source code and update database information in the <em>poll.php</em> file</strong> before trying out.</p>
<p><strong>Note:</strong> In this tutorial, i have only covered the user interface part of the user poll script. You&#8217;ll have to code the user interface for creating new polls or manually have to add questions and options in the tables. The sample database file provided with the source code contains a sample poll question along with some sample data.</p>
<h3>Related Posts</h3>
<ol>
		<li><a href="http://webdeveloperplus.com/jquery/ajax-multiple-file-upload-form-using-jquery/" rel="bookmark">
												AJAX Multiple File Upload Form Using jQuery</a><!-- (6.4)--></li>
		<li><a href="http://webdeveloperplus.com/php/integrate-customized-recaptcha-in-your-php-application/" rel="bookmark">
												Integrate Customized reCaptcha in your PHP Application</a><!-- (5.1)--></li>
	</ol>
]]></content:encoded>
			<wfw:commentRss>http://webdeveloperplus.com/php/ajax-user-poll-using-jquery-and-php/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>25 New &amp; Useful PHP Techniques &amp; Tutorials</title>
		<link>http://webdeveloperplus.com/php/25-new-useful-php-techniques-tutorials/</link>
		<comments>http://webdeveloperplus.com/php/25-new-useful-php-techniques-tutorials/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 14:39:30 +0000</pubDate>
		<dc:creator>Satbir</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Popular]]></category>
		<category><![CDATA[code snippets]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php debugging]]></category>

		<guid isPermaLink="false">http://webdeveloperplus.com/?p=473</guid>
		<description><![CDATA[PHP is the most popular and widely accepted server side scripting language among developers due to its easy to learn nature, free of cost and its large ever increasing helpful community. Here are 25 useful PHP techniques and tutorials, most of which have been published only in this year. 1. Facebook type image rotation and [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://webdeveloperplus.com/wp-content/uploads/2009/10/php.jpg" alt="PHP" title="PHP" width="160" height="85" class="alignleft size-full wp-image-487" />PHP is the most popular and widely accepted server side scripting language among developers due to its easy to learn nature, free of cost and its large ever increasing helpful community. Here are 25 useful PHP techniques and tutorials, most of which have been published only in this year. </p>
<h4>1. <a href="http://abhinavsingh.com/blog/2009/07/facebook-type-image-rotation-and-more-using-php-and-javascript/" >Facebook type image rotation and more using PHP and Javascript </a></h4>
<p><img src="http://webdeveloperplus.com/wp-content/uploads/2009/10/image-rotation.jpg" alt="image rotation with PHP" title="image rotation with PHP" width="500" height="290" class="alignnone size-full wp-image-485" /><br />
How does facebook rotate images in gallery. Here&#8217;s a nice solution using the inbuilt <em>imagerotate</em> functionality in PHP. <a href="http://abhinavsingh.com/webdemos/imagerotate/" >View Demo &raquo;</a><span id="more-473"></span></p>
<h4>2. <a href="http://davidwalsh.name/php-google-analytics" >Retrieve Google Analytics Visits and Pageviews with PHP</a></h4>
<p><img src="http://webdeveloperplus.com/wp-content/uploads/2009/10/google-analytics-data.png" alt="Retrieve Google Analytics data with PHP" title="Retrieve Google Analytics data with PHP" width="500" height="200" class="alignnone size-full wp-image-484" /><br />
Learn how to integrate Google Analytics data into your website using an easy to use PHP API<br />
<a href="http://davidwalsh.name/dw-content/google-analytics-stats-2.php"  >View Demo &raquo;</a></p>
<h4>3. <a href="http://papermashup.com/caching-dynamic-php-pages-easily/" >Caching Dynamic PHP pages easily</a></h4>
<p>Learn how to cache database intensive heavy pages and serve the static html cached files utilizing the output buffering in PHP</p>
<h4>4. <a href="http://www.hiteshagrawal.com/php/reading-excel-sheet-in-php" >Reading Excel Sheet in PHP</a></h4>
<p>In this article you will learn, how you can read Microsoft Excel Sheet in PHP using Open Source Tool PHPExcelReader.</p>
<h4>5. <a href="http://abhinavsingh.com/blog/2009/07/xml-parsing-in-php-xpath-way-the-best-i-know-so-far/" >XML Parsing in PHP/XPath Way</a></h4>
<p>If you are a PHP developer, you surely must have done XML parsing at some stage or the other. Parsing XML using XPath is far more better than other techniques, not only because it’s quite simple but also because it’s extendable.</p>
<h4>6. <a href="http://davidwalsh.name/gmail-php-imap" >Retrieve Your Gmail Emails Using PHP and IMAP</a></h4>
<p><img src="http://webdeveloperplus.com/wp-content/uploads/2009/10/gmail-email-using-php.png" alt="Grab emails from gmail using PHP" title="Grab emails from gmail using PHP" width="500" height="200" class="alignnone size-full wp-image-483" /><br />
Grabbing emails from your Gmail account using PHP is probably easier than you think. Armed with PHP and its IMAP extension, you can retrieve emails from your Gmail account in no time.<br />
<a href="http://davidwalsh.name/dw-content/php-gmail.php" >View Demo &raquo;</a></p>
<h4>7. <a href="http://www.lateralcode.com/directory-trees-with-php-and-jquery/" >Directory Trees With PHP and jQuery</a></h4>
<p><img src="http://webdeveloperplus.com/wp-content/uploads/2009/10/directory-tree.png" alt="Directory tree using PHP" title="Directory tree using PHP" width="500" height="170" class="alignnone size-full wp-image-482" /><br />
A simple way to keep track of many files is to use a directory tree. A directory tree lists out files and directories so that it’s easy to find what you’re looking for.</p>
<h4>8. <a href="http://dev-tips.com/featured/send-hassle-free-and-dependable-html-emails-with-php" >Send Hassle Free and dependable HTML emails with PHP</a></h4>
<p>A simple straightforward function that sends HTML e-mails with a plain text counterpart for those over 80 and still using AOL 2.5.</p>
<h4>9. <a href="http://dev-tips.com/featured/how-to-use-custom-ini-files-with-php" >How To Use Custom ini Files With PHP</a></h4>
<p>The config file typically holds information that will be used over and over again, such as database info. Today, we will have a look at a simple example of using a custom ini file to set our preferences.</p>
<h4>10. <a href="http://www.reynoldsftw.com/2009/09/from-mysql-to-jquery-via-php-xml-ajax/" >From MySQL to jQuery, via PHP, XML &#038; Ajax</a></h4>
<p>This article will focus on getting data from a database using PHP, converting that to an XML document, and reading that XML in through jQuery via Ajax calls. Seems complex, but is in fact, very easy.</p>
<h4>11. <a href="http://davidwalsh.name/web-service-php-mysql-xml-json" >Create a Basic Web Service Using PHP, MySQL, XML, and JSON</a></h4>
<p>Here’s how to create a basic web service that provides an XML or JSON response using some PHP and MySQL.</p>
<h4>12. <a href="http://corpocrat.com/2009/09/29/how-url-shortening-scripts-work/" >How URL shortner scripts work?</a></h4>
<p>Ever thought of how those URL Shortening services work. Have a look at a nice technique to create your own URL shortening service.</p>
<h4>13. <a href="http://corpocrat.com/2009/08/18/automatic-face-detection-with-php-in-linux/" >Automatic Face Detection in Photos with PHP </a></h4>
<p><img src="http://webdeveloperplus.com/wp-content/uploads/2009/10/php-face-detect.jpg" alt="Detect faces in image with PHP" title="Detect faces in image with PHP" width="247" height="159" class="alignnone size-full wp-image-486" /><br />
Find out how to automatically detect and tag a face in an image.</p>
<h4>14. <a href="http://codytaylor.org/2009/06/update-twitter-using-command-line-javascript-or-php.html" >Update Twitter using Command Line, Javascript, Or PHP.</a></h4>
<p>Everyone seems to be all about Twitter so here’s some simple examples of how to update your Twitter status from a command line prompt, web server or simple html web site.</p>
<h4>15. <a href="http://www.gen-x-design.com/archives/making-restful-requests-in-php/" >Making RESTful Requests in PHP</a></h4>
<p>APIs have become a very commonplace part of many popular web sites and services, especially REST APIs. This article discusses how to get, post, put and delete with a REST API in PHP.</p>
<h4>16. <a href="http://codestips.com/?p=226" >PHP Multithreading using CURL</a></h4>
<p>Simultaneously fetch data from multiple websites using CURL&#8217;s multithreading option.</p>
<h4>17. <a href="http://papermashup.com/php-http-authentication/" >PHP HTTP Authentication</a></h4>
<p><img src="http://webdeveloperplus.com/wp-content/uploads/2009/10/php-http-authentication.png" alt="HTTP Authentication With PHP" title="HTTP Authentication With PHP" width="500" height="132" class="alignnone size-full wp-image-481" /><br />
At times, you may wish to make certain pages of your site only viewable to a select few, you can do this by using PHP&#8217;s built in HTTP Authentication.</p>
<h4>18. <a href="http://codestips.com/?p=180" >PHP copy directory from source to destination</a></h4>
<p>To copy a directory source to a destination directory you will need to scan the source directory with all files and directory and copy to the destination. To accomplish this we should make a recursive function that will copy the files from source to target dir.</p>
<h4>19. <a href="http://viralpatel.net/blogs/2009/02/file-upload-in-php-file-upload-php-file-upload-tutorial-securing-things.html" >File Upload in PHP &#8211; Securing the things</a></h4>
<p>Secure your file upload forms and prevent malicious users from attacking your web app.</p>
<h4>20. <a href="http://www.hiteshagrawal.com/php/html-scrapper-in-php" >HTML Scraper in PHP</a></h4>
<p>Sometimes we want to extract the HTML content of the remote website page, this technique is called as HTML scraper. This article will discuss on how we can extract the HTML content of the remote webpage.</p>
<h4>21. <a href="http://hungred.com/useful-information/php-secure-login-tips-and-tricks/" >PHP Secure Login Tips and Tricks</a></h4>
<p>In this article, you will get a list of PHP secure login tips and tricks that will definitely help you decide on your secure rating of your login page.</p>
<h4>22. <a href="http://papermashup.com/use-php-to-gzip-css-files/" >Use PHP To Gzip CSS Files</a></h4>
<p>This technique is a powerful and simple way to reduce page download size and speed up your site that will work with most PHP installations</p>
<h4>23. <a href="http://davidwalsh.name/backup-database-xml-php" >Backup Your Database into an XML File Using PHP</a></h4>
<p>The database is the most important part of a web application. Imagine losing all of the data in your database — it would be tragic. Here’s a PHP snippet that outputs your database as XML.</p>
<h4>24. <a href="http://carsonified.com/blog/dev/how-to-debug-in-php/" >How To Debug in PHP</a></h4>
<p>This article breaks down the fundamentals of debugging in PHP, helps you understand PHP’s error messages and introduces you to some useful tools to help make the process a little less painful.</p>
<h4>25. <a href="http://giorgiosironi.blogspot.com/2009/10/optimizing-php-application-in-5-minutes.html" >Optimizing a php application in 5 minutes</a></h4>
<p>Optimizing means reducing loading and execution times, improving the user experience by making the application reacting more responsively. If your language of choice is php, fortunately this process takes only 5 minutes.</p>
<h3>Related Posts</h3>
<ol>
		<li><a href="http://webdeveloperplus.com/php/21-really-useful-handy-php-code-snippets/" rel="bookmark">
												21 Really Useful &#038; Handy PHP Code Snippets</a><!-- (6.9)--></li>
	</ol>
]]></content:encoded>
			<wfw:commentRss>http://webdeveloperplus.com/php/25-new-useful-php-techniques-tutorials/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
		<item>
		<title>21 Really Useful &amp; Handy PHP Code Snippets</title>
		<link>http://webdeveloperplus.com/php/21-really-useful-handy-php-code-snippets/</link>
		<comments>http://webdeveloperplus.com/php/21-really-useful-handy-php-code-snippets/#comments</comments>
		<pubDate>Mon, 17 Aug 2009 15:50:00 +0000</pubDate>
		<dc:creator>Satbir</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Popular]]></category>
		<category><![CDATA[code snippets]]></category>

		<guid isPermaLink="false">http://webdeveloperplus.com/?p=249</guid>
		<description><![CDATA[PHP is the most widely used web based programming language that powers millions of websites including some of the most popular ones like Facebook. Here are 21 really useful and handy PHP code snippets that every type of PHP developer will find useful.]]></description>
			<content:encoded><![CDATA[<p><img src="http://webdeveloperplus.com/wp-content/uploads/2009/08/php.jpg" alt="php" title="php" width="180" height="129" class="alignleft size-full wp-image-268" /> PHP is the most widely used web based programming language that powers millions of websites including some of the most popular ones like Facebook. Here are 21 really useful and handy PHP code snippets that every type of PHP developer will find useful.<br />
<br class="clear" /></p>
<h4>1. Human Readable Random String</h4>
<p>This code will create a human readable string that will look more close to dictionary words, useful for captchas.</p>
<pre name="code" class="php" >
/**************
*@length - length of random string (must be a multiple of 2)
**************/
function readable_random_string($length = 6){
    $conso=array(&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;f&quot;,&quot;g&quot;,&quot;h&quot;,&quot;j&quot;,&quot;k&quot;,&quot;l&quot;,
    &quot;m&quot;,&quot;n&quot;,&quot;p&quot;,&quot;r&quot;,&quot;s&quot;,&quot;t&quot;,&quot;v&quot;,&quot;w&quot;,&quot;x&quot;,&quot;y&quot;,&quot;z&quot;);
    $vocal=array(&quot;a&quot;,&quot;e&quot;,&quot;i&quot;,&quot;o&quot;,&quot;u&quot;);
    $password=&quot;&quot;;
    srand ((double)microtime()*1000000);
    $max = $length/2;
    for($i=1; $i&lt;=$max; $i++)
    {
    $password.=$conso[rand(0,19)];
    $password.=$vocal[rand(0,4)];
    }
    return $password;
}
</pre>
<h4>2. Generate a Random String</h4>
<p>If you don&#8217;t need human readable string, then use this function instead, which will create a random string you can use for user id&#8217;s etc.</p>
<pre name="code" class="php" >
/*************
*@l - length of random string
*/
function generate_rand($l){
  $c= &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&quot;;
  srand((double)microtime()*1000000);
  for($i=0; $i&lt;$l; $i++) {
	  $rand.= $c[rand()%strlen($c)];
  }
  return $rand;
 }
</pre>
<h4>3. Encode Email Address</h4>
<p>With this snippet, you can encode any email address into HTML entities so that spam bots do not find it.</p>
<pre name="code" class="php" >
function encode_email($email='info@domain.com', $linkText='Contact Us', $attrs ='class=&quot;emailencoder&quot;' )
{
	// remplazar aroba y puntos
	$email = str_replace('@', '&amp;#64;', $email);
	$email = str_replace('.', '&amp;#46;', $email);
	$email = str_split($email, 5);

	$linkText = str_replace('@', '&amp;#64;', $linkText);
	$linkText = str_replace('.', '&amp;#46;', $linkText);
	$linkText = str_split($linkText, 5);

	$part1 = '&lt;a href=&quot;ma';
	$part2 = 'ilto&amp;#58;';
	$part3 = '&quot; '. $attrs .' &gt;';
	$part4 = '&lt;/a&gt;';

	$encoded = '&lt;script type=&quot;text/javascript&quot;&gt;';
	$encoded .= &quot;document.write('$part1');&quot;;
	$encoded .= &quot;document.write('$part2');&quot;;
	foreach($email as $e)
	{
			$encoded .= &quot;document.write('$e');&quot;;
	}
	$encoded .= &quot;document.write('$part3');&quot;;
	foreach($linkText as $l)
	{
			$encoded .= &quot;document.write('$l');&quot;;
	}
	$encoded .= &quot;document.write('$part4');&quot;;
	$encoded .= '&lt;/script&gt;';

	return $encoded;
}
</pre>
<h4>4. Validate email Address</h4>
<p>E-mail validation is perhaps the most used validation in web forms, this code will validate email address and also optionally check the MX records of the domain provided in email address to make email validation more robust.</p>
<pre name="code" class="php" >
function is_valid_email($email, $test_mx = false)
{
	if(eregi(&quot;^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$&quot;, $email))
		if($test_mx)
		{
			list($username, $domain) = split(&quot;@&quot;, $email);
			return getmxrr($domain, $mxrecords);
		}
		else
			return true;
	else
		return false;
}
</pre>
<h4>5. List Directory Contents</h4>
<pre name="code" class="php" >
function list_files($dir)
{
	if(is_dir($dir))
  	{
  		if($handle = opendir($dir))
  		{
  			while(($file = readdir($handle)) !== false)
  			{
  				if($file != &quot;.&quot; &amp;&amp; $file != &quot;..&quot; &amp;&amp; $file != &quot;Thumbs.db&quot;)
  				{
  					echo '&lt;a target=&quot;_blank&quot; href=&quot;'.$dir.$file.'&quot;&gt;'.$file.'&lt;/a&gt;&lt;br&gt;'.&quot;\n&quot;;
  				}
  			}
  			closedir($handle);
  		}
	}
}
</pre>
<h4>6. Destroy Directory</h4>
<p>Delete a directory including its contents.</p>
<pre name="code" class="php" >
/*****
*@dir - Directory to destroy
*@virtual[optional]- whether a virtual directory
*/
function destroyDir($dir, $virtual = false)
{
	$ds = DIRECTORY_SEPARATOR;
	$dir = $virtual ? realpath($dir) : $dir;
	$dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
	if (is_dir($dir) &amp;&amp; $handle = opendir($dir))
	{
		while ($file = readdir($handle))
		{
			if ($file == '.' || $file == '..')
			{
				continue;
			}
			elseif (is_dir($dir.$ds.$file))
			{
				destroyDir($dir.$ds.$file);
			}
			else
			{
				unlink($dir.$ds.$file);
			}
		}
		closedir($handle);
		rmdir($dir);
		return true;
	}
	else
	{
		return false;
	}
}
</pre>
<h4>7. Parse JSON Data</h4>
<p>With most of the popular web services like Twitter providing their data through APIs, it is always helpful to know how to parse API data which is sent in various formats including JSON, XML etc. </p>
<pre name="code" class="php" >
$json_string='{&quot;id&quot;:1,&quot;name&quot;:&quot;foo&quot;,&quot;email&quot;:&quot;foo@foobar.com&quot;,&quot;interest&quot;:[&quot;wordpress&quot;,&quot;php&quot;]} ';
$obj=json_decode($json_string);
echo $obj-&gt;name; //prints foo
echo $obj-&gt;interest[1]; //prints php
</pre>
<h4>8. Parse XML Data</h4>
<pre name="code" class="php" >
//xml string
$xml_string=&quot;&lt;?xml version='1.0'?&gt;
&lt;users&gt;
   &lt;user id='398'&gt;
      &lt;name&gt;Foo&lt;/name&gt;
      &lt;email&gt;foo@bar.com&lt;/name&gt;
   &lt;/user&gt;
   &lt;user id='867'&gt;
      &lt;name&gt;Foobar&lt;/name&gt;
      &lt;email&gt;foobar@foo.com&lt;/name&gt;
   &lt;/user&gt;
&lt;/users&gt;&quot;;

//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);

//loop through the each node of user
foreach ($xml-&gt;user as $user)
{
   //access attribute
   echo $user['id'], '  ';
   //subnodes are accessed by -&gt; operator
   echo $user-&gt;name, '  ';
   echo $user-&gt;email, '&lt;br /&gt;';
}
</pre>
<h4>9. Create Post Slugs</h4>
<p>Create user friendly post slugs from title string to use within URLs.</p>
<pre name="code" class="php" >
function create_slug($string){
	$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
	return $slug;
}
</pre>
<h4>10. Get Real IP Address of Client</h4>
<p>This function will fetch the real IP address of the user even if he is behind a proxy server.</p>
<pre name="code" class="php" >
function getRealIpAddr()
{
	if (!empty($_SERVER['HTTP_CLIENT_IP']))
	{
		$ip=$_SERVER['HTTP_CLIENT_IP'];
	}
	elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
	//to check ip is pass from proxy
	{
		$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	}
	else
	{
		$ip=$_SERVER['REMOTE_ADDR'];
	}
	return $ip;
}
</pre>
<h4>11. Force file Download</h4>
<p>Provide files to the user by forcing them to download.</p>
<pre name="code" class="php" >
/********************
*@file - path to file
*/
function force_download($file)
{
    if ((isset($file))&amp;&amp;(file_exists($file))) {
       header(&quot;Content-length: &quot;.filesize($file));
       header('Content-Type: application/octet-stream');
       header('Content-Disposition: attachment; filename=&quot;' . $file . '&quot;');
       readfile(&quot;$file&quot;);
    } else {
       echo &quot;No file selected&quot;;
    }
}
</pre>
<h4>12. Creating a Tag Cloud</h4>
<pre name="code" class="php" >
function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )
{
	$minimumCount = min($data);
	$maximumCount = max($data);
	$spread       = $maximumCount - $minimumCount;
	$cloudHTML    = '';
	$cloudTags    = array();

	$spread == 0 &amp;&amp; $spread = 1;

	foreach( $data as $tag =&gt; $count )
	{
		$size = $minFontSize + ( $count - $minimumCount )
			* ( $maxFontSize - $minFontSize ) / $spread;
		$cloudTags[] = '&lt;a style=&quot;font-size: ' . floor( $size ) . 'px'
		. '&quot; class=&quot;tag_cloud&quot; href=&quot;#&quot; title=&quot;\'' . $tag  .
		'\' returned a count of ' . $count . '&quot;&gt;'
		. htmlspecialchars( stripslashes( $tag ) ) . '&lt;/a&gt;';
	}

	return join( &quot;\n&quot;, $cloudTags ) . &quot;\n&quot;;
}
/**************************
****   Sample usage    ***/
$arr = Array('Actionscript' =&gt; 35, 'Adobe' =&gt; 22, 'Array' =&gt; 44, 'Background' =&gt; 43,
	'Blur' =&gt; 18, 'Canvas' =&gt; 33, 'Class' =&gt; 15, 'Color Palette' =&gt; 11, 'Crop' =&gt; 42,
	'Delimiter' =&gt; 13, 'Depth' =&gt; 34, 'Design' =&gt; 8, 'Encode' =&gt; 12, 'Encryption' =&gt; 30,
	'Extract' =&gt; 28, 'Filters' =&gt; 42);
echo getCloud($arr, 12, 36);
</pre>
<h4>13. Find Similarity Between Two Strings</h4>
<p>PHP includes a function <code>similar_text</code> very rarely used but quite useful that compares two strings and returns the percentage of similarity between two.</p>
<pre name="code" class="php" >
similar_text($string1, $string2, $percent);
//$percent will have the percentage of similarity
</pre>
<h4>14. Use Gravatars in Your Application</h4>
<p>With ever increasing popularity of WordPress, Gravatars have become quite popular. It is very easy to integrate them into your application as they provide a very easy to use API.</p>
<pre name="code" class="php" >
/******************
*@email - Email address to show gravatar for
*@size - size of gravatar
*@default - URL of default gravatar to use
*@rating - rating of Gravatar(G, PG, R, X)
*/
function show_gravatar($email, $size, $default, $rating)
{
	echo '&lt;img src=&quot;http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).
		'&amp;default='.$default.'&amp;size='.$size.'&amp;rating='.$rating.'&quot; width=&quot;'.$size.'px&quot;
		height=&quot;'.$size.'px&quot; /&gt;';
}
</pre>
<h4>15. Truncate Text at Word Break</h4>
<p>This function will truncate strings only at word breaks which can be used to show a teaser for complete article without breaking words.</p>
<pre name="code" class="php" >
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function myTruncate($string, $limit, $break=&quot;.&quot;, $pad=&quot;...&quot;) {
	// return with no change if string is shorter than $limit
	if(strlen($string) &lt;= $limit)
		return $string; 

	// is $break present between $limit and the end of the string?
	if(false !== ($breakpoint = strpos($string, $break, $limit))) {
		if($breakpoint &lt; strlen($string) - 1) {
			$string = substr($string, 0, $breakpoint) . $pad;
		}
	}
	return $string;
}
/***** Example ****/
$short_string=myTruncate($long_string, 100, ' ');
</pre>
<h4>16. Zip Files on the Fly</h4>
<pre name="code" class="php" >
/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
	//if the zip file already exists and overwrite is false, return false
	if(file_exists($destination) &amp;&amp; !$overwrite) { return false; }
	//vars
	$valid_files = array();
	//if files were passed in...
	if(is_array($files)) {
		//cycle through each file
		foreach($files as $file) {
			//make sure the file exists
			if(file_exists($file)) {
				$valid_files[] = $file;
			}
		}
	}
	//if we have good files...
	if(count($valid_files)) {
		//create the archive
		$zip = new ZipArchive();
		if($zip-&gt;open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
			return false;
		}
		//add the files
		foreach($valid_files as $file) {
			$zip-&gt;addFile($file,$file);
		}
		//debug
		//echo 'The zip archive contains ',$zip-&gt;numFiles,' files with a status of ',$zip-&gt;status;

		//close the zip -- done!
		$zip-&gt;close();

		//check to make sure the file exists
		return file_exists($destination);
	}
	else
	{
		return false;
	}
}
/***** Example Usage ***/
$files=array('file1.jpg', 'file2.jpg', 'file3.gif');
create_zip($files, 'myzipfile.zip', true);
</pre>
<p>Source: <a href="http://davidwalsh.name/create-zip-php" target="_blank" >David Walsh</a></p>
<h4>17.  Unzip Zip File</h4>
<pre name="code" class="php" >
/**********************
*@file - path to zip file
*@destination - destination directory for unzipped files
*/
function unzip_file($file, $destination){
	// create object
	$zip = new ZipArchive() ;
	// open archive
	if ($zip-&gt;open($file) !== TRUE) {
		die (’Could not open archive’);
	}
	// extract contents to destination directory
	$zip-&gt;extractTo($destination);
	// close archive
	$zip-&gt;close();
	echo 'Archive extracted to directory';
}
</pre>
<h4>18. Prepend http to a URL</h4>
<p>Some times you need to accept some url as input but users seldom add http:// to it, this code will add http:// to the URL if it&#8217;s not there.</p>
<pre name="code" class="php" >
if (!preg_match(&quot;/^(http|ftp):/&quot;, $_POST['url'])) {
   $_POST['url'] = 'http://'.$_POST['url'];
}
</pre>
<h4>19. Convert URLs within String into hyperlinks</h4>
<p>This function converts URLs and e-mail addresses within a string into clickable hyperlinks.</p>
<pre name="code" class="php" >
function makeClickableLinks($text) {
 $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&amp;//=]+)',
 '&lt;a href=&quot;\1&quot;&gt;\1&lt;/a&gt;', $text);
 $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&amp;//=]+)',
 '\1&lt;a href=&quot;http://\2&quot;&gt;\2&lt;/a&gt;', $text);
 $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',
 '&lt;a href=&quot;mailto:\1&quot;&gt;\1&lt;/a&gt;', $text);

return $text;
}
</pre>
<h4>20. Resize Images on the fly</h4>
<p>Creating thumbnails of the images is required many a times, this code will be useful to know about the logic of thumbnail generation.</p>
<pre name="code" class="php" >
/**********************
*@filename - path to the image
*@tmpname - temporary path to thumbnail
*@xmax - max width
*@ymax - max height
*/
function resize_image($filename, $tmpname, $xmax, $ymax)
{
	$ext = explode(&quot;.&quot;, $filename);
	$ext = $ext[count($ext)-1];

	if($ext == &quot;jpg&quot; || $ext == &quot;jpeg&quot;)
		$im = imagecreatefromjpeg($tmpname);
	elseif($ext == &quot;png&quot;)
		$im = imagecreatefrompng($tmpname);
	elseif($ext == &quot;gif&quot;)
		$im = imagecreatefromgif($tmpname);

	$x = imagesx($im);
	$y = imagesy($im);

	if($x &lt;= $xmax &amp;&amp; $y &lt;= $ymax)
		return $im;

	if($x &gt;= $y) {
		$newx = $xmax;
		$newy = $newx * $y / $x;
	}
	else {
		$newy = $ymax;
		$newx = $x / $y * $newy;
	}

	$im2 = imagecreatetruecolor($newx, $newy);
	imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
	return $im2;
}
</pre>
<h4>21. Detect AJAX Request</h4>
<p>Most of the JavaScript frameworks like jQuery, mootools send and additional <code>HTTP_X_REQUESTED_WITH</code> header when they make an AJAX request, so that you can detect AJAX request on server side.(<a href="http://davidwalsh.name/detect-ajax" target="_blank" >source</a>)</p>
<pre name="code" class="php" >
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
	//If AJAX Request Then
}else{
//something else
}
</pre>
<p>If you would like to recommend a snippet to include in this list to make this list a more useful resource, tell us about it in comments below.</p>
<h3>Related Posts</h3>
<ol>
		<li><a href="http://webdeveloperplus.com/php/25-new-useful-php-techniques-tutorials/" rel="bookmark">
								<img src="http://thumbs.webdeveloperplus.com/img/2009/10/php-useful-techniques.png" alt="25 New &#038; Useful PHP Techniques &#038; Tutorials" width="40px" height="40px" />				25 New &#038; Useful PHP Techniques &#038; Tutorials</a><!-- (6.7)--></li>
		<li><a href="http://webdeveloperplus.com/php/ajax-user-poll-using-jquery-and-php/" rel="bookmark">
								<img src="http://thumbs.webdeveloperplus.com/img/2009/10/user-poll-thumb.png" alt="AJAX User Poll Using jQuery and PHP" width="40px" height="40px" />				AJAX User Poll Using jQuery and PHP</a><!-- (6.6)--></li>
		<li><a href="http://webdeveloperplus.com/php/integrate-customized-recaptcha-in-your-php-application/" rel="bookmark">
												Integrate Customized reCaptcha in your PHP Application</a><!-- (5.5)--></li>
	</ol>
]]></content:encoded>
			<wfw:commentRss>http://webdeveloperplus.com/php/21-really-useful-handy-php-code-snippets/feed/</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<item>
		<title>Create Thumbnail Images with Rounded Corners</title>
		<link>http://webdeveloperplus.com/php/create-thumbnail-images-with-rounded-corners/</link>
		<comments>http://webdeveloperplus.com/php/create-thumbnail-images-with-rounded-corners/#comments</comments>
		<pubDate>Fri, 27 Mar 2009 10:10:27 +0000</pubDate>
		<dc:creator>Satbir</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[image thumbnails]]></category>
		<category><![CDATA[phpThumb]]></category>

		<guid isPermaLink="false">http://webdeveloperplus.com/php/create-thumbnail-images-with-rounded-corners/</guid>
		<description><![CDATA[If you have been using Facebook, then you might have noticed thumbnail images with rounded corners in new Facebook homepage. If you would like to have similar effect for thumbnails in your application, then here’s a quick and easy way to do it. We’ll be using phpThumb, the open source PHP script to generate thumbnails [...]]]></description>
			<content:encoded><![CDATA[<p>If you have been using Facebook, then you might have noticed thumbnail images with rounded corners in new Facebook homepage. If you would like to have similar effect for thumbnails in your application, then here’s a quick and easy way to do it.</p>
<p><img title="Rounded Corner Thumbnails" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; margin-left: 0px; margin-right: 0px; border-right-width: 0px" height="252" alt="Rounded Corner Thumbnails" src="http://webdeveloperplus.com/wp-content/uploads/2009/03/roundedcornerthumbnails.jpg" width="316" border="0" /> </p>
<p>We’ll be using <a href="http://phpthumb.sourceforge.net/" target="_blank">phpThumb</a>, the open source PHP script to generate thumbnails on the fly.</p>
<p>Download and extract <a href="http://sourceforge.net/project/showfiles.php?group_id=106407&amp;package_id=114543" target="_blank">phpThumb</a> to somewhere in your website folder. Now to use a rounded corner thumbnail of an image, simply use the img tag of HTML with src as</p>
<pre class="html" name="code">&lt;img src=”phpThumb.php?src=test.jpg&amp;w=200&amp;h=150&amp;fltr[]=ric|20|20&amp;f=png” /&gt;</pre>
<p>Adjust the path to phpThumb according to where you place the phpThumb files. Now we have passed 5 parameters to phpThumb.php namely,</p>
<p>1. <em>src</em> is the path to image file relative to phpThumb.php</p>
<p>2. <em>w</em> &amp; <em>h</em> are width and height of the resulting thumbnail</p>
<p>3. <em>fltr</em> is used to tell phpThumb to generate rounded corner thumbnail with first numeric value as horizontal radius of the rounded corner and second as vertical radius in pixels.</p>
<p>4. The last parameter <em>f</em> is used to control the output image format of the thumbnail, namely png, jpg or gif. We are using png as it can render images with transparent corners which can be used on any background.</p>
<p>That’s it, you have cool looking thumbnails with rounded corners.</p>
<h3>Related Posts</h3>
<ol>
		<li><a href="http://webdeveloperplus.com/wordpress/how-to-use-thumbnails-generated-by-wordpress-in-your-theme/" rel="bookmark">
												How To Use Thumbnails Generated By WordPress In Your Theme</a><!-- (7.8)--></li>
	</ol>
]]></content:encoded>
			<wfw:commentRss>http://webdeveloperplus.com/php/create-thumbnail-images-with-rounded-corners/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Integrate Customized reCaptcha in your PHP Application</title>
		<link>http://webdeveloperplus.com/php/integrate-customized-recaptcha-in-your-php-application/</link>
		<comments>http://webdeveloperplus.com/php/integrate-customized-recaptcha-in-your-php-application/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 04:46:52 +0000</pubDate>
		<dc:creator>Satbir</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[captcha]]></category>
		<category><![CDATA[reCaptcha]]></category>

		<guid isPermaLink="false">http://webdeveloperplus.com/?p=25</guid>
		<description><![CDATA[Captchas are an essential part of an online web form to prevent automated spam bots accessing your application. Though creating captchas is not a rocket science in PHP and can be easily integrated into web based forms but creating a more usable and accesible captcha which can even read out captchas on the fly is [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-26" title="recaptcha" src="http://webdeveloperplus.com/wp-content/uploads/2009/03/recaptcha.jpg" alt="recaptcha" width="315" height="162" /></p>
<p>Captchas are an essential part of an online web form to prevent automated spam bots accessing your application. Though creating captchas is not a rocket science in PHP and can be easily integrated into web based forms but creating a more usable and accesible captcha which can even read out captchas on the fly is a tough job.</p>
<p>But with reCaptcha this won&#8217;t be a big task. reCaptcha is a free captcha service that lets you integrate more accessible and friendly captchas into your web application, it shows words from various digitized books rather than creating a cryptic code generated from a random string and can read out captchas to the user.</p>
<p>Here&#8217;s how to integrate a customized reCaptcha into your PHP based web application.</p>
<h3>1. Get reCaptcha API Key</h3>
<p>First of all, you&#8217;ll need to sign up with <a href="http://recaptcha.net" target="_blank">reCaptcha</a> for an API key to use the captchas in your application. You can get an API key fo either a single domain or if you have multiple websites, you can sign up for a global key that&#8217;ll work across domains.</p>
<p>After signing up, you&#8217;ll have two keys one Public an other Private.</p>
<h3>2. Download reCaptcha Library</h3>
<p>You don&#8217;t have to mess around with fsock functions to talk to reCaptcha service, they provide a library that&#8217;ll let you access reCaptcha service easily. Just downloa the latest <a href="http://code.google.com/p/recaptcha/downloads/list?q=label:phplib-Latest" target="_blank">reCaptcha library</a> and place it in your application folder.</p>
<h3>3. Add Captcha to your Form</h3>
<p>Now to include captcha in your form, you need to include the recaptcha library you downloaded earlier into your form page and output the recaptcha widget. You&#8217;ll need your Public API key to display the captcha. Here&#8217;s the sample code that you should add to Form page, make sure it is compiled by php.</p>
<pre name="code" class="php">//Include anywhere within the form tag of your page
&lt;?php
require_once('recaptchalib.php');//change path to where you placed the library
$publickey = "..."; // your public reCaptcha Key
echo recaptcha_get_html($publickey);
?&gt;</pre>
<h3>4. Process the captcha</h3>
<p>Now when the form is submitted, you&#8217;ll need to check the validity of the captcha and if it is ok then proceed to process rest of the form. In order to check the captcha, you&#8217;ll need the private API key and then use the <em>recaptcha_check_answer</em> function to check the validity.  Here&#8217;s the sample code to be include on the php page that processes the submitted form.</p>
<pre name="code" class="php">require_once('recaptchalib.php');
$privatekey = "...";//Your Private Key
$resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);
if (!$resp-&gt;is_valid)
        echo "&lt;p style=\"color:red; \"&gt;The entered value doesn't match that of the shown string ".$rep-&gt;error."&lt;/p&gt;";
else
        echo "&lt;p style=\"color:green; font-weight:bold;\" &gt;Form OK&lt;/p&gt;";</pre>
<p>With this, your captcha is ready to roll, but wait there is more to look for.</p>
<h3>5. Customizing the reCaptcha widget</h3>
<p>By default, the reCaptcha widget shows up in<em> red</em> theme. There are other themes you can use namely <em>white, blackglass and clean</em>. To use a different theme, add this into the head section of the page on which form is displayed.</p>
<pre name="code" class="js"> &lt;script type="text/javascript"&gt;
 var RecaptchaOptions = {
    theme : '&lt;theme name here&gt;'
 };
 &lt;/script&gt;</pre>
<p>And if you&#8217;d like to have your own custom theme, you can certainly do that.</p>
<h3>6. Creating your own Custom Theme</h3>
<p>The captcha image and textbox in which value is to be entered is mandatory to use recaptcha, other elements like refresh, switch to audio are optional. Now in your form tag create a <em>div</em> element with id as <em>recaptcha_image</em> and a text input box with <em>nam</em>e and <em>id</em> set to <em>recaptcha_response_field</em>.</p>
<p>And to avoid screen flickering while recaptcha loads, you can include all the widget elements within a <em>div</em> having an inline style of <em>display:none</em>.</p>
<p>Here&#8217;s the code to include within the form tag. Code is self-explanatory.</p>
<pre name="code" class="php">&lt;div id="divrecaptcha" style="display:none;"&gt;

    &lt;div id="controls"&gt;&lt;a href="#" onclick="Recaptcha.reload(); " &gt;Get another Captcha&lt;/a&gt; &lt;br /&gt;
       &lt;a href="#" onclick="javascript:Recaptcha.switch_type('audio');" class="recaptcha_only_if_image" &gt;Get Audio Captcha&lt;/a&gt;
       &lt;a href="#" onclick="Recaptcha.switch_type('image'); " class="recaptcha_only_if_audio" &gt;Get Text Captcha&lt;/a&gt; &lt;br /&gt;
       &lt;a href="#" onclick="Recaptcha.showhelp();" &gt;Help&lt;/a&gt;
     &lt;/div&gt;

       &lt;div id="recaptcha_image"&gt;&lt;/div&gt;&lt;!--Important--&gt;
    &lt;p&gt;
 &lt;input type="text" name="recaptcha_response_field" id="recaptcha_response_field"  /&gt;&lt;!--Important--&gt;
&lt;span class="recaptcha_only_if_image"&gt;Enter the words shown above separated by space&lt;/span&gt;
&lt;span class="recaptcha_only_if_audio"&gt;Enter the numbers you hear&lt;/span&gt;&lt;/p&gt;

     &lt;/div&gt;
     &lt;?php
    require_once('recaptchalib.php');
    $publickey = "..."; // your public API key
    echo recaptcha_get_html($publickey);
    ?&gt;</pre>
<p>And in the head section of the form page, add this code.</p>
<pre name="code" class="js">&lt;script type="text/javascript" &gt;
 var RecaptchaOptions = {
    theme : 'custom',
    lang: 'en',
    custom_theme_widget: 'divrecaptcha' //div enclosing widget elements
 };
&lt;/script&gt;</pre>
<p>I added some styles to the widget elements in order to give an idea. You can apply any style to the elements you want.</p>
<pre name="code" class="css">&lt;style type="text/css" &gt;
#divrecaptcha{
    width:500px;
    font-size:12px; font-family:Arial, Helvetica, sans-serif;
}
#controls{ width:180px; float:right; }
#recaptcha_image{
    padding:2px; background:#f9f9f9;
    border:1px solid #e0e0e0;
}
#recaptcha_response_field {
   border: 1px solid #999 !important; //Text input field border color
   background-color:#ccc !important; //Text input field background color
   width:120px !important;
   padding:5px;
}
#divrecaptcha a{
     font-size:11px;    font-family:Verdana;
    text-decoration:none; color:#3366ff;
}
#divrecaptcha a:hover{
     color:113399; text-decoration:underline;
}
&lt;/style&gt;</pre>
<p>This completes the customizing of reCaptcha widget and here&#8217;s how it looked.</p>
<p><img class="alignnone size-full wp-image-27" title="customized recaptcha" src="http://webdeveloperplus.com/wp-content/uploads/2009/03/customized-recaptcha.jpg" alt="customized recaptcha" width="483" height="161" /></p>
<!--No related posts.-->
]]></content:encoded>
			<wfw:commentRss>http://webdeveloperplus.com/php/integrate-customized-recaptcha-in-your-php-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

