<?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>Bagesh Singh&#039;s Blog &#187; php</title>
	<atom:link href="http://www.bageshsingh.com/bagesh-blog/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bageshsingh.com/bagesh-blog</link>
	<description>Shortest Distance to  Web Solutions &#38; Software Solutions</description>
	<lastBuildDate>Wed, 22 Feb 2012 18:42:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>How to Send Email (Text/HTML/Attachments) in php</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-send-email-texthtmlattachments-in-php/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-send-email-texthtmlattachments-in-php/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:30:19 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[ATTACHMENT]]></category>
		<category><![CDATA[DUAL]]></category>
		<category><![CDATA[EMAIL]]></category>
		<category><![CDATA[FORMAT]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[SEND]]></category>
		<category><![CDATA[Sending a Simple Text Email in php]]></category>
		<category><![CDATA[Sending Email with Attachments in php]]></category>
		<category><![CDATA[Sending HTML Email in php]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[SMTP]]></category>
		<category><![CDATA[text]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1447</guid>
		<description><![CDATA[Email is the most popular Internet service today. A plenty of emails are sent and delivered each day. The goal of this tutorial is to demonstrate how to generate and send emails in PHP. So, you want to send automated email messages from your PHP application. This can be in direct response to a user&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>Email is the most popular Internet service today. A plenty of emails are sent and delivered each day. The goal of this tutorial is to demonstrate how to generate and send emails in PHP.</p>
<p>So, you want to send automated email messages from your PHP application. This can be in direct response to a user&#8217;s action, such as signing up for your site, or a recurring event at a set time, such as a monthly newsletter. Sometimes email contains file attachments, both plain text and HTML portions, and so on. To understand how to send each variation that may exist on an email, we will start with the simple example and move to the more complicated.</p>
<ul>
<li>Sending a Simple Text Email</li>
<li>Sending HTML Email</li>
<li>Sending Email with Attachments</li>
</ul>
<p>Note that to send email with PHP you need a working email server that you have permission to use: for Unix machines, this is often Sendmail; for Windows machines, you must set the SMTP directive in your <em>php.ini</em> file to point to your email server.</p>
<p><a name="text"></a>Sending a Simple Text Email<a name="form"></a></p>
<p>At first let&#8217;s consider how to send a simple text email messages. PHP includes the <em>mail()</em> function for sending email, which takes three basic and two optional parameters. These parameters are, in order, the email address to send to, the subject of the email, the message to be sent, additional headers you want to include and finally an additional parameter to the Sendmail program. The <em>mail()</em> function returns True if the message is sent successfully and False otherwise. Have a look at the example:</p>
<div>&lt;?php<br />
//define the receiver of the email<br />
$to = &#8216;youraddress@example.com&#8217;;<br />
//define the subject of the email<br />
$subject = &#8216;Test email&#8217;;<br />
//define the message to be sent. Each line should be separated with \n<br />
$message = &#8220;Hello World!\n\nThis is my first mail.&#8221;;<br />
//define the headers we want passed. Note that they are separated with \r\n<br />
$headers = &#8220;From: webmaster@example.com\r\nReply-To: webmaster@example.com&#8221;;<br />
//send the email<br />
$mail_sent = @mail( $to, $subject, $message, $headers );<br />
//if the message is sent successfully print &#8220;Mail sent&#8221;. Otherwise print &#8220;Mail failed&#8221;<br />
echo $mail_sent ? &#8220;Mail sent&#8221; : &#8220;Mail failed&#8221;;<br />
?&gt;</div>
<p>As you can see, it very easy to send an email. You can add more receivers by either adding their addresses, comma separated, to the $to variable, or by adding cc: or bcc: headers. If you don&#8217;t receive the test mail, you have probably installed PHP incorrectly, or may not have permission to send emails.</p>
<p><img src="http://www.webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="html"></a>Sending HTML Email<a name="code"></a></p>
<p>The next step is to examine how to send HTML email. However, some mail clients cannot understand HTML emails. Therefore it is best to send any HTML email using a multipart construction, where one part contains a plain-text version of the email and the other part is HTML. If your customers have HTML email turned off, they will still get a nice email, even if they don&#8217;t get all of the HTML markup. Have a look at the example:</p>
<div>&lt;?php<br />
//define the receiver of the email<br />
$to = &#8216;youraddress@example.com&#8217;;<br />
//define the subject of the email<br />
$subject = &#8216;Test HTML email&#8217;;<br />
//create a boundary string. It must be unique<br />
//so we use the MD5 algorithm to generate a random hash<br />
$random_hash = md5(date(&#8216;r&#8217;, time()));<br />
//define the headers we want passed. Note that they are separated with \r\n<br />
$headers = &#8220;From: webmaster@example.com\r\nReply-To: webmaster@example.com&#8221;;<br />
//add boundary string and mime type specification<br />
$headers .= &#8221;\r\nContent-Type: multipart/alternative; boundary=\&#8221;PHP-alt-&#8221;.$random_hash.&#8221;\&#8221;";<br />
//define the body of the message.<br />
ob_start(); <span style="color: #007700;">//Turn on output buffering</span><br />
?&gt;<br />
&#8211;PHP-alt-&lt;?php echo $random_hash; ?&gt;<br />
Content-Type: text/plain; charset=&#8221;iso-8859-1&#8243;<br />
Content-Transfer-Encoding: 7bit</p>
<p>Hello World!!!<br />
This is simple text email message.</p>
<p>&#8211;PHP-alt-&lt;?php echo $random_hash; ?&gt;<br />
Content-Type: text/html; charset=&#8221;iso-8859-1&#8243;<br />
Content-Transfer-Encoding: 7bit</p>
<p>&lt;h2&gt;Hello World!&lt;/h2&gt;<br />
&lt;p&gt;This is something with &lt;b&gt;HTML&lt;/b&gt; formatting.&lt;/p&gt;</p>
<p>&#8211;PHP-alt-&lt;?php echo $random_hash; ?&gt;&#8211;<br />
&lt;?<br />
//copy current buffer contents into $message variable and delete current output buffer<br />
$message = ob_get_clean();<br />
//send the email<br />
$mail_sent = @mail( $to, $subject, $message, $headers );<br />
//if the message is sent successfully print &#8220;Mail sent&#8221;. Otherwise print &#8220;Mail failed&#8221;<br />
echo $mail_sent ? &#8220;Mail sent&#8221; : &#8220;Mail failed&#8221;;<br />
?&gt;</p></div>
<p>In the preceding example we add one additional header of Content-type:multipart/alternative and boundary string that marks the different areas of the email. Note that the content type of the message itself is sent as a mail header, while the content types of the individual parts of the message are embedded in the message itself. This way, mail clients can decide which part of the message they want to display.</p>
<p>Sending Email with Attachment<a name="attachment"></a></p>
<p>The last variation that we will consider is email with attachments. To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email. Have a look at the example:</p>
<div>&lt;?php<br />
//define the receiver of the email<br />
$to = &#8216;youraddress@example.com&#8217;;<br />
//define the subject of the email<br />
$subject = &#8216;Test email with attachment&#8217;;<br />
//create a boundary string. It must be unique<br />
//so we use the MD5 algorithm to generate a random hash<br />
$random_hash = md5(date(&#8216;r&#8217;, time()));<br />
//define the headers we want passed. Note that they are separated with \r\n<br />
$headers = &#8220;From: webmaster@example.com\r\nReply-To: webmaster@example.com&#8221;;<br />
//add boundary string and mime type specification<br />
$headers .= &#8220;\r\nContent-Type: multipart/mixed; boundary=\&#8221;PHP-mixed-&#8221;.$random_hash.&#8221;\&#8221;";<br />
//read the atachment file contents into a string,<br />
//encode it with MIME base64,<br />
//and split it into smaller chunks<br />
$attachment = chunk_split(base64_encode(file_get_contents(&#8216;attachment.zip&#8217;)));<br />
//define the body of the message.<br />
ob_start(); //Turn on output buffering<br />
?&gt;<br />
&#8211;PHP-mixed-&lt;?php echo $random_hash; ?&gt;<br />
Content-Type: multipart/alternative; boundary=&#8221;PHP-alt-&lt;?php echo $random_hash; ?&gt;&#8221;</p>
<p>&#8211;PHP-alt-&lt;?php echo $random_hash; ?&gt;<br />
Content-Type: text/plain; charset=&#8221;iso-8859-1&#8243;<br />
Content-Transfer-Encoding: 7bit</p>
<p>Hello World!!!<br />
This is simple text email message.</p>
<p>&#8211;PHP-alt-&lt;?php echo $random_hash; ?&gt;<br />
Content-Type: text/html; charset=&#8221;iso-8859-1&#8243;<br />
Content-Transfer-Encoding: 7bit</p>
<p>&lt;h2&gt;Hello World!&lt;/h2&gt;<br />
&lt;p&gt;This is something with &lt;b&gt;HTML&lt;/b&gt; formatting.&lt;/p&gt;</p>
<p>&#8211;PHP-alt-&lt;?php echo $random_hash; ?&gt;&#8211;</p>
<p>&#8211;PHP-mixed-&lt;?php echo $random_hash; ?&gt;<br />
Content-Type: application/zip; name=&#8221;attachment.zip&#8221;<br />
Content-Transfer-Encoding: base64<br />
Content-Disposition: attachment</p>
<p>&lt;?php echo $attachment; ?&gt;<br />
&#8211;PHP-mixed-&lt;?php echo $random_hash; ?&gt;&#8211;</p>
<p>&lt;?php<br />
//copy current buffer contents into $message variable and delete current output buffer<br />
$message = ob_get_clean();<br />
//send the email<br />
$mail_sent = @mail( $to, $subject, $message, $headers );<br />
//if the message is sent successfully print &#8220;Mail sent&#8221;. Otherwise print &#8220;Mail failed&#8221;<br />
echo $mail_sent ? &#8220;Mail sent&#8221; : &#8220;Mail failed&#8221;;<br />
?&gt;</p></div>
<p>As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64,  split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.</p>
<div id="seo_alrp_related"><h2>Posts Related to How to Send Email (Text/HTML/Attachments) in php</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/05/a-solution-for-e-mail-handling-in-cakephp/" rel="bookmark">A solution for e-mail handling in CakePHP</a></h3><p>The emailComponent (cake\libs\controller\components\email.php) is a way for you to using the same concepts of layouts and view ctp files to send formated messages as text, ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/04/newsletter-email-tracking-read-or-not/" rel="bookmark">Newsletter Email Tracking: Read or Not?</a></h3><p>I have completed first phase of a simple, yet useful Newsletter System. When I demonstrated to the clients, they came up with a question if ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/12/how-to-get-a-facebook-email-address-like-facebook-com/" rel="bookmark">How to Get a Facebook Email Address like @facebook.com?</a></h3><p>How to Get a Facebook Email Address like @facebook.com? Facebook as you know the top social networking site has recently introduced its own email service ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/12/facebook-unveils-email-addresses-new-messaging-features/" rel="bookmark">Facebook Unveils Email Addresses, New Messaging Features</a></h3><p>Facebook CEO Mark Zuckerberg announced that the social network will be launching a revamped messaging product, 'Messages,' that will give users an "@facebook.com" email address. ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/12/facebook-email-service-new-email-in-facebook/" rel="bookmark">Facebook Email Service : new email in facebook</a></h3><p>We have got news reports from many trusted sources that Facebook’s new email service called Project Titan is going to live on coming Monday. So ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-send-email-texthtmlattachments-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>how to work with Directories in php</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-work-with-directories-in-php/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-work-with-directories-in-php/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:28:22 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Creating New Directories]]></category>
		<category><![CDATA[Deleting the Directory and Its Contents]]></category>
		<category><![CDATA[DIRECTORIES]]></category>
		<category><![CDATA[FILES]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[ITERATORS]]></category>
		<category><![CDATA[PHP5]]></category>
		<category><![CDATA[Reading the Contents of a Directory]]></category>
		<category><![CDATA[RECURSION]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1445</guid>
		<description><![CDATA[As is necessary for any language, PHP has a complete set of directory support functions. PHP gives you a variety of functions to read and manipulate directories and directory entries. Like other file-related parts of PHP, the functions are similar to the C functions that accomplish the same tasks, with some simplifications. This tutorial describes [...]]]></description>
			<content:encoded><![CDATA[<p>As is necessary for any language, PHP has a complete set of directory support functions. PHP gives you a variety of functions to read and manipulate directories and directory entries. Like other file-related parts of PHP, the functions are similar to the C functions that accomplish the same tasks, with some simplifications. This tutorial describes how PHP handles directories. You will look at how to create, remove, and read them.</p>
<ul>
<li>Reading the Contents of a Directory</li>
<li>Deleting the Directory and Its Contents</li>
<li>Creating New Directories</li>
</ul>
<p><a name="read"></a>Reading the Contents of a Directory</p>
<p>Let&#8217;s start with simple listing the contents of a directory. We need three functions to perform this task: opendir(), readdir() and closedir(). The opendir() function takes one parameter, which is the directory we want to read, and returns a directory handle to be used in subsequent readdir() and closedir() calls. opendir() returns False if the directory could not be opened.</p>
<p>The readdir() function takes one parameter, which is the handle that opendir() returned and each time we call readdir() it returns the filename of the next file in the directory. readdir() returns False if the end of the directory has been reached. Note that readdir() returns only the names of its items, rather than full paths.</p>
<p>The example below creates a select box that lists all the files in a directory. Copy and paste this code and save it as <em>index.php</em> in a directory you wish do display all files for. It automatically excludes itself from the list, and is easy to modify to make it ignore other files as well:</p>
<div>&lt;?php<br />
// open the current directory<br />
$dhandle = opendir(&#8216;.&#8217;);<br />
// define an array to hold the files<br />
$files = array();</p>
<p>if ($dhandle) {<br />
// loop through all of the files<br />
while (false !== ($fname = readdir($dhandle))) {<br />
// if the file is not this file, and does not start with a &#8216;.&#8217; or &#8216;..&#8217;,<br />
// then store it for later display<br />
if (($fname != &#8216;.&#8217;) &amp;&amp; ($fname != &#8216;..&#8217;) &amp;&amp;<br />
($fname != basename($_SERVER['PHP_SELF']))) {<br />
// store the filename<br />
$files[] = (is_dir( &#8220;./$fname&#8221; )) ? &#8220;(Dir) {$fname}&#8221; : $fname;<br />
}<br />
}<br />
// close the directory<br />
closedir($dhandle);<br />
}</p>
<p>echo &#8220;&lt;select name=\&#8221;file\&#8221;&gt;\n&#8221;;<br />
// Now loop through the files, echoing out a new select option for each one<br />
foreach( $files as $fname )<br />
{<br />
echo &#8220;&lt;option&gt;{$fname}&lt;/option&gt;\n&#8221;;<br />
}<br />
echo &#8220;&lt;/select&gt;\n&#8221;;<br />
?&gt;</p></div>
<p>First, we open the directory for reading with the opendir() function and use a while statement to loop through each of its entries. We call readdir() as part of the while statement&#8217;s test expression, assigning its result to the $fname variable. We are explicitly testing whether the return value is equal to and of the same type as False since otherwise, any directory entry whose name evaluates to False will stop the loop prematurely. Within the body of the while statement, we check if the file is not this file, and does not start with a <strong>.</strong> (current directory) or <strong>..</strong> (parent directory) and then store the file name into the $files array. We also do one more check. If a full file path leads to a directory then we add to the file name &#8220;(Dir)&#8221;.</p>
<p>There is another way to iterate over all files in a directory. PHP 5 has a set of objects called iterators. Iterators help eliminate problems in your code. For instance, PHP 5 provides a DirectoryIterator:</p>
<div>&lt;?php<br />
echo &#8220;&lt;select name=\&#8221;file\&#8221;&gt;\n&#8221;;<br />
foreach (new DirectoryIterator(&#8216;.&#8217;) as $file) {<br />
// if the file is not this file, and does not start with a &#8216;.&#8217; or &#8216;..&#8217;,<br />
// then store it for later display<br />
if ( (!$file-&gt;isDot()) &amp;&amp; ($file-&gt;getFilename() != basename($_SERVER['PHP_SELF'])) ) {<br />
echo &#8220;&lt;option&gt;&#8221;;<br />
// if the element is a directory add to the file name &#8220;(Dir)&#8221;<br />
echo ($file-&gt;isDir()) ? &#8220;(Dir) &#8220;.$file-&gt;getFilename() : $file-&gt;getFilename();<br />
echo &#8220;&lt;/option&gt;\n&#8221;;<br />
}<br />
}<br />
echo &#8220;&lt;/select&gt;\n&#8221;;<br />
?&gt;</div>
<p>This example produces the same results as the earlier code that uses the directory functions, but this code is shorter and safer because you cannot forget the !== = comparison.</p>
<p><img src="http://www.webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="delete"></a>Deleting the Directory and Its Contents</p>
<p>PHP has the rmdir( ) function that takes a directory name as its only parameter and will remove the specified directory from the file system, if the process running your script has the right to do so. However, the rmdir() function works only on empty directories. The example below deletes empty directory named &#8220;temporary&#8221;:</p>
<div>&lt;?php<br />
rmdir( &#8220;temporary&#8221; );<br />
?&gt;</div>
<p>If you want to delete non-empty directory, you should use the recursion. In the following example we create recursive function named deleteDir() that takes a directory name as a parameter and will go through each subdirectory, deleting files as they go. When the directory is empty, we use rmdir() to remove it.</p>
<div>&lt;?php<br />
function deleteDir($dir) {<br />
// open the directory<br />
$dhandle = opendir($dir);</p>
<p>if ($dhandle) {<br />
<span style="color: #007700;">// loop through it</span><br />
while (false !== ($fname = readdir($dhandle))) {<br />
// if the element is a directory, and<br />
// does not start with a &#8216;.&#8217; or &#8216;..&#8217;<br />
// we call deleteDir function recursively<br />
// passing this element as a parameter<br />
if (is_dir( &#8220;{$dir}/{$fname}&#8221; )) {<br />
if (($fname != &#8216;.&#8217;) &amp;&amp; ($fname != &#8216;..&#8217;)) {<br />
echo &#8220;&lt;u&gt;Deleting Files in the Directory&lt;/u&gt;: {$dir}/{$fname} &lt;br /&gt;&#8221;;<br />
deleteDir(&#8220;$dir/$fname&#8221;);<br />
}<br />
<span style="color: #007700;">// the element is a file, so we delete it</span><br />
} else {<br />
echo &#8220;Deleting File: {$dir}/{$fname} &lt;br /&gt;&#8221;;<br />
unlink(&#8220;{$dir}/{$fname}&#8221;);<br />
}<br />
}<br />
closedir($dhandle);<br />
}<br />
<span style="color: #007700;">// now directory is empty, so we can use<br />
// the rmdir() function to delete it</span><br />
echo &#8220;&lt;u&gt;Deleting Directory&lt;/u&gt;: {$dir} &lt;br /&gt;&#8221;;<br />
rmdir($dir);<br />
}</p>
<p>// call deleteDir function and pass to it<br />
// as a parameter a directory name<br />
deleteDir(&#8220;temporary&#8221;);<br />
?&gt;</p></div>
<p>Another way to delete non-empty directory is to use RecursiveDirectoryIterator and RecursiveIteratorIterator. The RecursiveIteratorIterator must be told to provide children (files and subdirectories) before parents with its CHILD_FIRST constant. Have a look at the code:</p>
<div>&lt;?php<br />
function deleteDir($dir) {<br />
$iterator = new RecursiveDirectoryIterator($dir);<br />
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file)<br />
{<br />
if ($file-&gt;isDir()) {<br />
rmdir($file-&gt;getPathname());<br />
} else {<br />
unlink($file-&gt;getPathname());<br />
}<br />
}<br />
rmdir($dir);<br />
}</p>
<p>deleteDir(&#8220;temporary&#8221;);<br />
?&gt;</p></div>
<p>Note: The CHILD_FIRST constant was added with PHP 5.1</p>
<p><img src="http://www.webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="create"></a>Creating New Directories</p>
<p>Creating new directories in PHP is accomplished using the mkdir() function, which takes two parameters. These parameters are, in order, a directory name you want to create and a permission mode for a new directory, which must be an octal number. The mode parameter is optional and has an effect only on Unix systems. Have a look at the example:</p>
<div>&lt;?php<br />
<span style="color: #007700;">// if /path/to/my exists, this should return true<br />
// if PHP has the right permissions</span><br />
mkdir(&#8220;/path/to/directory&#8221;, 0777);<br />
?&gt;</div>
<p>By default, the mkdir() function only creates a directory if its parent exists. In PHP 5 the recursive parameter was added which should be true or false, depending on whether you want to create parent directories or not. In the following example, we pass true as a third parameter to mkdir(), so this makes the function act recursively to create any missing parent directories.</p>
<div>&lt;?php<br />
<span style="color: #007700;">// will create /path/to/directory and<br />
// also create /path and /path/to if needed and allowed<br />
</span>mkdir(&#8220;/path/to/directory&#8221;, 0777, true);<br />
?&gt;</div>
<div id="seo_alrp_related"><h2>Posts Related to how to work with Directories in php</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-create-thumbnail-images-using-php/" rel="bookmark">How to Create Thumbnail Images using PHP</a></h3><p>Download Source This tutorial will describe how to create thumbnail images on the fly using PHP. Furthermore you will learn how to process a whole ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-ftp-functions-list/" rel="bookmark">PHP FTP Functions List</a></h3><p>ftp_cdup — Changes to the parent directory ftp_chdir — Changes directories on a FTP server ftp_close — Closes an FTP connection ftp_connect — Opens an ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/12/www-ab-directory-com-free-directory-submission-website/" rel="bookmark">www.ab-directory.com  free directory submission website</a></h3><p>New Web Directory: The New Web Site Directory A new internet directory of professionally reviewed web sites offering basic and express site submission.  www.ab-directory.com Local ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-file-handling-filesystem-functions-list/" rel="bookmark">PHP File Handling (Filesystem) Functions List</a></h3><p>basename — Returns filename component of path chgrp — Changes file group chmod — Changes file mode chown — Changes file owner clearstatcache — Clears ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/07/seo-faq-google-page-rank-pr/" rel="bookmark">SEO FAQ &#8211; Google Page Rank ( PR )</a></h3><p>1.) I am changing my domain but want to keep my PR, how do I do it? A 301 redirect is the most efficient and ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-work-with-directories-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to make DSN and DSN-less connections</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-make-dsn-and-dsn-less-connections/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-make-dsn-and-dsn-less-connections/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:22:43 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[ACCESS]]></category>
		<category><![CDATA[ADODB]]></category>
		<category><![CDATA[CONNECTION]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[DRIVER]]></category>
		<category><![CDATA[DSN]]></category>
		<category><![CDATA[DSN-LESS]]></category>
		<category><![CDATA[OLEDB]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1441</guid>
		<description><![CDATA[DSN stands for &#8216;Data Source Name&#8217;. It is an easy way to assign useful and easily rememberable names to data sources which may not be limited to databases alone. If you do not know how to set up a system DSN read our tutorial How to set up a system DSN. For our example below [...]]]></description>
			<content:encoded><![CDATA[<p>DSN stands for &#8216;Data Source Name&#8217;. It is an easy way to assign useful and easily rememberable names to data sources which may not be limited to databases alone. If you do not know how to set up a system DSN read our tutorial How to set up a system DSN.</p>
<p>For our example below lets assume that our DSN points to an Access database called &#8216;examples.mdb&#8217; and that we will be selecting records from the table &#8216;cars&#8217;.</p>
<table cellspacing="1">
<tbody>
<tr>
<td id="post-main-8648" valign="top" width="100%">
<div>
<div>&lt;?php</p>
<p>//connect to a DSN &#8220;myDSN&#8221;<br />
$conn = odbc_connect(&#8216;myDSN&#8217;,&#8221;,&#8221;);</p>
<p>if ($conn)<br />
{<br />
//the SQL statement that will query the database<br />
$query = &#8220;select * from cars&#8221;;<br />
//perform the query<br />
$result=odbc_exec($conn, $query);</p>
<p>echo &#8220;&lt;table border=\&#8221;1\&#8221;&gt;&lt;tr&gt;&#8221;;</p>
<p>//print field name<br />
$colName = odbc_num_fields($result);<br />
for ($j=1; $j&lt;= $colName; $j++)<br />
{<br />
echo &#8220;&lt;th&gt;&#8221;;<br />
echo odbc_field_name ($result, $j );<br />
echo &#8220;&lt;/th&gt;&#8221;;<br />
}</p>
<p>//fetch tha data from the database<br />
while(odbc_fetch_row($result))<br />
{<br />
echo &#8220;&lt;tr&gt;&#8221;;<br />
for($i=1;$i&lt;=odbc_num_fields($result);$i++)<br />
{<br />
echo &#8220;&lt;td&gt;&#8221;;<br />
echo odbc_result($result,$i);<br />
echo &#8220;&lt;/td&gt;&#8221;;<br />
}<br />
echo &#8220;&lt;/tr&gt;&#8221;;<br />
}</p>
<p>echo &#8220;&lt;/td&gt; &lt;/tr&gt;&#8221;;<br />
echo &#8220;&lt;/table &gt;&#8221;;</p>
<p>//close the connection<br />
odbc_close ($conn);<br />
}<br />
else echo &#8220;odbc not connected&#8221;;<br />
?&gt;</p></div>
</div>
</td>
</tr>
</tbody>
</table>
<p>Remember that &#8216;myDSN&#8217; above is name of the DSN. Also note that you can change the table name from &#8216;cars&#8217; to the name of your table and point the DSN to whatever database you like. One other thing to remember is that you can set up a DSN on your own machine though if you are using a hosting company you may have to ask the webmaster.</p>
<p>DSN-less connection</p>
<p>DSN-less connections don&#8217;t require creation of system level DSNs for connecting to databases and provide an alternative to DSNs. We will now see how to connect to a database via PHP using Connection String in place of DSN name.</p>
<div>
<div>&lt;?php</p>
<p>//create an instance of the  ADO connection object<br />
$conn = new COM (&#8220;ADODB.Connection&#8221;)<br />
or die(&#8220;Cannot start ADO&#8221;);</p>
<p>//define connection string, specify database driver<br />
$connStr = &#8220;PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source= c:\inetpub\wwwroot\db\examples.mdb&#8221;;<br />
$conn-&gt;open($connStr); <span style="color: #007700;">//Open the connection to the database</span></p>
<p><span style="color: #007700;">//declare the SQL statement that will query the database</span><br />
$query = &#8220;SELECT * FROM cars&#8221;;</p>
<p><span style="color: #007700;">//execute the SQL statement and return records</span><br />
$rs = $conn-&gt;execute($query);</p>
<p>$num_columns = $rs-&gt;Fields-&gt;Count();<br />
echo $num_columns . &#8220;&lt;br&gt;&#8221;;</p>
<p>for ($i=0; $i &lt; $num_columns; $i++) {<br />
$fld[$i] = $rs-&gt;Fields($i);<br />
}</p>
<p>echo &#8220;&lt;table&gt;&#8221;; while (!$rs-&gt;EOF)  <span style="color: #007700;">//carry on looping through while there are records</span><br />
{<br />
echo &#8220;&lt;tr&gt;&#8221;;<br />
for ($i=0; $i &lt; $num_columns; $i++) {<br />
echo &#8220;&lt;td&gt;&#8221; . $fld[$i]-&gt;value . &#8220;&lt;/td&gt;&#8221;;<br />
}<br />
echo &#8220;&lt;/tr&gt;&#8221;;<br />
$rs-&gt;MoveNext(); //move on to the next record<br />
}</p>
<p>echo &#8220;&lt;/table&gt;&#8221;;</p>
<p>//close the connection and recordset objects freeing up resources<br />
$rs-&gt;Close();<br />
$conn-&gt;Close();</p>
<p>$rs = null;<br />
$conn = null;<br />
?&gt;</p></div>
</div>
<div id="seo_alrp_related"><h2>Posts Related to How to make DSN and DSN-less connections</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-connect-to-ms-sql-server-database/" rel="bookmark">How to connect to MS SQL Server database</a></h3><p>Below is the code for connecting to a MSSQL Server database. &lt;?php $myServer = "localhost"; $myUser = "your_name"; $myPass = "your_password"; $myDB = "examples"; //connection ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/paging-using-php-and-mysql/" rel="bookmark">Paging Using PHP and MySQL</a></h3><p>When there's more than one column involved in paging there isn't much that we need to modify. We only need to decide how to count ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-mysql-functions-list/" rel="bookmark">PHP Mysql Functions List</a></h3><p>mysql_affected_rows — Get number of affected rows in previous MySQL operation mysql_change_user — Change logged in user of the active connection mysql_client_encoding — Returns the ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/07/php-mssql-stored-procedure-with-parameters-in-and-out/" rel="bookmark">PHP MSSQL Stored Procedure with Parameters (In and Out)</a></h3><p>I gave up trying to do the output code version of the Stored Procedure call, instead I changed my Stored Procedure to return a single ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/php-export-database-schema-as-xml/" rel="bookmark">PHP: Export Database Schema as XML</a></h3><p>Sometimes it can be useful to have a dump of the current database schema. The script below reads the schema from a MySQL database and outputs ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-make-dsn-and-dsn-less-connections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Blocking access to the login page after three unsuccessful login attempts</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/blocking-access-to-the-login-page-after-three-unsuccessful-login-attempts/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/blocking-access-to-the-login-page-after-three-unsuccessful-login-attempts/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:21:30 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[ATTEMPTS]]></category>
		<category><![CDATA[AUTHORIZATION DEMO]]></category>
		<category><![CDATA[BLOCKING]]></category>
		<category><![CDATA[LOGIN]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[RESTRICTION]]></category>
		<category><![CDATA[UNSUCCESSFUL]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1439</guid>
		<description><![CDATA[Sometimes you need to add an extra protection to password-protected website. This article explains how access to the login page can be restricted after three unsuccessful login attempts. This schema uses visitors IP address to store log attempts in the database and block access to login feature for 30 minutes after third unsuccessful attempt. There [...]]]></description>
			<content:encoded><![CDATA[<p align="justify">Sometimes you need to add an extra protection to password-protected website. This article explains how access to the login page can be restricted after three unsuccessful login attempts. This schema uses visitors IP address to store log attempts in the database and block access to login feature for 30 minutes after third unsuccessful attempt.</p>
<p align="justify">There are a number of reasons to restrict access. One reason is security. Quite often users try to guess login and password combination to get unauthorized access to the system. Another reason is extra load on server.</p>
<p align="justify">So let&#8217;s start. At first you need to create a new table in your database to store information about login attempts from a certain computer. SQL script creating such table in MySQL Server will be the following. For other databases it will slightly differ.</p>
<table cellspacing="1">
<tbody>
<tr>
<td id="post-main-8648" valign="top" width="100%">
<div>
<div>CREATE TABLE `LoginAttempts`<br />
(<br />
`IP` VARCHAR( 20 ) NOT NULL ,<br />
`Attempts` INT NOT NULL ,<br />
`LastLogin` DATETIME NOT NULL<br />
)</div>
</div>
</td>
</tr>
</tbody>
</table>
<p align="justify">It is assumed that you have already had an authorization page. Otherwise you can create it using PHP, SSI, and similar languages. There are no major difficulties in writing this program (script).</p>
<p align="justify">Authorization page should work with two tables: one table where information about registered users is stored and the other one where unsuccessful login attempts are listed.<br />
Before verifying entered data, system has to check if the user exceeded attempts limit or not. If in the LoginAttempts table there are more than two records correspondent to one IP address, then error message will appear saying that access is blocked for a certain period of time. You can set time period at your discretion. Depending on your security policy it can vary from 1 minute to 24 hours or more. In the following example access will be blocked for 30 minutes.</p>
<table cellspacing="1">
<tbody>
<tr>
<td id="post-main-8648" valign="top" width="100%">
<div>
<div>&lt;?php<br />
function confirmIPAddress($value) {</p>
<p>$q = &#8220;SELECT attempts, (CASE when lastlogin is not NULL and DATE_ADD(LastLogin, INTERVAL &#8220;.TIME_PERIOD.<br />
&#8221; MINUTE)&gt;NOW() then 1 else 0 end) as Denied FROM &#8220;.TBL_ATTEMPTS.&#8221; WHERE ip = &#8216;$value&#8217;&#8221;;</p>
<p>$result = mysql_query($q, $this-&gt;connection);<br />
$data = mysql_fetch_array($result);</p>
<p>//Verify that at least one login attempt is in database</p>
<p>if (!$data) {<br />
return 0;<br />
}<br />
if ($data["attempts"] &gt;= ATTEMPTS_NUMBER)<br />
{<br />
if($data["Denied"] == 1)<br />
{<br />
return 1;<br />
}<br />
else<br />
{<br />
$this-&gt;clearLoginAttempts($value);<br />
return 0;<br />
}<br />
}<br />
return 0;<br />
}</p>
<p>function addLoginAttempt($value) {</p>
<p>//Increase number of attempts. Set last login attempt if required.</p>
<p>$q = &#8220;SELECT * FROM &#8220;.TBL_ATTEMPTS.&#8221; WHERE ip = &#8216;$value&#8217;&#8221;;<br />
$result = mysql_query($q, $this-&gt;connection);<br />
$data = mysql_fetch_array($result);</p>
<p>if($data)<br />
{<br />
$attempts = $data["attempts"]+1;</p>
<p>if($attempts==3) {<br />
$q = &#8220;UPDATE &#8220;.TBL_ATTEMPTS.&#8221; SET attempts=&#8221;.$attempts.&#8221;, lastlogin=NOW() WHERE ip = &#8216;$value&#8217;&#8221;;<br />
$result = mysql_query($q, $this-&gt;connection);<br />
}<br />
else {<br />
$q = &#8220;UPDATE &#8220;.TBL_ATTEMPTS.&#8221; SET attempts=&#8221;.$attempts.&#8221; WHERE ip = &#8216;$value&#8217;&#8221;;<br />
$result = mysql_query($q, $this-&gt;connection);<br />
}<br />
}<br />
else {<br />
$q = &#8220;INSERT INTO &#8220;.TBL_ATTEMPTS.&#8221; (attempts,IP,lastlogin) values (1, &#8216;$value&#8217;, NOW())&#8221;;<br />
$result = mysql_query($q, $this-&gt;connection);<br />
}<br />
}</p>
<p>function clearLoginAttempts($value) {<br />
$q = &#8220;UPDATE &#8220;.TBL_ATTEMPTS.&#8221; SET attempts = 0 WHERE ip = &#8216;$value&#8217;&#8221;;<br />
return mysql_query($q, $this-&gt;connection);<br />
}<br />
?&gt;</p></div>
</div>
</td>
</tr>
</tbody>
</table>
<p><img src="http://www.webcheatsheet.com/php/images/blocking_system-access_1.gif" alt="" width="757" height="460" border="0" /></p>
<p align="justify">If attempts limit has not been reached, then the system will check, if the data entered are correct. If the data are verified, information about previous attempts is deleted, and for the next authorization user again will have three login attempts.</p>
<p><img src="http://www.webcheatsheet.com/php/images/blocking_system-access_2.gif" alt="" width="757" height="460" border="0" /></p>
<p align="justify">
You can test this login system online or <a href="http://www.webcheatsheet.com/php/login_page/login_page.zip">download</a> completed php scripts and try to use them on your site.</p>
<div id="seo_alrp_related"><h2>Posts Related to Blocking access to the login page after three unsuccessful login attempts</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/ajax-login-validation-php-jquery/" rel="bookmark">Ajax login validation system in PHP using jQuery</a></h3><p>Last time, I’ve showed you how to check user availability in Ajax using jQuery’s fading effect. But I’ve just shown the example without connecting the ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/create-a-csv-file-from-mysql-with-php/" rel="bookmark">Create a CSV file from MySQL with PHP</a></h3><p>There are a couple of ways to export data from MySQL to a CSV file but neither of them supports adding a header row to ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/09/build-a-file-sharing-application-in-cakephp/" rel="bookmark">Build a file sharing application in cakephp</a></h3><p>The honeymoon is over baby. Now it’s time for the real work to begin. This iteration of our CakePHP tutorial series will result in your ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/record-locking-in-web-applications/" rel="bookmark">Record locking in Web applications</a></h3><p>Record locking is used for preventing simultaneous update of the same data and therefore avoiding inconsistent results. A locked record means it is not available ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/paging-using-php-and-mysql/" rel="bookmark">Paging Using PHP and MySQL</a></h3><p>When there's more than one column involved in paging there isn't much that we need to modify. We only need to decide how to count ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/blocking-access-to-the-login-page-after-three-unsuccessful-login-attempts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Encrypt Passwords in the Database</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-encrypt-passwords-in-the-database/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-encrypt-passwords-in-the-database/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:20:08 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Encrypt]]></category>
		<category><![CDATA[MD5 ALGORITHM]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[Passwords]]></category>
		<category><![CDATA[PROTECTION HASH]]></category>
		<category><![CDATA[SECURE]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1437</guid>
		<description><![CDATA[If you are developing a password-protected web site, you have to make a decision about how to store user password information securely. What is &#8220;secure,&#8221; anyway? Realize that the data in your database is not safe. What if the password to the database is compromised? Then your entire user password database will be compromised as [...]]]></description>
			<content:encoded><![CDATA[<p>If you are developing a password-protected web site, you have to make a decision about how to store user password information securely.</p>
<p>What is &#8220;secure,&#8221; anyway? Realize that the data in your database is not safe. What if the password to the database is compromised? Then your entire user password database will be compromised as well. Even if you are quite certain of the security of your database, your users&#8217; passwords are still accessible to all administrators who work at the Web hosting company where your database is hosted. Scrambling the passwords using some home-brewed algorithm may add some obscurity but not true &#8220;security.&#8221; Another approach would be to encrypt all passwords in your database using some industry-standard cipher, such as the Message-Digest Algorithm 5 (MD5).</p>
<p align="justify">MD5 encryption is a one-way hashing algorithm. Two important properties of the MD5 algorithm are that it is impossible to revert back an encrypted output to the initial, plain-text input, and that any given input always maps to the same encrypted value. This ensures that the passwords stored on the server cannot be deciphered by anyone. This way, even if an attacker gains reading permission to the user table, it will do him no good.</p>
<p align="justify">MD5 does have its weaknesses. MD5 encryption is not infallible: if the password is not strong enough, a brute force attack can still reveal it. So, you can ask: &#8220;Why should I use MD5 if I know it is not the most secure?&#8221; The answer is fairly straightforward: it&#8217;s fast, it&#8217;s easy, and it can be powerful if salted. The greatest advantage of MD5 is its speed and ease of use.</p>
<p align="justify">It is vitally important to understand that password encryption will not protect your website, it can protect your passwords only. If your website does not have sufficient protection, password encryption will not make it safe from cracking. If your system has been cracked, a hacker can inflict a irreparable damage to it and also gain an access to confidential information, including passwords database. But if you store this information encrypted, hackers practically cannot make use of it. Cracking an encrypted password takes a large amount of time and processing power, even on today&#8217;s computers.</p>
<p align="justify">So, let&#8217;s start. First of all, you need to add a new account to your database. The following code allows to do it.</p>
<table cellspacing="1">
<tbody>
<tr>
<td id="post-main-8648" valign="top" width="100%">
<div>
<div>&lt;?php<br />
define(&#8220;DB_SERVER&#8221;, &#8220;localhost&#8221;);<br />
define(&#8220;DB_USER&#8221;, &#8220;your_name&#8221;);<br />
define(&#8220;DB_PASS&#8221;, &#8220;your_pass&#8221;);<br />
define(&#8220;DB_NAME&#8221;, &#8220;your_db&#8221;);<br />
define(&#8220;TBL_USERS&#8221;, &#8220;users_table_name&#8221;);</p>
<p>$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());<br />
mysql_select_db(DB_NAME, $connection) or die(mysql_error());</p>
<p>&#8230;</p>
<p>function addNewUser($username, $password){<br />
global $connection;<br />
$password = md5($password);<br />
$q = &#8220;INSERT INTO &#8220;.TBL_USERS.&#8221; VALUES (&#8216;$username&#8217;, &#8216;$password&#8217;)&#8221;;<br />
return mysql_query($q, $connection);<br />
}<br />
?&gt;</p></div>
</div>
</td>
</tr>
</tbody>
</table>
<p align="justify">Now, when a new user completes the registration form, his password will be encrypted automatically.</p>
<p align="justify">After that we should write code that validates a given username/password pair.</p>
<table cellspacing="1">
<tbody>
<tr>
<td id="post-main-8648" valign="top" width="100%">
<div>
<div>&lt;?php<br />
function checkUserPass($username, $password){<br />
global $connection;</p>
<p>$username = str_replace(&#8220;&#8216;&#8221;,&#8221;&#8221;&#8221;,$username)<br />
$password = md5($password);</p>
<p>// Verify that user is in database<br />
$q = &#8220;SELECT password FROM &#8220;.TBL_USERS.&#8221; WHERE username = &#8216;$username&#8217;&#8221;;<br />
$result = mysql_query($q, $connection);<br />
if(!$result || (mysql_numrows($result) &lt; 1)){<br />
return 1; //Indicates username failure<br />
}</p>
<p>// Retrieve password from result<br />
$dbarray = mysql_fetch_array($result);</p>
<p>// Validate that password is correct<br />
if($password == $dbarray['password']){<br />
return 0; //Success! Username and password confirmed<br />
}<br />
else{<br />
return 1; //Indicates password failure<br />
}<br />
}<br />
?&gt;</p></div>
</div>
</td>
</tr>
</tbody>
</table>
<p align="justify">And what if you already have users&#8217; database ready and want to start using encrypted passwords? To do it, you need to write encypt.php script with the following code and run it in your browser.</p>
<div>
<div>&lt;?php<br />
define(&#8220;DB_SERVER&#8221;, &#8220;localhost&#8221;);<br />
define(&#8220;DB_USER&#8221;, &#8220;your_name&#8221;);<br />
define(&#8220;DB_PASS&#8221;, &#8220;your_pass&#8221;);<br />
define(&#8220;DB_NAME&#8221;, &#8220;your_db&#8221;);<br />
define(&#8220;TBL_USERS&#8221;, &#8220;users_table_name&#8221;);<br />
define(&#8220;FLD_USER&#8221;, &#8220;username_field_name&#8221;);<br />
define(&#8220;FLD_PASS&#8221;, &#8220;password_field_name&#8221;);</p>
<p>set_magic_quotes_runtime(0);</p>
<p>$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());<br />
mysql_select_db(DB_NAME, $connection) or die(mysql_error());</p>
<p>$q = &#8220;SELECT &#8220;.FLD_PASS.&#8221;,&#8221;.FLD_USER.&#8221; FROM &#8220;.TBL_USERS.&#8221;";<br />
$result = mysql_query($q, $connection);</p>
<p>$total=0;<br />
$enc=0;</p>
<p>$doencrypt=false;<br />
if (@$_REQUEST["do"]==&#8221;encrypt&#8221;)<br />
$doencrypt=true;</p>
<p>while($data = mysql_fetch_array($result))<br />
{<br />
if ($doencrypt)<br />
{<br />
$total++;<br />
if (!encrypted($data[0]))<br />
{<br />
$q=&#8221;UPDATE &#8220;.TBL_USERS.&#8221; SET &#8220;.FLD_PASS.&#8221;=&#8217;&#8221;.md5($data[0]).&#8221;&#8216; where &#8220;.FLD_USER.&#8221;=&#8217;&#8221;.<br />
str_replace(&#8220;&#8216;&#8221;,&#8221;&#8221;&#8221;,$data[1]).&#8221;&#8216;&#8221;;<br />
mysql_query($q, $connection);<br />
}<br />
$enc++;<br />
}<br />
else<br />
{<br />
$total++;<br />
if (encrypted($data[0]))<br />
$enc++;<br />
}<br />
}</p>
<p>function encrypted($str)<br />
{<br />
if (strlen($str)!=32)<br />
return false;</p>
<p>for($i=0;$i&lt;32;$i++)<br />
if ((ord($str[$i])&lt;ord(&#8217;0&#8242;) || ord($str[$i])&gt;ord(&#8217;9&#8242;)) &amp;&amp; (ord($str[$i])&lt;ord(&#8216;a&#8217;) || ord($str[$i])&gt;ord(&#8216;f&#8217;)))<br />
return false;</p>
<p>return true;<br />
}<br />
?&gt;</p>
<p>&lt;html&gt;<br />
&lt;head&gt;&lt;title&gt;Encrypt passwords&lt;/title&gt;&lt;/head&gt;<br />
&lt;body&gt;<br />
Total passwords in the table &#8211; &lt;?php echo $total; ?&gt;&lt;br&gt;<br />
&lt;?php if($enc==$total &amp;&amp; $total&gt;0) { ?&gt;<br />
All passwords are encrypted.<br />
&lt;?php } else if($total&gt;0) { ?&gt;<br />
Unencrypted &#8211; &lt;?php echo $total-$enc; ?&gt;&lt;br&gt;&lt;br&gt;<br />
Click &#8220;GO&#8221; to encrypt &lt;?php echo $total-$enc; ?&gt; passwords.&lt;br&gt;<br />
WARNING! There will be no way to decipher the passwords.&lt;br&gt;<br />
&lt;input type=button value=&#8221;GO&#8221; onclick=&#8221;window.location=&#8217;encrypt.php?do=encrypt&#8217;;&#8221;&gt;<br />
&lt;?php } ?&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;</p></div>
</div>
<div id="seo_alrp_related"><h2>Posts Related to How to Encrypt Passwords in the Database</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/password-encryption-and-decryption-technique-in-php/" rel="bookmark">Password Encryption and Decryption Technique in PHP</a></h3><p>I’ve noticed that many of my friends are storing password in database without encrypting them. This is really a bad technique because if somebody who ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-connect-to-mysql-database-using-php/" rel="bookmark">How to Connect to MySQL Database Using PHP?</a></h3><p>&lt;?php $username = "your_name"; $password = "your password"; $hostname = "localhost"; $dbname = "database name"; //Connection to the MySql Database $dbhandle = mysql_connect($hostname, $username, $password) ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/what-is-the-difference-between-mysql_connect-and-mysql_pconnect/" rel="bookmark">What Is the Difference Between Mysql_Connect() and Mysql_Pconnect()?</a></h3><p>When they are using mysql_connect() function, every time it is opening and closing the database connection, depending on the request . mysql_connect() and mysql_pconnect() both ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/ajax-login-validation-php-jquery/" rel="bookmark">Ajax login validation system in PHP using jQuery</a></h3><p>Last time, I’ve showed you how to check user availability in Ajax using jQuery’s fading effect. But I’ve just shown the example without connecting the ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/blocking-access-to-the-login-page-after-three-unsuccessful-login-attempts/" rel="bookmark">Blocking access to the login page after three unsuccessful login attempts</a></h3><p>Sometimes you need to add an extra protection to password-protected website. This article explains how access to the login page can be restricted after three ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-encrypt-passwords-in-the-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Create CAPTCHA Protection using PHP and AJAX</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-create-captcha-protection-using-php-and-ajax/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-create-captcha-protection-using-php-and-ajax/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:18:44 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Javascript Interview Questions]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[CAPTCHA]]></category>
		<category><![CDATA[DYNAMIC IMAGE]]></category>
		<category><![CDATA[GENERATION GD]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[SECURE SPAM]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1435</guid>
		<description><![CDATA[Download Source CAPTCHA is a simple test to determine if a user is a computer or a human. It is used to prevent spam abuse on the websites. So if you use CAPTCHA on your web site forms, this can help in stopping some bots and making life harder for other bots in accessing or using your [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.webcheatsheet.com/php/scripts/ajax_captcha.zip">Download Source</a></p>
<p>CAPTCHA is a simple test to determine if a user is a computer or a human. It is used to prevent spam abuse on the websites. So if you use CAPTCHA on your web site forms, this can help in stopping some bots and making life harder for other bots in accessing or using your forms.</p>
<p>In brief the CAPTCHA protection works by generating a random string, writing it to an image, then storing the string inside of a session or by some other method. This is then checked when the form is submitted.</p>
<p>The goal of this tutorial is to demonstrate how to make your own simple CAPTCHA protection using PHP and AJAX technologies.</p>
<p>This tutorial is very simple, but if you are unfamiliar with PHP and AJAX this is a great place to start. The tutorial consists of a HTML page for presenting a simple form that will send the data, a JavaScript file for handling the Ajax functionality, and a simple PHP page that makes the actual comparison of the what is in the text box compared to what phrase was stored in the image.</p>
<ul>
<li>The AJAX HTML Page (the Front-end)</li>
<li>The JavaScript</li>
<li>The PHP Server Page (the Backend)</li>
<li>The Ways to Make It More Secure</li>
</ul>
<p><a name="#front_end"></a>The AJAX HTML Page (the Front-end)</p>
<p>The front-end of this tutorial is straight forward. We are going to create a simple HTML form with a textbox for entering the security code, dynamically generated image holding this code, a button for submitting, and a DIV that we will display the CAPTCHA test result. The following example shows how you can do that. Create a new file named captcha_test.htm, and add this code to it.</p>
<div>&lt;form id=&#8221;frmCaptcha&#8221; name=&#8221;frmCaptcha&#8221;&gt;<br />
&lt;table&gt;<br />
&lt;tr&gt;<br />
&lt;td align=&#8221;left&#8221;&gt;<br />
&lt;label for=&#8221;captcha&#8221;&gt;Captcha&lt;/label&gt;<br />
&lt;/td&gt;<br />
&lt;td&gt;<br />
&lt;input id=&#8221;txtCaptcha&#8221; type=&#8221;text&#8221; name=&#8221;txtCaptcha&#8221; value=&#8221;" maxlength=&#8221;10&#8243; size=&#8221;32&#8243; /&gt;<br />
&lt;/td&gt;<br />
&lt;td&gt;<br />
&lt;img id=&#8221;imgCaptcha&#8221; src=&#8221;create_image.php&#8221; /&gt;<br />
&lt;/td&gt;<br />
&lt;/tr&gt;<br />
&lt;tr&gt;<br />
&lt;td&gt;&amp;nbsp;&lt;/td&gt;<br />
&lt;td&gt;<br />
&lt;input id=&#8221;btnCaptcha&#8221; type=&#8221;button&#8221; value=&#8221;Captcha Test&#8221; name=&#8221;btnCaptcha&#8221;<br />
onclick=&#8221;getParam(document.frmCaptcha)&#8221; /&gt;<br />
&lt;/td&gt;<br />
&lt;/tr&gt;<br />
&lt;/table&gt;</p>
<p>&lt;div id=&#8221;result&#8221;&gt;&amp;nbsp;&lt;/div&gt;<br />
&lt;/form&gt;</p></div>
<p>After the textbox and the button we have added the result DIV. We have given it an ID so we can address it through the DOM in our JavaScript. It can easily be a SPAN or any other HTML element that can contain text. The button onclick event will start the AJAX request to the server to make the comparison.</p>
<p>Below is a php script that generates the CAPTCHA image and set a session that stores the security code. Create a new file named create_image.php, and add this code to it.</p>
<div>&lt;?php<br />
//Start the session so we can store what the security code actually is<br />
session_start();</p>
<p>//Send a generated image to the browser<br />
create_image();<br />
exit();</p>
<p>function create_image()<br />
{<br />
//Let&#8217;s generate a totally random string using md5<br />
$md5_hash = md5(rand(0,999));<br />
//We don&#8217;t need a 32 character long string so we trim it down to 5<br />
$security_code = substr($md5_hash, 15, 5);</p>
<p>//Set the session to store the security code<br />
$_SESSION["security_code"] = $security_code;</p>
<p>//Set the image width and height<br />
$width = 100;<br />
$height = 20;</p>
<p>//Create the image resource<br />
$image = ImageCreate($width, $height);</p>
<p>//We are making three colors, white, black and gray<br />
$white = ImageColorAllocate($image, 255, 255, 255);<br />
$black = ImageColorAllocate($image, 0, 0, 0);<br />
$grey = ImageColorAllocate($image, 204, 204, 204);</p>
<p>//Make the background black<br />
ImageFill($image, 0, 0, $black);</p>
<p>//Add randomly generated string in white to the image<br />
ImageString($image, 3, 30, 3, $security_code, $white);</p>
<p>//Throw in some lines to make it a little bit harder for any bots to break<br />
ImageRectangle($image,0,0,$width-1,$height-1,$grey);<br />
imageline($image, 0, $height/2, $width, $height/2, $grey);<br />
imageline($image, $width/2, 0, $width/2, $height, $grey);</p>
<p>//Tell the browser what kind of file is come in<br />
header(&#8220;Content-Type: image/jpeg&#8221;);</p>
<p>//Output the newly created image in jpeg format<br />
ImageJpeg($image);</p>
<p>//Free up resources<br />
ImageDestroy($image);<br />
}<br />
?&gt;</p></div>
<p>If you view create_image.php in a browser, you should see a new JPEG image every time you refresh the page. You should see the black box with some letters and numbers on it. For more details how to create images on the fly read our tutorial Dynamic Image Generation.</p>
<p>The last we have to do is to include the JavaScript file that we will create on the next step.</p>
<div>&lt;script language=&#8221;JavaScript&#8221; type=&#8221;text/javascript&#8221; src=&#8221;ajax_captcha.js&#8221;&gt;&lt;/script&gt;</div>
<p><img src="http://www.webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="javascript"></a>The JavaScript</p>
<p>The JavaScript will be placed in an external file called ajax_captcha.js. Let&#8217;s look into the JavaScript code.</p>
<p>The first function simply returns a browser specific XmlHttpRequest object. Unfortunately AJAX is supported slightly differently in IE than it is Safari, Opera and Mozilla-based browsers like Firefox. Microsoft Internet Explorer uses an Active X object while Mozilla and Safari use a native object.</p>
<div>//Gets the browser specific XmlHttpRequest Object<br />
function getXmlHttpRequestObject() {<br />
if (window.XMLHttpRequest) {<br />
return new XMLHttpRequest(); //Mozilla, Safari &#8230;<br />
} else if (window.ActiveXObject) {<br />
return new ActiveXObject(&#8220;Microsoft.XMLHTTP&#8221;); //IE<br />
} else {<br />
//Display our error message<br />
alert(&#8220;Your browser doesn&#8217;t support the XmlHttpRequest object.&#8221;);<br />
}<br />
}</div>
<p>The next step we will create our XmlHttpRequest object that we can use to make the requests.</p>
<div>//Our XmlHttpRequest object<br />
var receiveReq = getXmlHttpRequestObject();</div>
<p>After that we create a function that will make the AJAX request. This function gets two parameters: the url to send to the server and a parameter to the url with the content of the input field.</p>
<div>//Initiate the AJAX request<br />
function makeRequest(url, param) {<br />
//If our readystate is either not started or finished, initiate a new request<br />
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {<br />
//Set up the connection to captcha_test.html. True sets the request to asyncronous(default)<br />
receiveReq.open(&#8220;POST&#8221;, url, true);<br />
//Set the function that will be called when the XmlHttpRequest objects state changes<br />
receiveReq.onreadystatechange = updatePage;</p>
<p>//Add HTTP headers to the request<br />
receiveReq.setRequestHeader(&#8220;Content-type&#8221;, &#8220;application/x-www-form-urlencoded&#8221;);<br />
receiveReq.setRequestHeader(&#8220;Content-length&#8221;, param.length);<br />
receiveReq.setRequestHeader(&#8220;Connection&#8221;, &#8220;close&#8221;);</p>
<p>//Make the request<br />
receiveReq.send(param);<br />
}<br />
}</p></div>
<p>At first we check if our XmlHttpRequest object is ready to make a request. If our readystate is either not started or finished then we initiate a new request. Next we open the connection to our server PHP page with the appended querystring and mark it as a &#8220;POST&#8221; request. After that we add HTTP headers to the request so that the server processes the request correctly. The next line defines the updatePage() function that will be called when we recieve the AJAX response. Finally, we actually send the request to the server.</p>
<p>The updatePage() function executes every time the state of the XmlHttpRequest object changes.</p>
<div>//Called every time our XmlHttpRequest objects state changes<br />
function updatePage() {<br />
//Check if our response is ready<br />
if (receiveReq.readyState == 4) {<br />
//Set the content of the DIV element with the response text<br />
document.getElementById(&#8216;result&#8217;).innerHTML = receiveReq.responseText;<br />
//Get a reference to CAPTCHA image<br />
img = document.getElementById(&#8216;imgCaptcha&#8217;);<br />
//Change the image<br />
img.src = &#8216;create_image.php?&#8217; + Math.random();<br />
}<br />
}</div>
<p>At first we need to make sure our response is ready. If it is, then the content of the DIV element is filled with the response text and the CAPTCHA image is changed. One other thing you must remember you must have different names for each image. For that purpose we use the random() function.</p>
<p>The last function will be called every time the form is submitted. It gets the value from the text box, sets the url and passes them as a parameters to makeRequest() function.</p>
<div>//Called every time when form is perfomed<br />
function getParam(theForm) {<br />
//Set the URL<br />
var url = &#8216;captcha.php&#8217;;<br />
//Set up the parameters of our AJAX call<br />
var postStr = theForm.txtCaptcha.name + &#8220;=&#8221; + encodeURIComponent( theForm.txtCaptcha.value );<br />
//Call the function that initiate the AJAX request<br />
makeRequest(url, postStr);<br />
}</div>
<p>That&#8217;s all. If we open our page, type the security code into the text box and click the button, our DIV element will read the CAPTCHA test result without having to refresh the page.</p>
<p><img src="http://www.webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><a><span style="color: #999999; font-size: x-small;">Back to top</span></a></p>
<p><a name="backend"></a>The PHP Server Page (the Backend)</p>
<p>The server-side PHP file will make the actual comparison and return the result. This is very simple PHP page that only prints the result of the CAPTCHA test. You can add needed functionality yourselves. For example, if your HTML form will contain some other fields, you can send their data using the POST method and then output the data on the screen or add it into the database for further use.</p>
<div>&lt;?php<br />
//Continue the session<br />
session_start();</p>
<p>//Make sure that the input come from a posted form. Otherwise quit immediately<br />
if ($_SERVER["REQUEST_METHOD"] &lt;&gt; &#8220;POST&#8221;)<br />
die(&#8220;You can only reach this page by posting from the html form&#8221;);</p>
<p>//Check if the security code and the session value are not blank<br />
//and if the input text matches the stored text<br />
if ( ($_REQUEST["txtCaptcha"] == $_SESSION["security_code"]) &amp;&amp;<br />
(!empty($_REQUEST["txtCaptcha"]) &amp;&amp; !empty($_SESSION["security_code"])) ) {<br />
echo &#8220;&lt;h1&gt;Test successful!&lt;/h1&gt;&#8221;;<br />
} else {<br />
echo &#8220;&lt;h1&gt;Test failed! Try again!&lt;/h1&gt;&#8221;;<br />
}<br />
?&gt;</p></div>
<p>The session_start() simply continues the session. Then it&#8217;s just a simple text matching which is done by the if statement. If the input text matches the stored text then the success message displayed, otherwise error message. If someone is trying to outwit you, then you should probably use a more secure way besides storing the security code in a session or a cookie that always has the same name. As an example you can store this data in MySQL database.</p>
<p>Create a new file named captcha.php, and add the code from the preceding example to it. And that&#8217;s all for the server-side.</p>
<p><a name="#conclusion"></a>The Ways to Make It More Secure</p>
<p>You can see how it is easy to use PHP with Ajax technologies. This is very simple CAPTCHA test you can use but I&#8217;m sure you will think how to make it more powerful, robust and secure. In conclusion I just want to suggest some several things you can do to make it more secure:</p>
<ul>
<li>Rotate the text randomly</li>
<li>Add random spaces in between characters</li>
<li>Use a TTF fonts and change the font randomly every time</li>
<li>Use a random text and image size every time</li>
<li>Use more advanced text distortion and colors</li>
<li>Move the lines randomly</li>
<li>Store the password in a random cookie</li>
</ul>
<div id="seo_alrp_related"><h2>Posts Related to How to Create CAPTCHA Protection using PHP and AJAX </h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/02/using-jquery-ajax-to-call-asp-net-json-web-service/" rel="bookmark">Using jQuery Ajax to call ASP.NET JSON web service</a></h3><p>The jQuery Ajax infrastructure allows you to perform asynchronous HTTP requests which makes it easy to call an ASP.NET JSON web service, using this api. ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/create-a-twitter-ajax-button-with-mootools-jquery-or-dojo/" rel="bookmark">Create a Twitter AJAX Button with MooTools, jQuery, or Dojo</a></h3><p>There's nothing like a subtle, slick website widget that effectively uses CSS and JavaScript to enhance the user experience.  Of course widgets like that take ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/05/a-easy-captcha-component-implentation-into-cakephp/" rel="bookmark">A easy captcha component implentation into cakephp.</a></h3><p>First save the code below into a file called captcha.php and put it in your controller components folder Then very important create a folder called ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/02/customize-the-display-of-error-messages-while-using-the-jquery-validation-plugin/" rel="bookmark">Customize the Display of Error Messages while using the jQuery Validation Plugin</a></h3><p>Here’s a simple way to customize the placement of the error labels while using the jQuery Validation Plugin. We will display the error message in ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-create-captcha-protection-using-php-and-ajax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Pass  JavaScript variables to PHP</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-pass-javascript-variables-to-php/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-pass-javascript-variables-to-php/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:17:22 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[Javascript Interview Questions]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[SCRIPTS GET]]></category>
		<category><![CDATA[VARIABLES PASSING]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1433</guid>
		<description><![CDATA[JavaScript is mainly used as a client side scripting language, while PHP is a server side technology. Unlike Java or ASP.Net, PHP doesn&#8217;t have tools to make it work client side. That is why you need to combine JavaScript and PHP scripts to develop powerful web-applications. One of the frequent problems is defining visitor’s screen [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript is mainly used as a client side scripting language, while PHP is a server side technology. Unlike Java or ASP.Net, PHP doesn&#8217;t have tools to make it work client side. That is why you need to combine JavaScript and PHP scripts to develop powerful web-applications.</p>
<p>One of the frequent problems is defining visitor’s screen resolution using JavaScript tools and passing this data to PHP-script. The following script provides solution for this problem:</p>
<table cellspacing="1">
<tbody>
<tr>
<td id="post-main-8648" valign="top" width="100%">
<div>
<div>&lt;script type=&#8221;text/javascript&#8221;&gt;</p>
<p>width = screen.width;<br />
height = screen.height;</p>
<p>if (width &gt; 0 &amp;&amp; height &gt;0) {<br />
window.location.href = &#8220;http://localhost/main.php?width=&#8221; + width + &#8220;&amp;height=&#8221; + height;<br />
} else<br />
exit();</p>
<p>&lt;/script&gt;</p></div>
</div>
</td>
</tr>
</tbody>
</table>
<p>Copy and paste this code snippet in the text editor, save it as index.htm and run it in your browser. After this code has been executed, a user is automatically redirected to the main.php page where screen resolution is displayed in the browser window.</p>
<p>The main.php looks as follows:</p>
<table cellspacing="1">
<tbody>
<tr>
<td id="post-main-8648" valign="top" width="100%">
<div>
<div>&lt;?php<br />
echo &#8220;&lt;h1&gt;Screen Resolution:&lt;/h1&gt;&#8221;;<br />
echo &#8220;Width  : &#8220;.$_GET['width'].&#8221;&lt;br&gt;&#8221;;<br />
echo &#8220;Height : &#8220;.$_GET['height'].&#8221;&lt;br&gt;&#8221;;<br />
?&gt;</div>
</div>
</td>
</tr>
</tbody>
</table>
<p>As you can see, passing JavaScript variables in PHP is similar to sending data using GET method.</p>
<div id="seo_alrp_related"><h2>Posts Related to How to Pass  JavaScript variables to PHP</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/03/how-to-pass-javascript-variable-to-php/" rel="bookmark">how to Pass javascript variable to PHP</a></h3><p>There is lots of way to pass the php script data in javascript like simply echoing php varible in PHP. Yes you can simply echo ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/03/javascript-interview-questions-%e2%80%93-third-part-of-jquery-interview-question/" rel="bookmark">Javascript Interview Questions – Third Part of Jquery Interview question</a></h3><p>How to write a script for “Select” lists using JavaScript? 1. To remove an item from a list set it to null mySelectObject.options[3] = null ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/04/innovative-gateway-api-code-innovative-gateway-integration/" rel="bookmark">Innovative Gateway API CODE  | Innovative Gateway Integration</a></h3><p>Gateway Toolkits Windows API Windows Client Install including MS Installer v1.0.0.5 Windows Client Install including MS Installer v1.0.0.4 Windows Client Objects v1.0.0.4 Windows Client ASP ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/03/javascript-interview-questions-%e2%80%93-second-part-of-jquery-interview-question/" rel="bookmark">Javascript Interview Questions – Second Part of Jquery Interview question</a></h3><p>What is JavaScript? JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/02/expand-a-textbox-on-focus-using-jquery/" rel="bookmark">Expand a TextBox on Focus using jQuery</a></h3><p>Here’s how to animate and expand the height and width of a TextBox when it receives focus. After a delay, the TextBox returns to its ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-pass-javascript-variables-to-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Create Thumbnail Images using PHP</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-create-thumbnail-images-using-php/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-create-thumbnail-images-using-php/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:14:48 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[DYNAMIC IMAGE]]></category>
		<category><![CDATA[GD2 STORE]]></category>
		<category><![CDATA[THUMBNAIL GENERATION]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1427</guid>
		<description><![CDATA[Download Source This tutorial will describe how to create thumbnail images on the fly using PHP. Furthermore you will learn how to process a whole folder of images and create their thumbnails. Since this requires the GD library, you will need an installation of PHP with at least GD 2.0.1 enabled. Below we will create [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.webcheatsheet.com/php/scripts/thumb.zip">Download Source</a></p>
<p>This tutorial will describe how to create thumbnail images on the fly using PHP. Furthermore you will learn how to process a whole folder of images and create their thumbnails. Since this requires the GD library, you will need an installation of PHP with at least GD 2.0.1 enabled.</p>
<p>Below we will create a PHP script that contains two functions. The first one scans a provided directory for any .JPG images and, for each one, creates a thumbnail in the specified folder using the GD image functions. The second function creates an HTML file in the same directory as the script, which contains all of the thumbnails with links to the original images. This could be the basis of advanced photo gallery software.</p>
<p>The code below creates a function named <em>createThumbs</em> that will get three parameters. The first and the second is correspondingly the path to the directory that contains original images and the path to the directory in which thumbnails will be placed. The third parameter is the width you want for the thumbnail images.</p>
<div>&lt;?php<br />
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )<br />
{<br />
// open the directory<br />
$dir = opendir( $pathToImages );</p>
<p>// loop through it, looking for any/all JPG files:<br />
while (false !== ($fname = readdir( $dir ))) {<br />
// parse path for the extension<br />
$info = pathinfo($pathToImages . $fname);<br />
// continue only if this is a JPEG image<br />
if ( strtolower($info['extension']) == &#8216;jpg&#8217; )<br />
{<br />
echo &#8220;Creating thumbnail for {$fname} &lt;br /&gt;&#8221;;</p>
<p>// load image and get image size<br />
$img = imagecreatefromjpeg( &#8220;{$pathToImages}{$fname}&#8221; );<br />
$width = imagesx( $img );<br />
$height = imagesy( $img );</p>
<p>// calculate thumbnail size<br />
$new_width = $thumbWidth;<br />
$new_height = floor( $height * ( $thumbWidth / $width ) );</p>
<p>// create a new temporary image<br />
$tmp_img = imagecreatetruecolor( $new_width, $new_height );</p>
<p>// copy and resize old image into new image<br />
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );</p>
<p>// save thumbnail into a file<br />
imagejpeg( $tmp_img, &#8220;{$pathToThumbs}{$fname}&#8221; );<br />
}<br />
}<br />
// close the directory<br />
closedir( $dir );<br />
}<br />
// call createThumb function and pass to it as parameters the path<br />
// to the directory that contains images, the path to the directory<br />
// in which thumbnails will be placed and the thumbnail&#8217;s width.<br />
// We are assuming that the path will be a relative path working<br />
// both in the filesystem, and through the web for links<br />
createThumbs(&#8220;upload/&#8221;,&#8221;upload/thumbs/&#8221;,100);<br />
?&gt;</p></div>
<p>At first we open the directory with images and iterate through it, looking for all .JPG files. Next we create thumbnails for each image in the directory. To create a thumbnail, we read in the file using the <em>imagecreatefromjpeg()</em> function and calculate the new thumbnail size. <em>imagesx()</em> and <em>imagesy()</em> functions return the width and height of the image respectively. Next we create a new image using the <em>imagecreatetruecolor()</em>. Finally, we copy and resize the original file with the <em>imagecopyresized()</em> function and save thumbnail with <em>imagejpeg()</em>.</p>
<p>The second part of the code creates the function named <em>createGallery</em> which gets two parameters (the relative paths to the directories in which images and thumbnails are stored) and creates an HTML page which contains all of the thumbnails with links to the original images.</p>
<div>&lt;?php<br />
function createGallery( $pathToImages, $pathToThumbs )<br />
{<br />
echo &#8220;Creating gallery.html &lt;br /&gt;&#8221;;</p>
<p>$output = &#8220;&lt;html&gt;&#8221;;<br />
$output .= &#8220;&lt;head&gt;&lt;title&gt;Thumbnails&lt;/title&gt;&lt;/head&gt;&#8221;;<br />
$output .= &#8220;&lt;body&gt;&#8221;;<br />
$output .= &#8220;&lt;table cellspacing=\&#8221;0\&#8221; cellpadding=\&#8221;2\&#8221; width=\&#8221;500\&#8221;&gt;&#8221;;<br />
$output .= &#8220;&lt;tr&gt;&#8221;;</p>
<p>// open the directory<br />
$dir = opendir( $pathToThumbs );</p>
<p>$counter = 0;<br />
// loop through the directory<br />
while (false !== ($fname = readdir($dir)))<br />
{<br />
// strip the . and .. entries out<br />
if ($fname != &#8216;.&#8217; &amp;&amp; $fname != &#8216;..&#8217;)<br />
{<br />
$output .= &#8220;&lt;td valign=\&#8221;middle\&#8221; align=\&#8221;center\&#8221;&gt;&lt;a href=\&#8221;{$pathToImages}{$fname}\&#8221;&gt;&#8221;;<br />
$output .= &#8220;&lt;img src=\&#8221;{$pathToThumbs}{$fname}\&#8221; border=\&#8221;0\&#8221; /&gt;&#8221;;<br />
$output .= &#8220;&lt;/a&gt;&lt;/td&gt;&#8221;;</p>
<p>$counter += 1;<br />
if ( $counter % 4 == 0 ) { $output .= &#8220;&lt;/tr&gt;&lt;tr&gt;&#8221;; }<br />
}<br />
}<br />
// close the directory<br />
closedir( $dir );</p>
<p>$output .= &#8220;&lt;/tr&gt;&#8221;;<br />
$output .= &#8220;&lt;/table&gt;&#8221;;<br />
$output .= &#8220;&lt;/body&gt;&#8221;;<br />
$output .= &#8220;&lt;/html&gt;&#8221;;</p>
<p>// open the file<br />
$fhandle = fopen( &#8220;gallery.html&#8221;, &#8220;w&#8221; );<br />
// write the contents of the $output variable to the file<br />
fwrite( $fhandle, $output );<br />
// close the file<br />
fclose( $fhandle );<br />
}<br />
// call createGallery function and pass to it as parameters the path<br />
// to the directory that contains images and the path to the directory<br />
// in which thumbnails will be placed. We are assuming that<br />
// the path will be a relative path working<br />
// both in the filesystem, and through the web for links<br />
createGallery(&#8220;upload/&#8221;,&#8221;upload/thumbs/&#8221;);<br />
?&gt;</p></div>
<p>First, we open the directory with thumbnails. Next we iterate through files in the directory and put the HTML into a string variable. The variable contents then written into a file using <em>fopen()</em>, <em>fwrite()</em>, and <em>fclose()</em> functions.</p>
<p>As you can see, adding on the fly generated thumbnails to your website with GD library and PHP is quite easy to accomplish.</p>
<div id="seo_alrp_related"><h2>Posts Related to How to Create Thumbnail Images using PHP</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-work-with-directories-in-php/" rel="bookmark">how to work with Directories in php</a></h3><p>As is necessary for any language, PHP has a complete set of directory support functions. PHP gives you a variety of functions to read and ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/07/simple-image-thumbnail-creator-in-php/" rel="bookmark">Simple image thumbnail creator in PHP</a></h3><p>This is a very simple function, but very useful for resizing JPEG images on the fly. You need to make sure GD is enabled on ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/05/image-upload-and-resize-component-for-cakephp-1-2/" rel="bookmark">Image Upload and Resize Component for CakePHP 1.2</a></h3><p>############## image.php ##################### create a components image in following given path /app/controllers/components/image.php /* File: /app/controllers/components/image.php */ class ImageComponent extends Object { /* * Uploads an ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/07/phpthumb-the-thumbnail-generator/" rel="bookmark">phpThumb(): the thumbnail generator</a></h3><p>phpThumb() uses the GD library to create thumbnails from images (JPEG, PNG, GIF, BMP, etc) on the fly. The output size is configurable (can be ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-file-handling-filesystem-functions-list/" rel="bookmark">PHP File Handling (Filesystem) Functions List</a></h3><p>basename — Returns filename component of path chgrp — Changes file group chmod — Changes file mode chown — Changes file owner clearstatcache — Clears ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-create-thumbnail-images-using-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Regular Expressions with PHP and with advance php</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/using-regular-expressions-with-php-and-with-advance-php/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/using-regular-expressions-with-php-and-with-advance-php/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:13:47 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[FILTER]]></category>
		<category><![CDATA[MATCH]]></category>
		<category><![CDATA[PATTERN]]></category>
		<category><![CDATA[PERL]]></category>
		<category><![CDATA[REGULAR EXPRESSION]]></category>
		<category><![CDATA[REPLACE]]></category>
		<category><![CDATA[SPLIT]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1425</guid>
		<description><![CDATA[Regular expressions are a powerful tool for examining and modifying text. Regular expressions themselves, with a general pattern notation almost like a mini programming language, allow you to describe and parse text. They enable you to search for patterns within a string, extracting matches flexibly and precisely. However, you should note that because regular expressions [...]]]></description>
			<content:encoded><![CDATA[<p>Regular expressions are a powerful tool for examining and modifying text. Regular expressions themselves, with a general pattern notation almost like a mini programming language, allow you to describe and parse text. They enable you to search for patterns within a string, extracting matches flexibly and precisely. However, you should note that because regular expressions are more powerful, they are also slower than the more basic string functions. You should only use regular expressions if you have a particular need.</p>
<p>This tutorial gives a brief overview of basic regular expression syntax and then considers the functions that PHP provides for working with regular expressions.</p>
<ul>
<li>The Basics</li>
<li>Matching Patterns</li>
<li>Replacing Patterns</li>
<li>Array Processing</li>
</ul>
<p>PHP supports two different types of regular expressions: POSIX-extended and Perl-Compatible Regular Expressions (PCRE). The PCRE functions are more powerful than the POSIX ones, and faster too, so we will concentrate on them.</p>
<p><a name="basics"></a>The Basics</p>
<p>In a regular expression, most characters match only themselves. For instance, if you search for the regular expression &#8220;foo&#8221; in the string &#8220;John plays football,&#8221; you get a match because &#8220;foo&#8221; occurs in that string. Some characters have special meanings in regular expressions. For instance, a dollar sign ($) is used to match strings that end with the given pattern. Similarly, a caret (^) character at the beginning of a regular expression indicates that it must match the beginning of the string. The characters that match themselves are called literals. The characters that have special meanings are called metacharacters.</p>
<p>The dot (.) metacharacter matches any single character except newline (\). So, the pattern h.t matches hat, hothit, hut, h7t, etc. The vertical pipe (|) metacharacter is used for alternatives in a regular expression. It behaves much like a logical OR operator and you should use it if you want to construct a pattern that matches more than one set of characters. For instance, the pattern Utah|Idaho|Nevada matches strings that contain &#8220;Utah&#8221; or &#8220;Idaho&#8221; or &#8220;Nevada&#8221;. Parentheses give us a way to group sequences. For example, (Nant|b)ucket matches &#8220;Nantucket&#8221; or &#8220;bucket&#8221;. Using parentheses to group together characters for alternation is called grouping.</p>
<p>If you want to match a literal metacharacter in a pattern, you have to escape it with a backslash.</p>
<p>To specify a set of acceptable characters in your pattern, you can either build a character class yourself or use a predefined one. A character class lets you represent a bunch of characters as a single item in a regular expression. You can build your own character class by enclosing the acceptable characters in square brackets. A character class matches any one of the characters in the class. For example a character class [abc] matches a, b or c. To define a range of characters, just put the first and last characters in, separated by hyphen. For example, to match all alphanumeric characters: [a-zA-Z0-9]. You can also create a negated character class, which matches any character that is not in the class. To create a negated character class, begin the character class with ^: [^0-9].</p>
<p>The metacharacters +, *, ?, and {} affect the number of times a pattern should be matched. + means &#8220;Match one or more of the preceding expression&#8221;, * means &#8220;Match zero or more of the preceding expression&#8221;, and ? means &#8220;Match zero or one of the preceding expression&#8221;. Curly braces {} can be used differently. With a single integer, {n} means &#8220;match exactly n occurrences of the preceding expression&#8221;, with one integer and a comma, {n,} means &#8220;match n or more occurrences of the preceding expression&#8221;, and with two comma-separated integers {n,m} means &#8220;match the previous character if it occurs at least n times, but no more than m times&#8221;.</p>
<p>Now, have a look at the examples:</p>
<table width="100%" cellspacing="1" cellpadding="1">
<tbody>
<tr>
<td width="30%">Regular Expression</td>
<td>Will match&#8230;</td>
</tr>
<tr>
<td>foo</td>
<td>The string &#8220;foo&#8221;</td>
</tr>
<tr>
<td>^foo</td>
<td>&#8220;foo&#8221; at the start of a string</td>
</tr>
<tr>
<td>foo$</td>
<td>&#8220;foo&#8221; at the end of a string</td>
</tr>
<tr>
<td>^foo$</td>
<td>&#8220;foo&#8221; when it is alone on a string</td>
</tr>
<tr>
<td>[abc]</td>
<td>a, b, or c</td>
</tr>
<tr>
<td>[a-z]</td>
<td>Any lowercase letter</td>
</tr>
<tr>
<td>[^A-Z]</td>
<td>Any character that is not a uppercase letter</td>
</tr>
<tr>
<td>(gif|jpg)</td>
<td>Matches either &#8220;gif&#8221; or &#8220;jpeg&#8221;</td>
</tr>
<tr>
<td>[a-z]+</td>
<td>One or more lowercase letters</td>
</tr>
<tr>
<td>[0-9\.\-]</td>
<td>Аny number, dot, or minus sign</td>
</tr>
<tr>
<td>^[a-zA-Z0-9_]{1,}$</td>
<td>Any word of at least one letter, number or _</td>
</tr>
<tr>
<td>([wx])([yz])</td>
<td>wy, wz, xy, or xz</td>
</tr>
<tr>
<td>[^A-Za-z0-9]</td>
<td>Any symbol (not a number or a letter)</td>
</tr>
<tr>
<td>([A-Z]{3}|[0-9]{4})</td>
<td>Matches three letters or four numbers</td>
</tr>
</tbody>
</table>
<p>Perl-Compatible Regular Expressions emulate the Perl syntax for patterns, which means that each pattern must be enclosed in a pair of delimiters. Usually, the slash (/) character is used. For instance, /pattern/.</p>
<p>The PCRE functions can be divided in several classes: matching, replacing, splitting and filtering.</p>
<p><img src="http://www.webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="match"></a>Matching Patterns</p>
<p>The <em>preg_match()</em> function performs Perl-style pattern matching on a string. <em>preg_match()</em> takes two basic and three optional parameters. These parameters are, in order, a regular expression string, a source string, an array variable which stores matches, a flag argument and an offset parameter that can be used to specify the alternate place from which to start the search:</p>
<div>preg_match ( pattern, subject [, matches [, flags [, offset]]])</div>
<p>The <em>preg_match()</em> function returns 1 if a match is found and 0 otherwise. Let&#8217;s search the string &#8220;Hello World!&#8221; for the letters &#8220;ll&#8221;:</p>
<div>&lt;?php<br />
if (preg_match(&#8220;/ell/&#8221;, &#8220;Hello World!&#8221;, $matches)) {<br />
echo &#8220;Match was found &lt;br /&gt;&#8221;;<br />
echo $matches[0];<br />
}<br />
?&gt;</div>
<p>The letters &#8220;ll&#8221; exist in &#8220;Hello&#8221;, so <em>preg_match()</em> returns 1 and the first element of the $matches variable is filled with the string that matched the pattern. The regular expression in the next example is looking for the letters &#8220;ell&#8221;, but looking for them with following characters:</p>
<div>&lt;?php<br />
if (preg_match(&#8220;/ll.*/&#8221;, &#8220;The History of Halloween&#8221;, $matches)) {<br />
echo &#8220;Match was found &lt;br /&gt;&#8221;;<br />
echo $matches[0];<br />
}<br />
?&gt;</div>
<p>Now let&#8217;s consider more complicated example. The most popular use of regular expressions is validation. The example below checks if the password is &#8220;strong&#8221;, i.e. the password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit:</p>
<div>&lt;?php<br />
$password = &#8220;Fyfjk34sdfjfsjq7&#8243;;</p>
<p>if (preg_match(&#8220;/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/&#8221;, $password)) {<br />
echo &#8220;Your passwords is strong.&#8221;;<br />
} else {<br />
echo &#8220;Your password is weak.&#8221;;<br />
}<br />
?&gt;</p></div>
<p>The ^ and $ are looking for something at the start and the end of the string. The &#8220;.*&#8221; combination is used at both the start and the end. As mentioned above, the .(dot) metacharacter means any alphanumeric character, and * metacharacter means &#8220;zero or more&#8221;. Between are groupings in parentheses. The &#8220;?=&#8221; combination means &#8220;the next text must be like this&#8221;. This construct doesn&#8217;t capture the text. In this example, instead of specifying the order that things should appear, it&#8217;s saying that it must appear but we&#8217;re not worried about the order.</p>
<p>The first grouping  is (?=.*{8,}). This checks if there are at least 8 characters in the string. The next grouping (?=.*[0-9]) means &#8220;any alphanumeric character can happen zero or more times, then any digit can happen&#8221;. So this checks if there is at least one number in the string. But since the string isn&#8217;t captured, that one digit can appear anywhere in the string. The next groupings (?=.*[a-z]) and (?=.*[A-Z]) are looking for the lower case and upper case letter accordingly anywhere in the string.</p>
<p>Finally, we will consider regular expression that validates an email address:</p>
<div>&lt;?php<br />
$email = firstname.lastname@aaa.bbb.com;<br />
$regexp = &#8220;/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/&#8221;;</p>
<p>if (preg_match($regexp, $email)) {<br />
echo &#8220;Email address is valid.&#8221;;<br />
} else {<br />
echo &#8220;Email address is &lt;u&gt;not&lt;/u&gt; valid.&#8221;;<br />
}<br />
?&gt;</p></div>
<p>This regular expression checks for the number at the beginning and also checks for multiple periods in the user name and domain name in the email address. Let&#8217;s try to investigate this regular expression yourself.</p>
<p>For the speed reasons, the <em>preg_match()</em> function matches only the first pattern it finds in a string. This means it is very quick to check whether a pattern exists in a string. An alternative function, <em>preg_match_all()</em>, matches a pattern against a string as many times as the pattern allows, and returns the number of times it matched.</p>
<p><img src="http://www.webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="replace"></a>Replacing Patterns</p>
<p>In the above examples, we have searched for patterns in a string, leaving the search string untouched. The <em>preg_replace()</em> function looks for substrings that match a pattern and then replaces them with new text. <em>preg_replace()</em> takes three basic parameters and an additional one. These parameters are, in order, a regular expression, the text with which to replace a found pattern, the string to modify, and the last optional argument which specifies how many matches will be replaced.</p>
<div>preg_replace( pattern, replacement, subject [, limit ])</div>
<p>The function returns the changed string if a match was found or an unchanged copy of the original string otherwise. In the following example we search for the copyright phrase and replace the year with the current.</p>
<div>&lt;?php<br />
echo preg_replace(&#8220;/([Cc]opyright) 200(3|4|5|6)/&#8221;, &#8220;$1 2007&#8243;, &#8220;Copyright 2005&#8243;);<br />
?&gt;</div>
<p>In the above example we use back references in the replacement string. Back references make it possible for you to use part of a matched pattern in the replacement string. To use this feature, you should use parentheses to wrap any elements of your regular expression that you might want to use. You can refer to the text matched by subpattern with a dollar sign ($) and the number of the subpattern. For instance, if you are using subpatterns, $0 is set to the whole match, then $1, $2, and so on are set to the individual matches for each subpattern.</p>
<p>In the following example we will change the date format from &#8220;yyyy-mm-dd&#8221; to &#8220;mm/dd/yyy&#8221;:</p>
<div>&lt;?php<br />
echo preg_replace(&#8220;/(\d+)-(\d+)-(\d+)/&#8221;, &#8220;$2/$3/$1&#8243;, &#8220;2007-01-25&#8243;);<br />
?&gt;</div>
<p>We also can pass an array of strings as <em>subject</em> to make the substitution on all of them. To perform multiple substitutions on the same string or array of strings with one call to <em>preg_replace()</em>, we should pass arrays of patterns and replacements. Have a look at the example:</p>
<div>&lt;?php<br />
$search = array ( &#8220;/(\w{6}\s\(w{2})\s(\w+)/e&#8221;,<br />
&#8220;/(\d{4})-(\d{2})-(\d{2})\s(\d{2}:\d{2}:\d{2})/&#8221;);</p>
<p>$replace = array (&#8216;&#8221;$1 &#8220;.strtoupper(&#8220;$2&#8243;)&#8217;,<br />
&#8220;$3/$2/$1 $4&#8243;);</p>
<p>$string = &#8220;Posted by John | 2007-02-15 02:43:41&#8243;;</p>
<p>echo preg_replace($search, $replace, $string);?&gt;</p></div>
<p>In the above example we use the other interesting functionality - you can say to PHP that the match text should be executed as PHP code once the replacement has taken place. Since we have appended an &#8220;e&#8221; to the end of the regular expression, PHP will execute the replacement it makes. That is, it will take strtoupper(name) and replace it with the result of the <em>strtoupper()</em> function, which is NAME.</p>
<p><img src="http://www.webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="array"></a>Array Processing</p>
<p>PHP&#8217;s <em>preg_split()</em> function enables you to break a string apart basing on something more complicated than a literal sequence of characters. When it&#8217;s necessary to split a string with a dynamic expression rather than a fixed one, this function comes to the rescue. The basic idea is the same as <em>preg_match_all()</em> except that, instead of returning matched pieces of the subject string, it returns an array of pieces that didn&#8217;t match the specified pattern. The following example uses a regular expression to split the string by any number of commas or space characters:</p>
<div>&lt;?php<br />
$keywords = preg_split(&#8220;/[\s,]+/&#8221;, &#8220;php, regular expressions&#8221;);<br />
print_r( $keywords );<br />
?&gt;</div>
<p>Another useful PHP function is the <em>preg_grep()</em> function which returns those elements of an array that match a given pattern. This function traverses the input array, testing all elements against the supplied pattern. If a match is found, the matching element is returned as part of the array containing all matches. The following example searches through an array and all the names starting with letters A-J:</p>
<div>&lt;?php<br />
$names = array(&#8216;Andrew&#8217;,'John&#8217;,'Peter&#8217;,'Nastin&#8217;,'Bill&#8217;);<br />
$output = preg_grep(&#8216;/^[a-m]/i&#8217;, $names);<br />
print_r( $output );<br />
?&gt;</div>
<div id="seo_alrp_related"><h2>Posts Related to Using Regular Expressions with PHP and with advance php</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-regular-expression-regex-functions-list/" rel="bookmark">PHP Regular Expression (Regex) Functions List</a></h3><p>Perl-Compatible Functions List preg_grep — Return array entries that match the pattern preg_match_all — Perform a global regular expression match preg_match — Perform a regular ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/mysql-regexps/" rel="bookmark">MySQL Regexps</a></h3><p>You have seen MySQL pattern matching with LIKE ...%. MySQL supports another type of pattern matching operation based on regular expressions and the REGEXP operator. ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/understanding-and-validating-integers-in-php/" rel="bookmark">Understanding and Validating Integers in PHP</a></h3><p>I’ve found many of my friends struggling with the validation of integers i.e. the numbers with only digits in PHP. Some of them were wondering ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-do-date-format-validation-in-php/" rel="bookmark">How to do Date format validation in PHP</a></h3><p>Today Sushil asked me how can we validate the date which is entered from textbox in “YYYY-MM-DD” format. Well, we can validate the format of ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/ip-address-validation-in-php-using-regular-expression/" rel="bookmark">Ip address validation in PHP using regular expression</a></h3><p>If you don’t know how to validate the IP address format in PHP, then you are in the right place.I’ll show you here how to ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/using-regular-expressions-with-php-and-with-advance-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating Word, Excel and CSV files with PHP</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/creating-word-excel-and-csv-files-with-php/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/creating-word-excel-and-csv-files-with-php/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:09:42 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[CREATE WORD]]></category>
		<category><![CDATA[Creating Word]]></category>
		<category><![CDATA[Excel and CSV files with PHP]]></category>
		<category><![CDATA[EXCEL CSV FILE]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1416</guid>
		<description><![CDATA[Browsing the World Wide Web you can find out various methods of creating files with PHP. In this article we demonstrate several ways to create Microsoft Word and Excel documents, and also CSV files using PHP. MS Word document Using HTTP headers Using COM objects Using OpenOffice templates Using Zend Framework component phpLiveDocx MS Excel [...]]]></description>
			<content:encoded><![CDATA[<p>Browsing the World Wide Web you can find out various methods of creating files with PHP. In this article we demonstrate several ways to create Microsoft Word and Excel documents, and also CSV files using PHP.</p>
<ul type="square">
<li>MS Word document
<ul type="disc">
<li>Using HTTP headers</li>
<li>Using COM objects</li>
<li>Using OpenOffice templates</li>
<li>Using Zend Framework component phpLiveDocx</li>
</ul>
</li>
<li>MS Excel document
<ul type="disc">
<li>Using HTTP headers</li>
<li>Using COM objects</li>
</ul>
</li>
<li>CSV file
<ul type="disc">
<li>Using HTTP headers</li>
<li>Using <em>fputcsv()</em></li>
</ul>
</li>
</ul>
<p><a name="wordheader"></a>How to create MS Word document</p>
<p><strong>Method 1 &#8211; Using HTTP headers</strong></p>
<p>In this method you need to format the HTML/PHP page using Word-friendly CSS and add header information to your PHP script. Make sure you don&#8217;t use external style sheets since everything should be in the same file.</p>
<p>As a result user will be prompted to download a file. This file will not be 100% &#8220;original&#8221; Word document, but it certainly will open in MS Word application. You can use this method both for Unix and Windows environments.</p>
<div>&lt;?php<br />
header(&#8220;Content-type: application/vnd.ms-word&#8221;);<br />
header(&#8220;Content-Disposition: attachment;Filename=document_name.doc&#8221;);</p>
<p>echo &#8220;&lt;html&gt;&#8221;;<br />
echo &#8220;&lt;meta http-equiv=\&#8221;Content-Type\&#8221; content=\&#8221;text/html; charset=Windows-1252\&#8221;&gt;&#8221;;<br />
echo &#8220;&lt;body&gt;&#8221;;<br />
echo &#8220;&lt;b&gt;My first document&lt;/b&gt;&#8221;;<br />
echo &#8220;&lt;/body&gt;&#8221;;<br />
echo &#8220;&lt;/html&gt;&#8221;;<br />
?&gt;</p></div>
<p>As you may note, the formatting capabilities are limited here.</p>
<p><img src="http://webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="wordcom"></a><strong>Method 2 &#8211; Using COM objects</strong></p>
<p>Note that the server running the code stated below must have MS Word installed. COM will work on Windows only.</p>
<p>Word document is saved to the temporary directory and then sent to the browser via <em>readfile()</em> function.</p>
<div>&#8230;<br />
// Create new COM object – word.application<br />
$word = new COM(&#8220;word.application&#8221;);</p>
<p>// Hide MS Word application window<br />
$word-&gt;Visible = 0;</p>
<p>//Create new document<br />
$word-&gt;Documents-&gt;Add();</p>
<p>// Define page margins<br />
$word-&gt;Selection-&gt;PageSetup-&gt;LeftMargin = &#8217;2&#8242;;<br />
$word-&gt;Selection-&gt;PageSetup-&gt;RightMargin = &#8217;2&#8242;;</p>
<p>// Define font settings<br />
$word-&gt;Selection-&gt;Font-&gt;Name = &#8216;Arial&#8217;;<br />
$word-&gt;Selection-&gt;Font-&gt;Size = 10;</p>
<p>// Add text<br />
$word-&gt;Selection-&gt;TypeText(&#8220;TEXT!&#8221;);</p>
<p>// Save document<br />
$filename = tempnam(sys_get_temp_dir(), &#8220;word&#8221;);<br />
$word-&gt;Documents[1]-&gt;SaveAs($filename);</p>
<p>// Close and quit<br />
$word-&gt;quit();<br />
unset($word);</p>
<p>header(&#8220;Content-type: application/vnd.ms-word&#8221;);<br />
header(&#8220;Content-Disposition: attachment;Filename=document_name.doc&#8221;);</p>
<p>// Send file to browser<br />
readfile($filename);<br />
unlink($filename);<br />
&#8230;</p></div>
<p><img src="http://webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="wordooo"></a><strong>Method 3 &#8211; Using OpenOffice templates</strong></p>
<ol>
<li>Create manually an ODT template with placeholders, like [%value-to-replace%].</li>
<li>When instantiating the template with real data in PHP, unzip the template ODT (it&#8217;s a zipped XML), and run against the XML the textual replace of the placeholders with the actual values.</li>
<li>Zip the ODT back.</li>
<li>Run the conversion ODT -&gt; DOC via OpenOffice command line interface.</li>
</ol>
<p>There are tools and libraries available to ease each of those steps.</p>
<p><a name="wordzend"></a><strong>Method 4 &#8211; Using Zend Framework component phpLiveDocx</strong></p>
<p>One of the ways to create DOC files in Linux using PHP is to use the Zend Framework component phpLiveDocx. It allows developers to generate documents by combining structured data from PHP with a template, created in a word processor. The resulting document can be saved as a PDF, DOCX, DOC or RTF file. The concept is the same as with mail-merge.</p>
<p>PhpLiveDocx is completely free to download and use. For more information, please take a look at http://www.phplivedocx.org/articles/brief-introduction-to-phplivedocx/.</p>
<p><img src="http://webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="excelheader"></a>How to create MS Excel document</p>
<p><strong>Method 1 &#8211; Using HTTP headers</strong></p>
<p>As described for the MS Word, you need to format the HTML/PHP page using Excel-friendly CSS and add header information to your PHP script.</p>
<div>&lt;?php<br />
header(&#8220;Content-type: application/vnd.ms-excel&#8221;);<br />
header(&#8220;Content-Disposition: attachment;Filename=document_name.xls&#8221;);</p>
<p>echo &#8220;&lt;html&gt;&#8221;;<br />
echo &#8220;&lt;meta http-equiv=\&#8221;Content-Type\&#8221; content=\&#8221;text/html; charset=Windows-1252\&#8221;&gt;&#8221;;<br />
echo &#8220;&lt;body&gt;&#8221;;<br />
echo &#8220;&lt;b&gt;testdata1&lt;/b&gt; \t &lt;u&gt;testdata2&lt;/u&gt; \t \n &#8220;;<br />
echo &#8220;&lt;/body&gt;&#8221;;<br />
echo &#8220;&lt;/html&gt;&#8221;;<br />
?&gt;</p></div>
<p><img src="http://webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="excelcom"></a><strong>Method 2 &#8211; Using COM objects</strong></p>
<p>Note that the server running the code stated below must have MS Excel installed.</p>
<p>We use the same approach as for MS Word with saving a file to the temporary directory first.</p>
<div>&#8230;<br />
//Create new COM object – excel.application<br />
$xl = new COM(&#8220;excel.application&#8221;);</p>
<p>//Hide MS Excel application window<br />
$xl-&gt;Visible = 0;</p>
<p>//Create new document<br />
$xlBook = $xl-&gt;Workbooks-&gt;Add();</p>
<p>//Create Sheet 1<br />
$xlBook-&gt;Worksheets(1)-&gt;Name = &#8220;Worksheet 1&#8243;;<br />
$xlBook-&gt;Worksheets(1)-&gt;Select;</p>
<p>//Set Width &amp; Height<br />
$xl-&gt;ActiveSheet-&gt;Range(&#8220;A1:A1&#8243;)-&gt;ColumnWidth = 10.0;<br />
$xl-&gt;ActiveSheet-&gt;Range(&#8220;B1:B1&#8243;)-&gt;ColumnWidth = 13.0;</p>
<p>//Add text<br />
$xl-&gt;ActiveSheet-&gt;Cells(1,1)-&gt;Value = &#8220;TEXT&#8221;;<br />
$xl-&gt;ActiveSheet-&gt;Cells(1,1)-&gt;Font-&gt;Bold = True;</p>
<p>//Save document<br />
$filename = tempnam(sys_get_temp_dir(), &#8220;excel&#8221;);<br />
$xlBook-&gt;SaveAs($filename);</p>
<p>//Close and quit<br />
unset( $xlBook);<br />
$xl-&gt;ActiveWorkBook-&gt;Close();<br />
$xl-&gt;Quit();<br />
unset( $xl );</p>
<p>header(&#8220;Content-type: application/vnd.ms-excel&#8221;);<br />
header(&#8220;Content-Disposition: attachment;Filename=document_name.xls&#8221;);</p>
<p>// Send file to browser<br />
readfile($filename);<br />
unlink($filename);<br />
&#8230;</p></div>
<p><img src="http://webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="csvheader"></a>How to create a CSV file</p>
<p><strong>Method 1 &#8211; Using HTTP headers</strong></p>
<p>As in the examples for the Word and Excel, you need to add header information to your PHP script.</p>
<p>The code snippet below creates a CSV file of the specified table including its column names. Then user will be prompted to download this file.</p>
<div>&lt;?php<br />
$table = &#8216;table_name&#8217;;<br />
$outstr = NULL;</p>
<p>header(&#8220;Content-Type: application/csv&#8221;);<br />
header(&#8220;Content-Disposition: attachment;Filename=cars-models.csv&#8221;);</p>
<p>$conn = mysql_connect(&#8220;localhost&#8221;, &#8220;mysql_user&#8221;, &#8220;mysql_password&#8221;);<br />
mysql_select_db(&#8220;db&#8221;,$conn);</p>
<p>// Query database to get column names<br />
$result = mysql_query(&#8220;show columns from $table&#8221;,$conn);<br />
// Write column names<br />
while($row = mysql_fetch_array($result)){<br />
$outstr.= $row['Field'].&#8217;,';<br />
}<br />
$outstr = substr($outstr, 0, -1).&#8221;\n&#8221;;</p>
<p>// Query database to get data<br />
$result = mysql_query(&#8220;select * from $table&#8221;,$conn);<br />
// Write data rows<br />
while ($row = mysql_fetch_assoc($result)) {<br />
$outstr.= join(&#8216;,&#8217;, $row).&#8221;\n&#8221;;<br />
}</p>
<p>echo $outstr;<br />
mysql_close($conn);<br />
?&gt;</p></div>
<p><img src="http://webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="fputcsv"></a><strong>Method 2 &#8211; Using <em>fputcsv()</em></strong></p>
<p>The <em>fputcsv()</em> function formats a line as CSV and writes it to an open file. For more information, take a look at http://php.net/manual/en/function.fputcsv.php.</p>
<p>The code snippet below creates a CSV file of the specified table including its column names and sends it to the browser.</p>
<div>&lt;?php<br />
$table = &#8216;table_name&#8217;;<br />
$filename = tempnam(sys_get_temp_dir(), &#8220;csv&#8221;);</p>
<p>$conn = mysql_connect(&#8220;localhost&#8221;, &#8220;mysql_user&#8221;, &#8220;mysql_password&#8221;);<br />
mysql_select_db(&#8220;db&#8221;,$conn);</p>
<p>$file = fopen($filename,&#8221;w&#8221;);</p>
<p>// Write column names<br />
$result = mysql_query(&#8220;show columns from $table&#8221;,$conn);<br />
for ($i = 0; $i &lt; mysql_num_rows($result); $i++) {<br />
$colArray[$i] = mysql_fetch_assoc($result);<br />
$fieldArray[$i] = $colArray[$i]['Field'];<br />
}<br />
fputcsv($file,$fieldArray);</p>
<p>// Write data rows<br />
$result = mysql_query(&#8220;select * from $table&#8221;,$conn);<br />
for ($i = 0; $i &lt; mysql_num_rows($result); $i++) {<br />
$dataArray[$i] = mysql_fetch_assoc($result);<br />
}<br />
foreach ($dataArray as $line) {<br />
fputcsv($file,$line);<br />
}</p>
<p>fclose($file);</p>
<p>header(&#8220;Content-Type: application/csv&#8221;);<br />
header(&#8220;Content-Disposition: attachment;Filename=cars-models.csv&#8221;);</p>
<p>// send file to browser<br />
readfile($filename);<br />
unlink($filename);<br />
?&gt;</p></div>
<div id="seo_alrp_related"><h2>Posts Related to Creating Word, Excel and CSV files with PHP</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/create-a-csv-file-from-mysql-with-php/" rel="bookmark">Create a CSV file from MySQL with PHP</a></h3><p>There are a couple of ways to export data from MySQL to a CSV file but neither of them supports adding a header row to ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/07/how-to-read-excel-file-in-php/" rel="bookmark">how to read excel file in php</a></h3><p>2 Techniques Access the raw Excel Binary File Use the Excel API Both techniques have their advantages and disadvantages as you will see during this ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/reading-the-clean-text-from-docx-and-odt/" rel="bookmark">Reading the &#8220;clean&#8221; text from DOCX and ODT</a></h3><p>In this article we will resolve the task of reading the “clean” text from the Office Open XML (more known as DOCX) and OpenDocument Format ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-make-dsn-and-dsn-less-connections/" rel="bookmark">How to make DSN and DSN-less connections</a></h3><p>DSN stands for 'Data Source Name'. It is an easy way to assign useful and easily rememberable names to data sources which may not be ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/paging-using-php-and-mysql/" rel="bookmark">Paging Using PHP and MySQL</a></h3><p>When there's more than one column involved in paging there isn't much that we need to modify. We only need to decide how to count ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/creating-word-excel-and-csv-files-with-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

