<?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/"
	xmlns:media="http://search.yahoo.com/mrss/"
>

<channel>
	<title>Various Technical Articles to learn PHP with easy Examples</title>
	<atom:link href="https://jharaphula.com/category/programming-solutions/php-demo-apps/feed/" rel="self" type="application/rss+xml" />
	<link>https://jharaphula.com/category/programming-solutions/php-demo-apps/</link>
	<description>Blog for SEO Guest Posting, Digital Marketing or Home Remedies</description>
	<lastBuildDate>Tue, 14 Apr 2026 06:09:31 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>
	<item>
		<title>Frequently used PHP String Functions with Example &#038; Explanation</title>
		<link>https://jharaphula.com/php-string-functions-with-example/</link>
					<comments>https://jharaphula.com/php-string-functions-with-example/#respond</comments>
		
		<dc:creator><![CDATA[Biswabhusan Panda]]></dc:creator>
		<pubDate>Tue, 01 Nov 2016 13:02:54 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[JQuery String Functions]]></category>
		<category><![CDATA[PHP String Functions]]></category>
		<category><![CDATA[Script for PHP]]></category>
		<category><![CDATA[strpos() Function]]></category>
		<category><![CDATA[trim String Functions]]></category>
		<guid isPermaLink="false">http://jharaphula.com/?p=6623</guid>

					<description><![CDATA[<img width="300" height="178" src="https://jharaphula.com/wp-content/uploads/2016/10/php-string-functions-300x178.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="Frequently used PHP String Functions with Example &amp; Explanation" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" fetchpriority="high" srcset="https://jharaphula.com/wp-content/uploads/2016/10/php-string-functions-300x178.jpg 300w, https://jharaphula.com/wp-content/uploads/2016/10/php-string-functions.jpg 750w" sizes="(max-width: 300px) 100vw, 300px" /><p>In PHP there are more than hundred of String functions available freely to make string operations easier. But you must noticed during our day today...</p>
<p>The post <a href="https://jharaphula.com/php-string-functions-with-example/">Frequently used PHP String Functions with Example &amp; Explanation</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="178" src="https://jharaphula.com/wp-content/uploads/2016/10/php-string-functions-300x178.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="Frequently used PHP String Functions with Example &amp; Explanation" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" srcset="https://jharaphula.com/wp-content/uploads/2016/10/php-string-functions-300x178.jpg 300w, https://jharaphula.com/wp-content/uploads/2016/10/php-string-functions.jpg 750w" sizes="(max-width: 300px) 100vw, 300px" /><p>In PHP there are more than hundred of String functions available freely to make string operations easier. But you must noticed during our day today development frequently we use some of the String functions. Normally those string function are String replace, Sub String, String length, String Position or Trim a String. For fresher in PHP let us discuss all those frequently used <a href="https://jharaphula.com/jquery-string-functions/" rel="noopener noreferrer" target="_blank">String function</a> with examples. It&#8217;s not matter if you don&#8217;t know all PHP string functions, when required you can take the help of Google to recall the Syntax. But to be a good programmer it&#8217;s mandatory for you to remember below PHP string functions.</p>
<h3>ltrim(), rtrim() &amp; trim String Functions</h3>
<p>Assume that you have a string with whitespace or predefined characters at the beginning and end. In this case to remove whitespaces or predefined characters trim function is useful. Compare to ltrim and rtrim trim function helps to reduce spaces and predefined characters from the both side (<em>left and right</em>) of a string. While ltrim removes whitespaces &amp; predefined characters from left part of a string rtrim helps to remove whitespaces &amp; predefined characters from the right side of a string. Look at the example below.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$str = &quot;Hari is a good Boy.&quot;;
echo ltrim($str,&quot;Hari&quot;);
?&gt;</pre>
<p>Output: <em>is a good Boy.</em></p>
<h3>str_replace() Function</h3>
<p>In PHP we use str_replace() function to replace specific characters with some other characters. This function is case sensitive. If in a string you want replace a specific word str_replace function replace all the words with similar characters. Syntax for str_replace is as below.</p>
<p>Syntax: <em>str_replace(find, replace, string, count);</em></p>
<p>Keep remember str_replace accepts 4 parameters. The first 3 parameters are mandatory. Where ever the last parameter count is optional. The first parameter find says which string of characters you want to replace. While replace says what are the other characters you want to replace for the find characters. String parameter is the variable which holds the complete string. Count is optional. In place of count if you are passing any variable as a parameter it returns the total number of time the find word replaced. Look at the example below here I have a string &#8220;Hello Biswabhusan!&#8221;. I want to replace &#8220;Biswabhusan&#8221; with &#8220;Peter&#8221;. To know how many times the word &#8220;Biswabhusan&#8221; was replaced I am passing $i as the count parameter and printing that after a hyphen.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo str_replace(&quot;Biswabhusan&quot;,&quot;Peter&quot;,&quot;Hello Biswabhusan!&quot;, $i);
echo &quot;-&quot; . $i;
?&gt;</pre>
<p>Output: <em>Hello Peter!-1</em></p>
<h3>str_split() Function</h3>
<p>Using str_split() Function you can split a string to array. str_split() function accepts 2 parameters string and length. The first parameter sting is the string which you want to split in to arrays. The second parameter length is an optional parameter. By default this is 1. To know how to implement str_split() Function Look at the example below.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
print_r(str_split(&quot;biswabhusan&quot;,3));
?&gt;</pre>
<p>Output: <em>Array ( [0] => bis [1] => wab [2] => hus [3] => an )</em> </p>
<h3>strpos() Function</h3>
<p>During string operation sometime we required to know the position of a particular word or character in a complete string. In such case strpos() is useful. Using strpos() you can easily know the first occurrence position of any word or character in a complete sentence. Keep remember strpos() function is case-sensitive and binary-safe. It accepts 3 parameters string, find &#038; start. The first parameter string is nothing but the sentence where you want to know the position of a specific word or character. The second parameter Find is the word or character you want to search. The third parameter start is optional. It specifies in the complete string from where after you want to search the find word or character. For an example in below I am with a string &#8220;Ravi is a good person.&#8221;. Here I want to know the position of &#8220;good&#8221;.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo strpos(&quot;Ravi is a good person.&quot;,&quot;good&quot;);
?&gt;</pre>
<p>Output: <em>10</em></p>
<p><strong>Related Functions</strong></p>
<p>strrpos() &#8211; This function helps to find position of the last occurrence of a word or character inside a string. This is case-sensitive.</p>
<p>stripos() &#8211; This function helps to find position of the first occurrence of a word or character inside a string. This is case-sensitive.</p>
<p>strripos() &#8211; This function finds the position of the last occurrence of a word or character inside a string. This is case-insensitive.</p>
<h3>strlen() Function</h3>
<p>To know the length of a String we use strlen() function in PHP. This function accepts 1 parameter as string. strlen() always returns integer value. In-case you pass a empty string it return 0. Look at the example below here to strlen I am passing a string &#8220;How are you?&#8221;. In result strlen() returns 12. It&#8217;s means that strlen() function calculates spaces including characters.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo strlen(&quot;How are you?&quot;);
?&gt;</pre>
<p>Output: <em>12</em></p>
<h3>strrev() Function</h3>
<p>You must remember those days while to reverse a string we do implement a for loop over the length of a string. Then using echo we print each characters from last to first. In latest revision of PHP (Version 4 onwards) this issue is resolved with strrev() function. Using this function you don&#8217;t required to write a complex logic for reverse a string. Simply by passing the string as a parameter to strrev() function you can easily achieve a reverse string. Look at the example below.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo strrev(&quot;This is an Example.&quot;);
?&gt;</pre>
<p>Output: <em>.elpmaxE na si sihT</em></p>
<h3>substr() Function</h3>
<p>This is a very useful string function. During we extract a part of string from the complete string this function is helpful. substr() function accepts 3 parameters as string, start and length. The first parameter string is nothing but the complete string from which you want to derive part of string. The second parameter start specifies where to start from the complete string. It accepts both negative and positive values. By passing positive number substr() function with start at a specified position from the beginning of the string. If you are passing negative number then it start at a specified position starting from the end of the string. Third parameter length is optional. If in a string of 25 characters length you are passing 2nd and 3rd parameter as 5 and 12 then substr() will return the sub-string from the 5th position to 17th position of complete string. Look at the example below.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo substr(&quot;This is a awesome School.&quot;, 5, 12);
?&gt;</pre>
<p>Output: <em>is a awesome</em>.</p>
<h3>strtolower() &#038; strtoupper() PHP String Functions</h3>
<p>These 2 string functions are used to change the case of Characters. Both of these functions accepts 1 parameter as the string. Using strtolower() you can convert a string to lowercase letters. Similarly using strtoupper() function you can convert a string to uppercase letters. Look at the example below.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo strtolower(&quot;Hello WORLD.&quot;);
?&gt;</pre>
<p>Output: <em>hello world.</em></p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo strtoupper(&quot;Hello WORLD!&quot;);
?&gt;</pre>
<p>Output: <em>HELLO WORLD!</em></p>
<p>The post <a href="https://jharaphula.com/php-string-functions-with-example/">Frequently used PHP String Functions with Example &amp; Explanation</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/php-string-functions-with-example/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/10/php-string-functions.jpg" medium="image" />
	</item>
		<item>
		<title>Google like Autosuggestion Search Box using PHP, MySQL &#038; Jquery</title>
		<link>https://jharaphula.com/google-like-autosuggestion-search-box-using-php-mysql-jquery/</link>
					<comments>https://jharaphula.com/google-like-autosuggestion-search-box-using-php-mysql-jquery/#respond</comments>
		
		<dc:creator><![CDATA[Biswabhusan Panda]]></dc:creator>
		<pubDate>Thu, 21 Jul 2016 15:15:01 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[AngularJS Search Filter]]></category>
		<category><![CDATA[Autosuggestion Search Box]]></category>
		<category><![CDATA[Script for PHP]]></category>
		<category><![CDATA[Search Box using PHP]]></category>
		<guid isPermaLink="false">http://jharaphula.com/?p=4258</guid>

					<description><![CDATA[<img width="300" height="187" src="https://jharaphula.com/wp-content/uploads/2016/07/autosuggestion-search-box-300x187.png" class="webfeedsFeaturedVisual wp-post-image" alt="Google like autosuggestion Search box using PHP, MySQL &amp; Jquery" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" srcset="https://jharaphula.com/wp-content/uploads/2016/07/autosuggestion-search-box-300x187.png 300w, https://jharaphula.com/wp-content/uploads/2016/07/autosuggestion-search-box.png 750w" sizes="(max-width: 300px) 100vw, 300px" /><p>Web is the house of information. Millions are working Day &#38; Night to make the Web better. In this rush to locate correct information from...</p>
<p>The post <a href="https://jharaphula.com/google-like-autosuggestion-search-box-using-php-mysql-jquery/">Google like Autosuggestion Search Box using PHP, MySQL &amp; Jquery</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="187" src="https://jharaphula.com/wp-content/uploads/2016/07/autosuggestion-search-box-300x187.png" class="webfeedsFeaturedVisual wp-post-image" alt="Google like autosuggestion Search box using PHP, MySQL &amp; Jquery" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/07/autosuggestion-search-box-300x187.png 300w, https://jharaphula.com/wp-content/uploads/2016/07/autosuggestion-search-box.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>Web is the house of information. Millions are working Day &amp; Night to make the Web better. In this rush to locate correct information from Search engines you required to search wisely. You must noticed sometime it was difficult to find out a suitable search string according to the need. In such case autosuggestion facility works awesome. The king of Search engines Google provides this facility. To implement the same in your application with this demo I created an autosuggestion Search box using PHP and jQuery. Data I am fetching from MySQL Database.</p>
<p>To create this demo here I am with 4 files index.htm, main.css, loading.js &amp; live-Search.php. The HTML file contains a Container which hold an input control with id txtSearch. Below the Search box I have a div to display autosuggestion strings. Initial during page load I hided this using CSS display:none.</p>
<h3>index.htm</h3>
<pre class="brush: xml; title: ; notranslate">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;title&gt;Google like autosuggestion Search box using PHP&lt;/title&gt;
&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;loading.js&quot;&gt;&lt;/script&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;main.css&quot; /&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div class=&quot;container&quot;&gt;
&lt;input type=&quot;text&quot; id=&quot;txtSearch&quot; placeholder=&quot;Search our Faculty Database&quot; /&gt;&lt;br /&gt; 
&lt;div id=&quot;SearchResults&quot;&gt;&lt;/div&gt;
&lt;/div&gt; 
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>The below CSS file gives look n feel to my <a href="https://jharaphula.com/list-of-html5-new-tags/" rel="noopener noreferrer" target="_blank">HTML elements</a>. Here depending upon the width of Search box I applied the same to Search result div.</p>
<h3>main.css</h3>
<pre class="brush: css; title: ; notranslate">.container { margin: 0 auto; padding-top: 150px; width: 600px; }
#txtSearch { width:600px; border:solid 1px #000000; padding:10px; font-size:16px; }
#SearchResults { position:absolute; width:600px; padding:10px; display:none; margin-top:-1px; border-top:0px; overflow:hidden; border:1px #CCC solid; background: #FFF; }
.res-pan { border-bottom: 1px dashed #999; font-size: 16px; height: 40px; }
.res-pan:hover { background: #2E237A; cursor:pointer; color:#FFFFFF; }
.live-results { width: 100%; height: 100%; padding-top: 8px; }</pre>
<p>Core logic for autosuggestion Search box is running inside the below JS file. Here using Jquery I am tracking the keyup event of the Search box. Inside this using <a href="https://jharaphula.com/jquery-ajax-example/" rel="noopener noreferrer" target="_blank">Jquery Ajax method</a> I am sending user inputs to live-Search.php. To maintain secure data transmission in Ajax call I used POST method.</p>
<h3>loading.js</h3>
<pre class="brush: jscript; title: ; notranslate">$(document).ready(function(){
/* During page load Clearing the Search Box value */
$(&quot;#txtSearch&quot;).val('');
/* Setting Focus to Search Box */
$(&quot;#txtSearch&quot;).focus();
/* Handling Keyup event for Search Box */
$(&quot;#txtSearch&quot;).keyup(function(){
var queryStr = $(this).val();
var dataString = 'SearchString='+ queryStr;
if(queryStr!='')
{
$.ajax({
type: &quot;POST&quot;,
url: &quot;live-Search.php&quot;,
data: dataString,
cache: false,
success: function(html)
{
$(&quot;#SearchResults&quot;).html(html).show();
$(&quot;.live-results&quot;).on(&quot;click&quot;,function() {	
$(&quot;#txtSearch&quot;).val($(this).html());
$(&quot;#SearchResults&quot;).fadeOut();
});
}
});
}
return false; 
});

$(document).on(&quot;click&quot;, function(e) { 
var clicked = $(e.target);
if (!clicked.hasClass(&quot;live-results&quot;)){
$(&quot;#SearchResults&quot;).fadeOut(); 
}
});
});</pre>
<p>In success event of Jquery Ajax method I am binding the response data to SearchResults div. Here my response data is pure HTML. Which is programmed in below PHP file. This HTML contains a div with class name live-results. After displaying autosuggestion pan to handle user selection I am assigning the selected value to Search box inside the live-results click event. Once the selected value mapped to Search box I am hiding the Search results pan.</p>
<h3>live-Search.php</h3>
<pre class="brush: php; title: ; notranslate">&lt;?php
$connection = mysql_connect(&quot;localhost&quot;, &quot;root&quot;);
mysql_select_db(&quot;demo_db&quot;, $connection);
if($_POST)
{
$q = $_POST['SearchString'];
$sqlRes = mysql_query(&quot;select faculty_id,faculty_name from faculty where faculty_name like '%$q%' order by faculty_id LIMIT 5&quot;);

while($row=mysql_fetch_array($sqlRes))
{
$username   = $row['faculty_name'];
?&gt;
&lt;div class=&quot;res-pan&quot;&gt;
&lt;div class=&quot;live-results&quot;&gt;&lt;?php echo $username; ?&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;?php
}
}
?&gt;</pre>
<p>The above PHP file is fetching user inputs from Jquery Ajax method using $_POST[&#8216;SearchString&#8217;]. Then using a MySQL Select query I am using wild-char Search with limit of 5 records. Then displaying those data inside a while loop using div. To apply CSS on these div&#8217;s I assigned Classes to them.</p>
<p>For demo purpose in MySQL create a db with name &#8220;demo_db&#8221;. Then using the following query Create a table for Faculty. </p>
<pre class="brush: sql; title: ; notranslate">CREATE TABLE Faculty (
Faculty_ID INT NOT NULL AUTO_INCREMENT,
Faculty_Name VARCHAR(70) NOT NULL,
Email_ID VARCHAR(60) NOT NULL,
Mobile_Number VARCHAR(10) NOT NULL,
PRIMARY KEY (Faculty_ID)
);</pre>
<p>Once the table Created successfully insert data using the following SQL statements.</p>
<pre class="brush: sql; title: ; notranslate">INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Abhishek Bachchan','abhishek@gmail.com','9823234566');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Bijayalaxmi Sahoo','bijayalaxmi@gmail.com','8773325680');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Manmohan Desai','manmohan.desai@gmail.com','7734698800');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Naveen Patnaik','naveen.p@gmail.com','8775600027');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Poonam Jhawar','poonam.jhawar@gmail.com','9096266548');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Poonam Pandey','poonam.p@gmail.com','8772282800');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Ravi Shankar','ravi.shankar@gmail.com','9258733647');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Nibedita Panda','nibedita.panda@gmail.com','9227855677');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Gitanjali Swamy','gitanjali@gmail.com','8227699000');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Ravi Srivastab','ravi.srivastab@gmail.com','7433309768');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Rani Mukherjee','rani.mukherjee@gmail.com','8227899003');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Meghana Kaushik','meghana.k@gmail.com','8923764466');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Rituraj Mohanty','rituraj.mohanty@gmail.com','9096874588');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Meghana Raj','meghana.raj@gmail.com','9896355454');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Sanchita Shetty','sanchita.shetty@gmail.com','7878654321');
INSERT INTO faculty(Faculty_Name, Email_ID, Mobile_Number) VALUES ('Ramya Krishnan','ramya.krishnan@gmail.com','9888766543');</pre>
<p>Hope the above explanation will make you clear about the logic behind this demo app. Enrich your application Search facility with autosuggestion. This will make your application much user friendly.</p>
<p>The post <a href="https://jharaphula.com/google-like-autosuggestion-search-box-using-php-mysql-jquery/">Google like Autosuggestion Search Box using PHP, MySQL &amp; Jquery</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/google-like-autosuggestion-search-box-using-php-mysql-jquery/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/07/autosuggestion-search-box.png" medium="image" />
	</item>
		<item>
		<title>How to Export data from MySQL to Excel using PHP?</title>
		<link>https://jharaphula.com/export-data-from-mysql-to-excel-php/</link>
					<comments>https://jharaphula.com/export-data-from-mysql-to-excel-php/#respond</comments>
		
		<dc:creator><![CDATA[Biswabhusan Panda]]></dc:creator>
		<pubDate>Sun, 17 Jul 2016 06:19:36 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[Database Terminologies]]></category>
		<category><![CDATA[Display Excel File records]]></category>
		<category><![CDATA[Export data from MySQL]]></category>
		<category><![CDATA[How to Bind Data?]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[MySQL to Excel using PHP]]></category>
		<guid isPermaLink="false">http://jharaphula.com/?p=4232</guid>

					<description><![CDATA[<img width="300" height="193" src="https://jharaphula.com/wp-content/uploads/2016/07/Export-to-Excel-using-PHP-300x193.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="How to Export data from MySQL to Excel using PHP?" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/07/Export-to-Excel-using-PHP-300x193.jpg 300w, https://jharaphula.com/wp-content/uploads/2016/07/Export-to-Excel-using-PHP-294x190.jpg 294w, https://jharaphula.com/wp-content/uploads/2016/07/Export-to-Excel-using-PHP.jpg 798w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>Decade back MS-Excel is one of most popular data inter-exchange platform. Looking into it&#8217;s popularity Excel file is supported by Window, Linux, Mac OS X,...</p>
<p>The post <a href="https://jharaphula.com/export-data-from-mysql-to-excel-php/">How to Export data from MySQL to Excel using PHP?</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="193" src="https://jharaphula.com/wp-content/uploads/2016/07/Export-to-Excel-using-PHP-300x193.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="How to Export data from MySQL to Excel using PHP?" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/07/Export-to-Excel-using-PHP-300x193.jpg 300w, https://jharaphula.com/wp-content/uploads/2016/07/Export-to-Excel-using-PHP-294x190.jpg 294w, https://jharaphula.com/wp-content/uploads/2016/07/Export-to-Excel-using-PHP.jpg 798w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>Decade back MS-Excel is one of most popular data inter-exchange platform. Looking into it&#8217;s popularity Excel file is supported by Window, Linux, Mac OS X, Android &amp; iOS. Compare to Other spreadsheets Excel is rich with many advanced functionalities such as Calculation, Formula Feeding, Pivot Tables, Graphics tools, Data visuals or Macro programming. This is the reason Customer wants Export to Excel facility in their application.</p>
<p>Generally during we display tabular data in a web page for sharing purpose we do implement export to excel button. For every user it&#8217;s many not possible to give access to the System. The cause using an excel sheet we can easily share data to the respective authority. In the below demo I am fetching data from a MySQL Database table and exporting those data to an excel file using <a href="https://jharaphula.com/category/programming-solutions/php-demo-apps/" rel="noopener noreferrer" target="_blank">PHP programming</a>.</p>
<p>To export data from MySQL to excel, here under MySQL Database &#8220;temp_db&#8221; I created a Table &#8220;ManagerDetails&#8221;. Which holds managers details.</p>
<h3>Create Table</h3>
<pre class="brush: sql; title: ; notranslate">CREATE TABLE IF NOT EXISTS ManagerDetails (
Manager_ID varchar(10) NOT NULL DEFAULT '', 
Manager_Name varchar(200) NOT NULL DEFAULT '', 
Manager_Designation varchar(200) NOT NULL DEFAULT '', 
Manager_Salary varchar(20) NOT NULL DEFAULT '0', 
PRIMARY KEY (Manager_ID) 
)</pre>
<h3>Insert Records for Demo purpose</h3>
<pre class="brush: sql; title: ; notranslate">INSERT INTO ManagerDetails (Manager_ID, Manager_Name, Manager_Designation, Manager_Salary) VALUES
(1, 'Sujata Mohapatra', 'Sr. Manager', '28000'),
(2, 'Ravi Ranjan Dash', 'Program Manager', '32000'),
(3, 'Bijaylakshmi Dash', 'Business Manager', '48000'),
(4, 'Rosalin Roy', 'Sr. Program Manager', '62000'),
(5, 'Nibedita Mahapatra', 'Jr. Manager', '18000'),
(6, 'Meghana Roy', 'Sr. Manager', '35000'),
(7, 'Manamohan Mohanty', 'Sr. Team Lead', '23000'),
(8, 'Rupak Maharana', 'Business Head', '36000'),
(9, 'Ramkrishna Dalei', 'QA Manager', '18000'),
(10, 'Puspashree Mishra', 'Team Leader', '15000'),
(11, 'Jayshree Moharana', 'Sr. Project Manager', '55000'),
(12, 'Ravi Prakash Dash', 'Business Head', '42000');</pre>
<p>Then to Fetch Data from &#8220;ManagerDetails.php&#8221; first I am establishing Database Connection. Once after the Successful Connection executing a <a href="https://jharaphula.com/sql-queries-with-example/" rel="noopener noreferrer" target="_blank">SQL query</a> to fetch data. To customize output Excel File Name here I declared a variable $FileName. Currently here I decided the File Name as &#8220;ManagerDetails.xls&#8221;. You can update this as per your requirements.</p>
<p>To generate an Excel File after File Name I am declaring Excel File Header information. Then inside a while loop I am storing &#8220;mysql_fetch_assoc($manager_query)&#8221; to $row variable. Which holds database records. To print those values to an Excel File I am using echo command. To create several columns in Excel during echo command I am using &#8220;/t&#8221; (Tab) after each column of $row. Similarly for new line at the end of echo command using &#8220;/n&#8221;.</p>
<h3>ManagerDetails.php</h3>
<pre class="brush: php; title: ; notranslate">&lt;?php
/* Establishing MySQL Database Connection */
$sql_query=mysql_connect(&quot;localhost&quot;, &quot;root&quot;);
mysql_select_db(&quot;temp_db&quot;, $sql_query);

/* Executing query to Fetch Data from MySQL Table */
$manager_query=mysql_query(&quot;SELECT * FROM ManagerDetails&quot;);

/* Function to Filter each data row */
function FilterSpecialChars(&amp;$str)
{
$str = preg_replace(&quot;/\t/&quot;, &quot;\\t&quot;, $str);
$str = preg_replace(&quot;/\r?\n/&quot;, &quot;\\n&quot;, $str);
if(strstr($str, '&quot;')) $str = '&quot;' . str_replace('&quot;', '&quot;&quot;', $str) . '&quot;';
}

/* Place to Define File Name for your Excel File */
$FileName = &quot;ManagerDetails&quot; . &quot;.xls&quot;;

/*Setting File Header information for Excel*/
header(&quot;Content-Disposition: attachment; filename=\&quot;$FileName\&quot;&quot;);
header(&quot;Content-Type: application/vnd.ms-excel&quot;);

/* Running loop to display each row of Data */
while($row = mysql_fetch_assoc($manager_query)){
// filter data
array_walk($row, 'FilterSpecialChars');
echo $row['Manager_Name'] . &quot;\t&quot; . $row['Manager_Designation'] . &quot;\t&quot; . $row['Manager_Salary'] . &quot;\n&quot;;
}

exit;
?&gt;</pre>
<p>The post <a href="https://jharaphula.com/export-data-from-mysql-to-excel-php/">How to Export data from MySQL to Excel using PHP?</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/export-data-from-mysql-to-excel-php/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/07/Export-to-Excel-using-PHP.jpg" medium="image" />
	</item>
		<item>
		<title>Simple PHP pagination Example using MySQL records</title>
		<link>https://jharaphula.com/simple-php-pagination-example-mysql/</link>
					<comments>https://jharaphula.com/simple-php-pagination-example-mysql/#respond</comments>
		
		<dc:creator><![CDATA[Nibedita Panda]]></dc:creator>
		<pubDate>Sun, 15 May 2016 18:01:57 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Pagination using AngularJS]]></category>
		<category><![CDATA[PHP pagination Example]]></category>
		<category><![CDATA[PHP String Functions]]></category>
		<category><![CDATA[Sorting and Pagination]]></category>
		<guid isPermaLink="false">http://box.jharaphula.com/?p=1687</guid>

					<description><![CDATA[<img width="300" height="170" src="https://jharaphula.com/wp-content/uploads/2016/05/datatable-pagination-300x170.png" class="webfeedsFeaturedVisual wp-post-image" alt="Simple PHP pagination Example using MySQL records" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/datatable-pagination-300x170.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/datatable-pagination.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>During Web Application designing to display bulk of records in distributed manner we use pagination. Assume in your Customers table you have more than 600...</p>
<p>The post <a href="https://jharaphula.com/simple-php-pagination-example-mysql/">Simple PHP pagination Example using MySQL records</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="170" src="https://jharaphula.com/wp-content/uploads/2016/05/datatable-pagination-300x170.png" class="webfeedsFeaturedVisual wp-post-image" alt="Simple PHP pagination Example using MySQL records" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/datatable-pagination-300x170.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/datatable-pagination.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>During Web Application designing to display bulk of records in distributed manner we use pagination. Assume in your Customers table you have more than 600 records. While displaying those records in a tabular view it is much better to use pagination. The key advantage of using pagination is we can do partial loading from the database. Which saves user time.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-1728" title="Simple PHP pagination Example" src="https://jharaphula.com/wp-content/uploads/2016/05/pagination.jpg" alt="Simple PHP pagination Example" width="750" height="191" srcset="https://jharaphula.com/wp-content/uploads/2016/05/pagination.jpg 750w, https://jharaphula.com/wp-content/uploads/2016/05/pagination-300x76.jpg 300w" sizes="auto, (max-width: 750px) 100vw, 750px" /></p>
<p>In this example I am with a <a href="https://jharaphula.com/category/programming-solutions/php-demo-apps/" target="_blank" rel="noopener noreferrer">PHP</a> pagination script which fetch data from MySQL. To start with Create a table using the following &#8220;CREATE TABLE&#8230;&#8221; query. Keep your database name &#8220;empdb&#8221;.</p>
<pre class="brush: sql; title: ; notranslate">CREATE TABLE IF NOT EXISTS EmpDetails (
Emp_ID varchar(10) NOT NULL DEFAULT '', 
Emp_Name varchar(200) NOT NULL DEFAULT '', 
Emp_Designation varchar(200) NOT NULL DEFAULT '', 
Emp_Salary varchar(20) NOT NULL DEFAULT '0', 
PRIMARY KEY (Emp_ID) 
)

Once you successfully created the &quot;EmpDetails&quot; table. Insert some sample records using the following INSERT STATEMENT.

INSERT INTO EmpDetails (Emp_ID, Emp_Name, Emp_Designation, Emp_Salary) VALUES
(1, 'Mounika Readdy', 'UI Developer', '23000'),
(2, 'Vishval Chohhan', 'Graphics Engineer', '12000'),
(3, 'Biswabhusan Panda', 'Sr. Software Engineer', '45000'),
(4, 'Satyabrat Panda', 'Program Manager', '60000'),
(5, 'Nilima Kapoor', 'JS Developer', '30000'),
(6, 'Megha Roy', 'Software Engineer', '12000'),
(7, 'Manamohan Maharana', 'Team Lead', '25000'),
(8, 'Rupak Srivastab', 'UI Developer', '32000'),
(9, 'Ramkumar Ojha', 'QA Engineer', '10000'),
(10, 'Mittali Roy', 'Graphics Engineer', '15000'),
(11, 'Ravina Mohapatra', 'Team Lead', '25000'),
(12, 'Raghav Malhotra', 'Sr. Software Engineer', '42000');</pre>
<p>pagination.php is the File where I am <a href="https://jharaphula.com/data-json-to-html-table-php/" target="_blank" rel="noopener noreferrer">binding data to a HTML table</a> and at the same time implemented pagination. This is a very simple working example of pagination. You can easily customize it as per your requirements. To decide how many records you want to display in a page here I declared 2 variable $begin=0; $end=4;. By updating the second variable $end you can change the number of records per page.</p>
<h2>PHP pagination Example</h2>
<pre class="brush: php; title: ; notranslate">&lt;?php
/*Establishing Database Connection*/
$sql_query=mysql_connect(&quot;localhost&quot;, &quot;root&quot;);
mysql_select_db(&quot;empdb&quot;, $sql_query);

/*Defining number of records in a page*/
$begin=0;
$end=4;

if(isset($_GET['id']))
{
$id=$_GET['id'];
$begin=($id-1)*$end;
} else {
$id = 0;
}

/*Executing &amp; fetching data from SQL table*/
$emp_query=mysql_query(&quot;SELECT * FROM EmpDetails LIMIT $begin, $end&quot;);

$rows=mysql_num_rows(mysql_query(&quot;SELECT * FROM EmpDetails&quot;));
$total=ceil($rows/$end);

/*Creating table dynamically*/
echo &quot;&lt;table&gt;&quot;;

/*Defining Table header*/
echo &quot;&lt;tr&gt;&lt;th&gt;Employee Name&lt;/th&gt;&lt;th&gt;Designation&lt;/th&gt;&lt;th&gt;Salary&lt;/th&gt;&lt;/tr&gt;&quot;;

/*Generating rows with data*/
while($data=mysql_fetch_array($emp_query)) {
echo &quot;&lt;tr&gt;&quot;;
echo &quot;&lt;td&gt;&quot;. $data['Emp_Name'] .&quot;&lt;/td&gt;&quot;;
echo &quot;&lt;td&gt;&quot;. $data['Emp_Designation'] .&quot;&lt;/td&gt;&quot;;
echo &quot;&lt;td&gt;&quot;. $data['Emp_Salary'] .&quot;&lt;/td&gt;&quot;;
echo &quot;&lt;/tr&gt;&quot;;
}
echo &quot;&lt;/table&gt;&quot;;

/*Implemented next and previous buttons*/
if($id&gt;1)
{
echo &quot;&lt;div class='parallalpre'&gt;&lt;a href='?id=&quot;.($id-1).&quot;' class='pagButton'&gt;PREVIOUS&lt;/a&gt;&amp;nbsp;&lt;/div&gt;&quot;;
}
if($id!=$total)
{
?&gt;

&lt;div class='parallal'&gt;

&lt;?php
/*Generating Pagination Tabs*/
echo &quot;&lt;ul class='pagination'&gt;&quot;;
for($i=1;$i&lt;=$total;$i++)
{
if($i==$id) { echo &quot;&lt;li&gt;&quot;.$i.&quot;&lt;/li&gt;&quot;; }

else { echo &quot;&lt;li&gt;&lt;a href='?id=&quot;.$i.&quot;'&gt;&quot;.$i.&quot;&lt;/a&gt;&lt;/li&gt;&quot;; }
}
echo &quot;&lt;/ul&gt;&quot;;
?&gt;

&lt;/div&gt;

&lt;?php
echo &quot;&lt;div class='parallalnex'&gt;&amp;nbsp;&lt;a href='?id=&quot;.($id+1).&quot;' class='pagButton'&gt;NEXT&lt;/a&gt;&lt;/div&gt;&quot;;
}
?&gt;</pre>
<p>Using the above code you can have a PHP pagination with table of data. To make the pagination better in below I am with some CSS classes. These classes provides style to pagination.</p>
<h2>Required CSS Classes</h2>
<pre class="brush: css; title: ; notranslate">/*Style for Table*/
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 4px;
font-family: arial;
}
/*Style for Table Header*/
th {
background: darkblue;
color: white;
text-align: left;
}
/*Style for Alternate Rows*/
table tr:nth-child(odd) {
background-color: #C2EBC3;
}
table tr:nth-child(even) {
background-color: #FFFFFF;
}

/*Style for Pagination*/
.parallal { float:left; }
.parallalnex, .parallalpre { float:left; margin-top: 16px; }
.pagination { margin-top: 16px; padding:0; }

.pagination li {
display: inline-block;
padding: 0px 9px;
margin-right: 4px;
border-radius: 3px;
border: solid 1px #c0c0c0;
background: #e9e9e9;
box-shadow: inset 0px 1px 0px rgba(255,255,255, .8), 0px 1px 3px rgba(0,0,0, .1);
font-size: .875em;
font-weight: bold;
text-decoration: none;
color: #717171;
text-shadow: 0px 1px 0px rgba(255,255,255, 1);
}

.pagination li:hover, .pagination.gradient:hover {
background: #fefefe;
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#FEFEFE), to(#f0f0f0));
background: -moz-linear-gradient(0% 0% 270deg,#FEFEFE, #f0f0f0);
}</pre>
<p>The post <a href="https://jharaphula.com/simple-php-pagination-example-mysql/">Simple PHP pagination Example using MySQL records</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/simple-php-pagination-example-mysql/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/05/datatable-pagination.png" medium="image" />
	</item>
		<item>
		<title>Simple string to image based free PHP Captcha Code</title>
		<link>https://jharaphula.com/simple-free-php-captcha-code/</link>
					<comments>https://jharaphula.com/simple-free-php-captcha-code/#respond</comments>
		
		<dc:creator><![CDATA[Nibedita Panda]]></dc:creator>
		<pubDate>Sun, 15 May 2016 17:59:49 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[Client Side Captcha]]></category>
		<category><![CDATA[Free PHP Captcha Code]]></category>
		<category><![CDATA[Generating Captcha]]></category>
		<category><![CDATA[Script for PHP]]></category>
		<category><![CDATA[Simple String to Image]]></category>
		<guid isPermaLink="false">http://box.jharaphula.com/?p=1683</guid>

					<description><![CDATA[<img width="300" height="195" src="https://jharaphula.com/wp-content/uploads/2016/05/captcha-300x195.png" class="webfeedsFeaturedVisual wp-post-image" alt="Simple string to image based free PHP Captcha Code" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/captcha-300x195.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/captcha-294x190.png 294w, https://jharaphula.com/wp-content/uploads/2016/05/captcha-106x70.png 106w, https://jharaphula.com/wp-content/uploads/2016/05/captcha.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>In web Captcha is the Technique using which we can protect spam users. Today hackers are very cleaver. Let&#8217;s talk about a login page. Here...</p>
<p>The post <a href="https://jharaphula.com/simple-free-php-captcha-code/">Simple string to image based free PHP Captcha Code</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="195" src="https://jharaphula.com/wp-content/uploads/2016/05/captcha-300x195.png" class="webfeedsFeaturedVisual wp-post-image" alt="Simple string to image based free PHP Captcha Code" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/captcha-300x195.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/captcha-294x190.png 294w, https://jharaphula.com/wp-content/uploads/2016/05/captcha-106x70.png 106w, https://jharaphula.com/wp-content/uploads/2016/05/captcha.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>In web Captcha is the Technique using which we can protect spam users. Today hackers are very cleaver. Let&#8217;s talk about a login page. Here someone can easily enter spam records using a script. Captcha gives confirmation that the user is a real-human. The story behind Captcha is &#8220;We generate a random string and store that in server. In the next moment showing the same string to the user as an image. To validate comparing server session value with user input against the image&#8221;. In below demo app I am creating a PHP Captcha.</p>
<h2>Understanding CAPTCHA</h2>
<p>CAPTCHAs serve as a barrier against automated attacks, such as brute-force login attempts, spam form submissions, and credential stuffing. By presenting a challenge that requires human-like interpretation—such as distorted text, image recognition, or logical puzzles—CAPTCHAs help protect web applications from abuse.</p>
<p>String-to-image CAPTCHAs are particularly effective because they rely on visual distortion, noise, and variable fonts to prevent optical character recognition (OCR) tools from extracting the text.</p>
<h2>How String-to-Image CAPTCHA Works?</h2>
<p>1. String Generation: A random string (usually alphanumeric) is generated.<br />
2. Image Creation: The string is rendered onto an image with distortions, such as warping, overlapping lines, or varying colors.<br />
3. Session Storage: The CAPTCHA value is stored server-side (e.g., in a session) for later validation.<br />
4. User Input: The user reads the image and submits the text via a form.<br />
5. Validation: The submitted text is compared against the stored value.</p>
<p>Here I defined 4 functions CAPTCHA, randomString, hexadecimalToRGB and alignImageToCenter. The function CAPTCHA is responsible to Create Captcha image. It accepts 4 params $textColor, $backgroundColor, $imgWidth, $imgHeight. $textColor is the color for text. $backgroundColor is the captcha background. $imgWidth &amp; $imgHeight is decides area for capatch. randomString function generating random strings which I am converting later into Captcha image. hexadecimalToRGB is the color converter function. While generating image alignImageToCenter is responsible for aling <a href="https://jharaphula.com/javascript-function-random-string/" target="_blank" rel="noopener noreferrer">random string</a> to center.</p>
<p>The base function to generate Captcha is &#8220;CAPTCHA&#8221;. In this function initially I am with some configurable variables. Then generating a random string and providing style. Finally using PHP imagettftext() function generating the Captcha image.</p>
<h3>PHP-Captcha.php</h3>
<pre class="brush: php; title: ; notranslate">&lt;?php
/*Executing the Function Captcha*/
CAPTCHA('#162453', '#fff', 120, 40);

/*Function to Generate Captcha*/
function CAPTCHA($textColor, $backgroundColor, $imgWidth, $imgHeight)
{
/* Configuration Settings */
$font = './font/mono.ttf';
$fontSize = $imgHeight * 0.75;
$textColor = hexadecimalToRGB($textColor);

/*Generating and Storing random string to $rnd variable*/
$rnd = randomString();

$im = imagecreatetruecolor($imgWidth, $imgHeight);	
$textColor = imagecolorallocate($im, $textColor['r'], $textColor['g'], $textColor['b']);			

$bgColor = hexadecimalToRGB($backgroundColor);
$backgroundColor = imagecolorallocate($im, $bgColor['r'],$bgColor['g'],$bgColor['b']);				

imagefill($im, 0, 0, $backgroundColor);	
list($x, $y) = alignImageToCenter($im, $rnd, $font, $fontSize);	
imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $rnd);		

/*Displaying image*/
imagejpeg($im, NULL, 90);

/*Declaring Image Type*/
header('Content-Type: image/jpeg');
imagedestroy($im);/* Destroying image instance */

/*Storing the random string to a Session variable*/
if(isset($_SESSION)){
$_SESSION['captcha_code'] = $rnd;/* set random text in session for captcha validation*/
}
}

/*This for is responsible to generate Random string for Captcha*/
function randomString($length=6){
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i &lt; $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}

/*Using this function I am extracting RBG value form Hexadecimal Color*/
function hexadecimalToRGB($colour)
{
$hex = str_replace(&quot;#&quot;, &quot;&quot;, $colour); 

if(strlen($hex) == 3) { 
$red = hexdec(substr($hex,0,1).substr($hex,0,1)); 
$green = hexdec(substr($hex,1,1).substr($hex,1,1)); 
$blue = hexdec(substr($hex,2,1).substr($hex,2,1)); 
} else { 
$red = hexdec(substr($hex,0,2)); 
$green = hexdec(substr($hex,2,2)); 
$blue = hexdec(substr($hex,4,2)); 
}
return array( 'r' =&gt; $red, 'g' =&gt; $green, 'b' =&gt; $blue );
}		

/*Function to position Image to the Center*/
function alignImageToCenter($image, $text, $font, $size, $angle = 8) 
{
$xi = imagesx($image);
$yi = imagesy($image);
$box = imagettfbbox($size, $angle, $font, $text);
$xr = abs(max($box[2], $box[4]));
$yr = abs(max($box[5], $box[7]));
$x = intval(($xi - $xr) / 2);
$y = intval(($yi + $yr) / 2);
return array($x, $y);	
}
?&gt;</pre>
<p>To run the above code additionally you required to Create a font folder in root directory. Download a ttf image file. Put that in the font folder. Without ttf font file this PHP Captcha program will not run.</p>
<h2>Enhancing CAPTCHA Security</h2>
<p>1. Dynamic Distortion: Vary the distortion level for each character.<br />
2. Variable Length: Randomize the string length.<br />
3. Case Sensitivity: Enforce case sensitivity if needed.<br />
4. Expiration: Set a time limit for CAPTCHA validity.<br />
5. Rate Limiting: Limit CAPTCHA attempts per IP.</p>
<h2>Alternatives to Traditional CAPTCHA</h2>
<p>While string-to-image CAPTCHAs are effective, they can be inconvenient for users. Alternatives include:</p>
<p>&#8211; reCAPTCHA (Google): Uses behavioral analysis and image recognition.<br />
&#8211; hCaptcha: Privacy-focused alternative to reCAPTCHA.<br />
&#8211; Math-Based CAPTCHA: Requires solving a simple arithmetic problem.</p>
<h2>Conclusion</h2>
<p>String-to-image CAPTCHA remains a reliable method for preventing automated attacks while maintaining accessibility for human users. By leveraging PHP’s GD library, developers can implement a customizable CAPTCHA system with varying levels of complexity. However, balancing security and usability is crucial—excessive distortion may frustrate users, while insufficient measures may fail to deter bots. For high-security applications, integrating third-party solutions like reCAPTCHA may offer better protection with minimal development overhead.</p>
<p>The post <a href="https://jharaphula.com/simple-free-php-captcha-code/">Simple string to image based free PHP Captcha Code</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/simple-free-php-captcha-code/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/05/captcha.png" medium="image" />
	</item>
		<item>
		<title>How to display data from JSON to HTML table using PHP?</title>
		<link>https://jharaphula.com/data-json-to-html-table-php/</link>
					<comments>https://jharaphula.com/data-json-to-html-table-php/#comments</comments>
		
		<dc:creator><![CDATA[Nibedita Panda]]></dc:creator>
		<pubDate>Sun, 15 May 2016 17:51:23 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[GetJSON Example]]></category>
		<category><![CDATA[HTML table using PHP]]></category>
		<category><![CDATA[JSON to HTML Table]]></category>
		<category><![CDATA[Script for PHP]]></category>
		<category><![CDATA[XML to HTML Table]]></category>
		<guid isPermaLink="false">http://box.jharaphula.com/?p=1671</guid>

					<description><![CDATA[<img width="300" height="174" src="https://jharaphula.com/wp-content/uploads/2016/05/html-table-300x174.png" class="webfeedsFeaturedVisual wp-post-image" alt="How to display data from JSON to HTML table using PHP?" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/html-table-300x174.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/html-table.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>JSON (JavaScript Object Notation) is a platform independent data inter-exchange technology. To bulid a JSON file we follow XML formatting. JavaScript program can easily convert...</p>
<p>The post <a href="https://jharaphula.com/data-json-to-html-table-php/">How to display data from JSON to HTML table using PHP?</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="174" src="https://jharaphula.com/wp-content/uploads/2016/05/html-table-300x174.png" class="webfeedsFeaturedVisual wp-post-image" alt="How to display data from JSON to HTML table using PHP?" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/html-table-300x174.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/html-table.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>JSON (<em>JavaScript Object Notation</em>) is a platform independent data inter-exchange technology. To bulid a JSON file we follow XML formatting. JavaScript program can easily convert JSON data into JavaScript objects. Like a database using <a href="https://jharaphula.com/learn-json-tutorial-for-beginners/" target="_blank" rel="noopener noreferrer">JSON</a> we can store and retrieve data with multiple fields. In this demo app I am fetching a well formatted JSON file using PHP file_get_contents method. Then dynamically using html table, tr and td presenting those JSON records in a HTML Table.</p>
<h2>Converting Data from JSON to HTML Tables</h2>
<p>JSON is a lightweight data interchange format widely used for transmitting data between servers and web applications. HTML tables, on the other hand, provide a structured way to display data in rows and columns on a webpage. Converting JSON data into an HTML table is a common task in web development, enabling developers to present data in a readable and organized manner. This article explores various methods to achieve this conversion, including manual JavaScript approaches, using libraries, and leveraging modern frameworks.</p>
<p>To start with first let me create a valid JSON file. In below JSON file for each node we have 4 fields empName, designation, company and mob. To present data using JSON we follow key, value pair. Curly braces hold objects while Square brackets hold arrays.</p>
<h3>emp_records.json</h3>
<pre class="brush: jscript; title: ; notranslate">{&quot;employees&quot;:
[
{
&quot;empName&quot;: &quot;Swati Nanda&quot;,
&quot;designation&quot;: &quot;Project Manager&quot;,
&quot;company&quot;: &quot;InfoSys&quot;,
&quot;mob&quot;: &quot;9092353322&quot;
},
{
&quot;empName&quot;: &quot;Pravat Mishra&quot;,
&quot;designation&quot;: &quot;English Trainer&quot;,
&quot;company&quot;: &quot;FM College&quot;,
&quot;mob&quot;: &quot;7847324432&quot;
},
{
&quot;empName&quot;: &quot;Divya Singh&quot;,
&quot;designation&quot;: &quot;Sr. Content Writer&quot;,
&quot;company&quot;: &quot;Wipro&quot;,
&quot;mob&quot;: &quot;9625477893&quot;
},
{
&quot;empName&quot;: &quot;Baby Roy&quot;,
&quot;designation&quot;: &quot;Graphic Engineer&quot;,
&quot;company&quot;: &quot;Tech Mahindra&quot;,
&quot;mob&quot;: &quot;9096266548&quot;
},
{
&quot;empName&quot;: &quot;Satyabrata Panda&quot;,
&quot;designation&quot;: &quot;Sr. Software Engineer&quot;,
&quot;company&quot;: &quot;Capgemini&quot;,
&quot;mob&quot;: &quot;5567748833&quot;
},
{
&quot;empName&quot;: &quot;Sonam Singh&quot;,
&quot;designation&quot;: &quot;Graphic Engineer&quot;,
&quot;company&quot;: &quot;TCS&quot;,
&quot;mob&quot;: &quot;8260272137&quot;
},
{
&quot;empName&quot;: &quot;Subash Roy&quot;,
&quot;designation&quot;: &quot;Jr. Software Engineer&quot;,
&quot;company&quot;: &quot;InfoSys BPO&quot;,
&quot;mob&quot;: &quot;5237748822&quot;
},
{
&quot;empName&quot;: &quot;Mohini Mohapatra&quot;,
&quot;designation&quot;: &quot;UI/UX Engineer&quot;,
&quot;company&quot;: &quot;Synechron&quot;,
&quot;mob&quot;: &quot;8892978436&quot;
},
{
&quot;empName&quot;: &quot;Supriti Kabi&quot;,
&quot;designation&quot;: &quot;Sr. HTML Developer&quot;,
&quot;company&quot;: &quot;InfoSys BPO&quot;,
&quot;mob&quot;: &quot;6667748877&quot;
}
]
}</pre>
<p><img loading="lazy" decoding="async" src="https://jharaphula.com/wp-content/uploads/2016/05/php-table-with-json-data.jpg" alt="php-table-with-json-data" width="754" height="173" class="alignnone size-full wp-image-1802" srcset="https://jharaphula.com/wp-content/uploads/2016/05/php-table-with-json-data.jpg 754w, https://jharaphula.com/wp-content/uploads/2016/05/php-table-with-json-data-300x69.jpg 300w" sizes="auto, (max-width: 754px) 100vw, 754px" /></p>
<p>Now create your PHP file with the below lines of Code.</p>
<h3>JSON-to-HTML.php</h3>
<pre class="brush: php; title: ; notranslate">/*Fetching JSON file content using php file_get_contents method*/
$str_data = file_get_contents(&quot;emp-records.json&quot;);
$data = json_decode($str_data, true);

/*Initializing temp variable to design table dynamically*/
$temp = &quot;&lt;table&gt;&quot;;

/*Defining table Column headers depending upon JSON records*/
$temp .= &quot;&lt;tr&gt;&lt;th&gt;Employee Name&lt;/th&gt;&quot;;
$temp .= &quot;&lt;th&gt;Designation&lt;/th&gt;&quot;;
$temp .= &quot;&lt;th&gt;Company&lt;/th&gt;&quot;;
$temp .= &quot;&lt;th&gt;Mobile Number&lt;/th&gt;&lt;/tr&gt;&quot;;

/*Dynamically generating rows &amp; columns*/
for($i = 0; $i &lt; sizeof($data[&quot;employees&quot;]); $i++)
{
$temp .= &quot;&lt;tr&gt;&quot;;
$temp .= &quot;&lt;td&gt;&quot; . $data[&quot;employees&quot;][$i][&quot;empName&quot;] . &quot;&lt;/td&gt;&quot;;
$temp .= &quot;&lt;td&gt;&quot; . $data[&quot;employees&quot;][$i][&quot;designation&quot;] . &quot;&lt;/td&gt;&quot;;
$temp .= &quot;&lt;td&gt;&quot; . $data[&quot;employees&quot;][$i][&quot;company&quot;] . &quot;&lt;/td&gt;&quot;;
$temp .= &quot;&lt;td&gt;&quot; . $data[&quot;employees&quot;][$i][&quot;mob&quot;] . &quot;&lt;/td&gt;&quot;;
$temp .= &quot;&lt;/tr&gt;&quot;;
}

/*End tag of table*/
$temp .= &quot;&lt;/table&gt;&quot;;

/*Printing temp variable which holds table*/
echo $temp;</pre>
<p>Using the above PHP codes first I am reading the JSON file using file_get_contents() method. Then after using json_decode() method I am decoding the JSON data and storing in a variable like an Array. Temp is the variable which I used to generate dynamic html for table. Using string concatenation I am appending html and $data values to $temp. Finally using using echo I am printing the value of $temp.</p>
<p>Inside the table to Create dynamic rows I am using a for loop over total records count. To get total record count here I am using sizeof() method against $data[&#8220;employees&#8221;] array. Then depending upon JSON records I am binding respective values to td&#8217;s for each row.</p>
<h3>tblClasses.css</h3>
<pre class="brush: css; title: ; notranslate">/*Style for Table*/
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 4px;
font-family: arial;
}
/*Style for Table Header*/
th {
background: darkblue;
color: white;
text-align: left;
}
/*Style for Alternate Rows*/
table tr:nth-child(odd) {
background-color: #C2EBC3;
}
table tr:nth-child(even) {
background-color: #FFFFFF;
}</pre>
<p>Without the above CSS code this demo app will run. But to make your HTML table beautiful this CSS classes can help. Just copy paste these classes under style tag. This will give you a table as shown in the above figure. You must noticed here I am using tr:nth-child(odd) and tr:nth-child(even) with different background colors. This CSS selector helps to distigush alternate rows with different color codes.</p>
<h2>Best Practices</h2>
<p>improper usage can lead to inefficiencies, security vulnerabilities, and poor user experiences. By following best practices, developers can ensure JSON is used effectively, optimizing performance, enhancing accessibility, and maintaining data integrity.</p>
<p><strong>1. Validate JSON Data</strong></p>
<p>Ensuring JSON data is correctly structured and free from errors is crucial for application stability.</p>
<p>Use Schema Validation JSON Schema provides a standardized way to define the structure of JSON data. By validating incoming JSON against a schema, developers can catch malformed data early. Tools like AJV (Another JSON Schema Validator) for JavaScript or jsonschema for Python help enforce data integrity.</p>
<p>Sanitize Inputs Malicious or malformed JSON can lead to security risks such as injection attacks. Always sanitize inputs before parsing. Libraries like DOMPurify for browser-based applications or custom validation logic can prevent unsafe data from being processed.</p>
<p>Handle Parsing Errors Gracefully Use `try-catch` blocks when parsing JSON to manage errors without crashing the application. For example:</p>
<p>javascript try { const data = JSON.parse(jsonString); } catch (error) { console.error(&#8220;Invalid JSON format:&#8221;, error); }</p>
<p><strong>2. Optimize Performance</strong></p>
<p>Efficient JSON usage reduces latency and improves application responsiveness.</p>
<p>Minify JSON Removing unnecessary whitespace and line breaks reduces file size, speeding up transmission. Tools like JSON.stringify() with replacer functions or online minifiers can help.</p>
<p>Use Compression For large JSON payloads, enable Gzip or Brotli compression on the server to minimize bandwidth usage. Most web servers (e.g., Nginx, Apache) support compression out of the box.</p>
<p>Lazy Load Large Datasets Instead of loading entire JSON files at once, implement pagination or streaming for large datasets. For example, Node.js streams can process JSON data in chunks:</p>
<p>javascript const fs = require(&#8216;fs&#8217;); const stream = fs.createReadStream(&#8216;large-data.json&#8217;); stream.on(&#8216;data&#8217;, (chunk) => processChunk));</p>
<p>Cache JSON Responses Leverage browser caching (`Cache-Control` headers) or server-side caching (Redis, Memcached) to avoid redundant JSON fetches.</p>
<p><strong>3. Enhance Accessibility</strong></p>
<p>JSON should be structured to support assistive technologies and diverse user needs.</p>
<p>Use Semantic Keys Choose descriptive key names that convey meaning. For example:</p>
<p>json { &#8220;user&#8221;: { &#8220;name&#8221;: &#8220;John Doe&#8221;, &#8220;email&#8221;: &#8220;john@example.com&#8221; } }</p>
<p>Instead of:</p>
<p>json { &#8220;u&#8221;: { &#8220;n&#8221;: &#8220;John Doe&#8221;, &#8220;e&#8221;: &#8220;john@example.com&#8221; } }</p>
<p>Support Localization Store multilingual content in a structured way for easy translation:</p>
<p>json { &#8220;greeting&#8221;: { &#8220;en&#8221;: &#8220;Hello&#8221;, &#8220;es&#8221;: &#8220;Hola&#8221;, &#8220;fr&#8221;: &#8220;Bonjour&#8221; } }</p>
<p>Provide Alternative Text for Media When JSON includes media references, include `altText` for screen readers:</p>
<p>json { &#8220;image&#8221;: { &#8220;url&#8221;: &#8220;profile.jpg&#8221;, &#8220;altText&#8221;: &#8220;Profile picture of John Doe&#8221; } }</p>
<p><strong>4. Responsive Design with JSON</strong></p>
<p>JSON can dynamically adapt to different devices and screen sizes.</p>
<p>Serve Conditional Data Return only necessary fields based on device type. For example, mobile clients may require fewer data points than desktop:</p>
<p>json { &#8220;product&#8221;: { &#8220;id&#8221;: 123, &#8220;name&#8221;: &#8220;Smartphone&#8221;, &#8220;price&#8221;: 599, &#8220;mobile&#8221;: { &#8220;thumbnail&#8221;: &#8220;phone-sm.jpg&#8221; }, &#8220;desktop&#8221;: { &#8220;gallery&#8221;: [&#8220;phone-1.jpg&#8221;, &#8220;phone-2.jpg&#8221;] } } }</p>
<p>Use Media Queries with JSON Frontend frameworks can conditionally render JSON data based on screen size:</p>
<p>javascript const responsiveData = window.innerWidth < 768 ? mobileData : desktopData;

Optimize for Low-Bandwidth Users Provide fallback JSON structures with reduced detail for slow connections:

json { "lowBandwidthMode": true, "essentialData": { "title": "Basic Content", "summary": "Simplified version for slow connections" } }



<h2>Conclusion</h2>
<p>Converting JSON to HTML tables is a fundamental task in web development, facilitating the display of structured data on webpages. Whether using vanilla JavaScript, libraries, or frameworks, developers can choose the method that best suits their project requirements. By following best practices, the resulting tables will be efficient, accessible, and user-friendly.</p>
<p>The post <a href="https://jharaphula.com/data-json-to-html-table-php/">How to display data from JSON to HTML table using PHP?</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/data-json-to-html-table-php/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/05/html-table.png" medium="image" />
	</item>
		<item>
		<title>PHP Treeview Example using data from MySQL Database</title>
		<link>https://jharaphula.com/php-treeview-example-database/</link>
					<comments>https://jharaphula.com/php-treeview-example-database/#comments</comments>
		
		<dc:creator><![CDATA[Nibedita Panda]]></dc:creator>
		<pubDate>Sun, 15 May 2016 17:43:05 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[Data from MySQL Database]]></category>
		<category><![CDATA[JQuery Treeview example]]></category>
		<category><![CDATA[PHP Treeview Example]]></category>
		<category><![CDATA[Pure CSS Treeview Example]]></category>
		<guid isPermaLink="false">http://box.jharaphula.com/?p=1667</guid>

					<description><![CDATA[<img width="300" height="193" src="https://jharaphula.com/wp-content/uploads/2016/05/treeview-demo-app-300x193.png" class="webfeedsFeaturedVisual wp-post-image" alt="PHP Treeview Example using data from MySQL Database" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/treeview-demo-app-300x193.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/treeview-demo-app-294x190.png 294w, https://jharaphula.com/wp-content/uploads/2016/05/treeview-demo-app.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>To present bulk of data with parent child relationship Treeview is a classical approach. The major advantage of Treeview is using a Treeview we can...</p>
<p>The post <a href="https://jharaphula.com/php-treeview-example-database/">PHP Treeview Example using data from MySQL Database</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="193" src="https://jharaphula.com/wp-content/uploads/2016/05/treeview-demo-app-300x193.png" class="webfeedsFeaturedVisual wp-post-image" alt="PHP Treeview Example using data from MySQL Database" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/treeview-demo-app-300x193.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/treeview-demo-app-294x190.png 294w, https://jharaphula.com/wp-content/uploads/2016/05/treeview-demo-app.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>To present bulk of data with parent child relationship Treeview is a classical approach. The major advantage of Treeview is using a Treeview we can show more data in less space. Assume that you have a global recruitment portal. You want to display job opportunities depending upon Countries and their Cities. In this case you required a Treeview.</p>
<p>Using a Treeview easily you can display Countries &amp; related Cities hirarchically. In this session let us share sample codes for a PHP Treeview using data from MySQL Database. In front-end using PHP I am binding data to ol li <a href="https://jharaphula.com/list-of-html5-new-tags/" target="_blank" rel="noopener noreferrer">element of HTML</a>. Then by applying CSS styles giving expand and collapse effects to the Treeview. Let us explain this PHP Treeview Example Step by Step.</p>
<p><strong>1</strong>. Create a MySQL table &#8220;tab_treeview&#8221;. Consider &#8220;id&#8221; as the Primary key. During an user enter a record to this SQL table I need the primary field entry need to jump 1 after 1 automatically. Thats why here I declared id filed with &#8220;auto_increment&#8221; property. To store Treeview node details Create 2 other Columns name and title. These fields are with datatype varchar(255). While inserting records keep noted these fields will accept only 255 charecters. You can&#8217;t entry a null value to these fields as NOT NULL attributes specifies. Then to establish parent child relationship created one more column &#8220;parent_id&#8221;. This will store reference of parent node. If parent_id is zero then that record is itself a parent node.</p>
<h2>Query to Create table tab_treeview</h2>
<pre class="brush: sql; title: ; notranslate">CREATE TABLE IF NOT EXISTS tab_treeview (
id int(12) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
title varchar(255) NOT NULL,
parent_id varchar(12) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7;</pre>
<p><strong>2</strong>. To start with first you need to insert some sample records to &#8220;tab_treeview&#8221; SQL table. While inserting sample records stay careful about parent_id. A wrong parent_id can change your Treeview structure and nodes.</p>
<h2>Query to Insert sample Records</h2>
<pre class="brush: sql; title: ; notranslate">INSERT INTO tab_treeview (id, name, title, parent_id) VALUES
(1, 'Mumbai', 'The Film City', '3'),
(2, 'New Delhi', 'Capital of India', '3'),
(3, 'India', 'Country', '0'),
(4, 'United States', 'Country', '0'),
(5, 'Washington', 'Popular City of US', '4'),
(6, 'New York', 'Popular City of US', '4'),
(7, 'Olympia', 'Capital of Washington', '5'),
(8, 'Russia', 'Country', '0'),
(9, 'Moscow', 'Popular City of Russia', '8'),
(10, 'Saint Petersburg', 'Popular City of Russia', '8')
(11, 'Bihar', 'State of India', '3'),
(12, 'Uttar Pradesh', 'State of India', '3'),
(13, 'Himachal Pradesh', 'State of India', '3');</pre>
<h2>PHP Treeview Example (<em>Binding Data from Database</em>)</h2>
<p><strong>3</strong>. Create a blank HTML page. Then in body inside PHP tag Copy n Paste the below recursive function &#8220;buildTree()&#8221;. Keep notice this is the function which generates Treeview html. In this function using a foreach loop I am dealing each record from the database. Then dynamically using HTML5 ol li and echo function from PHP writing the ordered list as a treeview.</p>
<h2>buildTree() Recursive function</h2>
<p>This approach is often used to break down complex problems into simpler subproblems, allowing for easier management and resolution. When implementing a recursive function, it is essential to define a base case to prevent infinite loops and ensure that the function eventually terminates. Additionally, careful consideration of the function&#8217;s parameters and return values is crucial for maintaining clarity and efficiency in the code.</p>
<pre class="brush: php; title: ; notranslate">function buildTree($array, $currentParent, $currLevel = 0, $prevLevel = -1) {
foreach ($array as $categoryId =&gt; $category) {
if ($currentParent == $category['parent_id']) {
if ($currLevel &gt; $prevLevel) echo &quot;&lt;ol id='menutree'&gt;&quot;; 
if ($currLevel == $prevLevel) echo &quot;&lt;/li&gt;&quot;;
echo '&lt;li&gt; &lt;label class=&quot;menu_label&quot; for='.$categoryId.'&gt;'.$category['name'].'&lt;/label&gt;&lt;input type=&quot;checkbox&quot; id='.$categoryId.' /&gt;';
if ($currLevel &gt; $prevLevel) { $prevLevel = $currLevel; }
$currLevel++; 
buildTree ($array, $categoryId, $currLevel, $prevLevel);
$currLevel--;   
}
}
if ($currLevel == $prevLevel) echo &quot;&lt;/li&gt; &lt;/ol&gt;&quot;;
}</pre>
<p>Using the recursive function buildTree() inside a foreach loop over $array length I am building each li element of ordered list. To position the cursor for next item here I am using $currLevel++ increment operator. Here orderlist id is &#8220;menutree&#8221;.</p>
<p><strong>4</strong>. Below the &#8220;buildTree()&#8221; function Copy n Paste the below PHP codes. Here using this block I am fetching data from tab_treeview table.</p>
<h2>Understanding the Structure of a Treeview</h2>
<p>A treeview is a hierarchical data structure that organizes information in a parent-child relationship, resembling an inverted tree. It is widely used in computer science, databases, file systems, and user interfaces to represent nested data efficiently. The structure consists of nodes, each serving a specific role in the hierarchy. The four primary components of a treeview are the root node, parent node, child node, and leaf node. Understanding these elements is essential for working with tree-like data models.</p>
<h3>The Root Node</h3>
<p>The root node is the topmost element in a treeview hierarchy. In a file system, for example, the root directory (often represented as &#8220;/&#8221; in Unix-based systems or &#8220;C:\&#8221; in Windows) is the root node. All files and subdirectories stem from this single point.</p>
<p>A key characteristic of the root node is that it is always singular in a well-formed tree structure. Multiple root nodes would imply separate trees, often referred to as a forest in data structure terminology. The root node’s primary function is to provide a reference point for traversing the hierarchy, allowing algorithms to navigate downward through parent and child relationships.</p>
<h3>Parent Nodes</h3>
<p>A parent node is any node in the treeview that has one or more child nodes connected beneath it. Parent nodes act as containers for their children, grouping related data into meaningful subsets. For instance, in an organizational chart, a department head (parent node) may oversee several team leads (child nodes), who in turn manage individual employees.</p>
<p>Parent nodes can themselves be children of higher-level parents, creating multiple layers of depth in the tree. The ability to collapse or expand parent nodes in a graphical user interface (GUI) enhances usability by allowing users to hide or reveal details as needed.</p>
<h3>Child Nodes</h3>
<p>Child nodes are direct descendants of a parent node. Each child node can have only one immediate parent, ensuring a clear hierarchical relationship. Child nodes inherit certain properties from their parents, such as access permissions in a file system or organizational roles in a management hierarchy.</p>
<p>A child node may also function as a parent if it has its own descendants, creating a multi-level tree structure. For example, in a product category tree, &#8220;Electronics&#8221; might be a child of the root node, while &#8220;Smartphones&#8221; is a child of &#8220;Electronics,&#8221; and &#8220;Brand X&#8221; is a child of &#8220;Smartphones.&#8221; This chaining of relationships allows for detailed and scalable data organization.</p>
<h3>Leaf Nodes</h3>
<p>They represent the most granular level of data in the hierarchy. In a file system, individual files are leaf nodes, whereas directories act as parent nodes. Similarly, in a family tree, individuals without descendants would be considered leaf nodes.</p>
<p>Leaf nodes often contain actionable or displayable data, such as file contents in a directory, employee names in an org chart, or product details in an e-commerce category tree. Their position at the end of branches makes them crucial for data retrieval operations, as they hold the actual information rather than just structural references.</p>
<p>Understanding the structure of a treeview—comprising root nodes, parent nodes, child nodes, and leaf nodes—is fundamental for efficient data organization and retrieval. This hierarchical model provides clarity, scalability, and flexibility, making it indispensable in various fields. Whether navigating file systems, designing databases, or structuring user interfaces, recognizing the roles of each node ensures optimal system performance and usability. Mastery of treeview principles empowers users and developers to harness the full potential of hierarchical data representation.</p>
<p>Treeviews can be rendered using HTML, CSS, and JavaScript, with PHP handling the backend logic to fetch and structure the data.</p>
<h2>Traversal Techniques</h2>
<p>Navigating a treeview involves moving from one node to another using specific algorithms. The two primary traversal methods are:</p>
<p>1. <strong>Depth-First Search (DFS)</strong>: Explores as far down a branch as possible before backtracking. Variations include in-order, pre-order, and post-order traversals.<br />
2. <strong>Breadth-First Search (BFS)</strong>: Visits nodes level by level, starting from the root and moving downward in layers.</p>
<h2>Fetching data from MySQL Database</h2>
<p>As natural first using mysql_connect I am pointing my PHP Compiler to localhost mysql database as the user root. In next step using mysql_select_db pre-defiend php function I am selecting treeview specific database from MySQL server. Now we need to execute the sql query &#8220;SELECT * FROM tab_treeview&#8221; to fetch data from db. To do that using mysql_query and storing all records to an array $arrayCountry.</p>
<pre class="brush: php; title: ; notranslate">
/*Connecting to Database tempdb*/
mysql_connect('localhost', 'root');
mysql_select_db('tempdb');

/*Executing the select query to fetch data from table tab_treeview*/
$sqlqry=&quot;SELECT * FROM tab_treeview&quot;;
$result=mysql_query($sqlqry);

/*Defining an array*/
$arrayCountry = array();

while($row = mysql_fetch_assoc($result)){ 
$arrayCountry[$row['id']] = array(&quot;parent_id&quot; =&gt; $row['parent_id'], &quot;name&quot; =&gt; $row['name']);
}

/*Checking is there any records in $result array*/
if(mysql_num_rows($result)!=0)
{
/*Calling the recursive function*/
buildTree($arrayCountry, 0);
}</pre>
<p>Finally on array of data using while loop to build the tree. Inside while loop after checking data persist for the existing row calling the recursive function buildTree($arrayCountry, 0);. Where the first parameter is the $arrayCountry. The function buildTree() accepts 4 parameters. Using this you can customize your treeview as needed.</p>
<p><strong>5</strong>. Now you can able to watch Treeview data in your html page. Apply the below CSS styles to implement expand and collapse effects. Add a style tag in html file head section and copy the below CSS styles. To customize this dynamic Treeview including the below classes you can add your additional CSS Classes.</p>
<h2>CSS Styles for PHP Treeview</h2>
<p>To remove default bulleted list from my ordered list items here I am using list-style: none; for my menu menutree. On clickable node of tree to my the cursor with hand symbol here I am using cursor: pointer for all menu labels.</p>
<pre class="brush: css; title: ; notranslate">#menutree li { list-style: none; }
li .menu_label + input[type=checkbox] { opacity: 0; }
li .menu_label { cursor: pointer; }
li .menu_label + input[type=checkbox] + ol &gt; li { display: none; }
li .menu_label + input[type=checkbox]:checked + ol &gt; li { display: block; }</pre>
<h2>Security Considerations</h2>
<p>Modern web applications face numerous security threats that can compromise user data, disrupt services, and damage organizational reputations. Three critical vulnerabilities—SQL Injection, Cross-Site Scripting (XSS), and Cross-Site Request Forgery (CSRF)—pose significant risks if not properly mitigated. Understanding these threats and implementing protective measures is essential for maintaining a secure digital environment.</p>
<h3>SQL Injection</h3>
<p>By inserting malicious SQL queries into input fields, attackers can manipulate or extract sensitive data, bypass authentication, and even execute administrative operations.</p>
<p><strong>Prevention Techniques</strong></p>
<p>1. Parameterized Queries (Prepared Statements) Using parameterized queries ensures that user input is treated as data rather than executable code. Most modern database libraries support this method.</p>
<p>2. Input Validation Restrict input to expected formats (e.g., alphanumeric characters only) and reject suspicious patterns (e.g., SQL keywords).</p>
<p>3. Stored Procedures Encapsulate database logic in stored procedures, reducing direct SQL string manipulation.</p>
<p>4. Least Privilege Principle Database accounts should have minimal permissions necessary for the application, limiting damage in case of a breach.</p>
<h3>Cross-Site Scripting (XSS) Prevention</h3>
<p>Cross-Site Scripting (XSS) happens due to the injection of malicious scripts. These scripts can steal session cookies, deface websites, or redirect users to phishing sites.</p>
<p><strong>Types of XSS</strong></p>
<p>1. Reflected XSS Malicious scripts are embedded in URLs or forms and executed when the victim loads a manipulated link.</p>
<p>2. Stored XSS Attackers inject persistent scripts into a database or file, which are later served to users.</p>
<p>3. DOM-Based XSS Scripts manipulate the Document Object Model (DOM) directly in the victim&#8217;s browser without server interaction.</p>
<p><strong>Prevention Techniques</strong></p>
<p>1. Output Encoding Encode dynamic content before rendering it in HTML, JavaScript, or other contexts to neutralize malicious scripts.</p>
<p>2. Content Security Policy (CSP) Define a CSP header to restrict sources of executable scripts, reducing the impact of XSS attacks.</p>
<p>3. Input Sanitization Remove or escape unsafe characters (e.g., `<`, `>`, `&#038;`) from user-generated content.</p>
<p>4. HTTP-Only Cookies Mark session cookies as HTTP-only to prevent JavaScript access, mitigating cookie theft.</p>
<h3>CSRF Protection</h3>
<p>Cross-Site Request Forgery (CSRF) tricks users into executing unintended actions on a web application where they are authenticated. Attackers exploit the trust between a user’s browser and a legitimate website to submit forged requests.</p>
<p><strong>Prevention Techniques</strong></p>
<p>1. Anti-CSRF Tokens Require a unique, unpredictable token with each state-changing request. The token must match the one stored on the server.</p>
<p>2. SameSite Cookies Set the `SameSite` attribute for cookies to `Strict` or `Lax` to prevent cross-origin requests.</p>
<p>3. Double-Submit Cookies Store the CSRF token in both a cookie and a hidden form field, validating both upon submission.</p>
<p>4. Require Re-Authentication For sensitive actions (e.g., password changes), force users to confirm their credentials again.</p>
<p>Security threats like SQL Injection, XSS, and CSRF require proactive measures to prevent exploitation. Developers must adopt secure coding practices, validate and sanitize input, implement robust authentication mechanisms, and stay updated on emerging threats. By prioritizing security, organizations can safeguard user data and maintain trust in their digital services.</p>
<h2>Performance Optimization</h2>
<p><strong>Lazy Loading</strong> – This approach enhances performance and reduces resource consumption, particularly in web applications where numerous elements may be present. Load only visible nodes.</p>
<p><strong>Indexing</strong> – Ensure `parent_id` is indexed for faster queries.</p>
<h2>Real-World Applications</h2>
<p>Treeview is a useful tool that helps us organize information in a way that is easy to understand. Imagine you have a big box of toys. If you just dump them all out, it can be hard to find what you want. But if you sort them into groups—like cars in one section and dolls in another—it becomes much easier. In the real world, treeviews are used in many places, like on websites or apps. For example, when you look at files on a computer, the treeview shows folders and files in a clear way. This helps you find what you need quickly. Treeviews are also used in educational apps to break down topics into smaller parts, making learning simpler and more fun. Overall, treeviews help people manage and find information more easily, just like organizing your toys!</p>
<p>1. File Managers – Display directories and files.<br />
2. E-Commerce Categories – Organize product hierarchies.<br />
3. Navigation Menus – Create multi-level dropdowns.</p>
<h2>Conclusion</h2>
<p>A PHP treeview is a powerful tool for displaying hierarchical data in a structured and interactive manner. By combining PHP for backend logic, HTML/CSS for presentation, and JavaScript for interactivity, developers can create efficient and user-friendly treeviews. Whether used in file systems, navigation menus, or organizational charts, mastering treeview implementation enhances web application usability and functionality.</p>
<p>The post <a href="https://jharaphula.com/php-treeview-example-database/">PHP Treeview Example using data from MySQL Database</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/php-treeview-example-database/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/05/treeview-demo-app.png" medium="image" />
	</item>
		<item>
		<title>PHP File Handling methods with suitable Examples</title>
		<link>https://jharaphula.com/php-file-handling-methods-examples/</link>
					<comments>https://jharaphula.com/php-file-handling-methods-examples/#comments</comments>
		
		<dc:creator><![CDATA[Nibedita Panda]]></dc:creator>
		<pubDate>Sun, 15 May 2016 17:41:52 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[File Handling methods]]></category>
		<category><![CDATA[File Operation using PHP]]></category>
		<category><![CDATA[File Upload to Server]]></category>
		<category><![CDATA[PHP File Handling]]></category>
		<category><![CDATA[PHP upload Image File]]></category>
		<guid isPermaLink="false">http://box.jharaphula.com/?p=1665</guid>

					<description><![CDATA[<img width="300" height="187" src="https://jharaphula.com/wp-content/uploads/2016/05/PHP-File-Operation-300x187.png" class="webfeedsFeaturedVisual wp-post-image" alt="PHP File Handling methods with suitable Examples" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/PHP-File-Operation-300x187.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/PHP-File-Operation.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>In a Web application generally we use File to store data. Assume that in your CMS you want to generate HTML files for each content...</p>
<p>The post <a href="https://jharaphula.com/php-file-handling-methods-examples/">PHP File Handling methods with suitable Examples</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="187" src="https://jharaphula.com/wp-content/uploads/2016/05/PHP-File-Operation-300x187.png" class="webfeedsFeaturedVisual wp-post-image" alt="PHP File Handling methods with suitable Examples" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/PHP-File-Operation-300x187.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/PHP-File-Operation.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>In a Web application generally we use File to store data. Assume that in your CMS you want to generate HTML files for each content you like to publish. Here you required File Operations. Before move into the basics of File Operations using <a href="https://jharaphula.com/category/programming-solutions/php-demo-apps/" target="_blank" rel="noopener noreferrer">PHP</a> let you recall every File has its own properties like File Name, File Size, File Type or Created Date. File to File depending upon the header information File type varies. In PHP to get started with File Operations first you need to learn the following PHP File Handling methods.</p>
<table>
<tr>
<th>Methods</th>
<th>Description</th>
</tr>
<tr>
<td><em>fopen()</em></td>
<td>In PHP using fopen() method we can open a file. fopen() accepts 2 parameters. First parameter is the File Name and second parameter is the mode. There are 6 types of modes r (Open file in read-only mode), r+ (Open the file for writing and reading), w (Open the file for write only mode), w+ (Open the file for reading and writing), a (Open the file for writing only), a+ (Open the file for reading and writing only).</td>
</tr>
<tr>
<td><em>fread()</em></td>
<td>Using fopen() once we open the file to read the contents we use fread(). The method fread() acts like a pointer. It accepts 2 parameters.</td>
</tr>
<tr>
<td><em>fwrite()</em></td>
<td>Using this method we can write or append a File. To execute fwrite() first it is mandatory to open the File. fwrite() accepts 2 parameters. First parameter is the File pointer and second parameter is string of data you want to write in the File.</td>
</tr>
<tr>
<td><em>fclose()</em></td>
<td>Use to close File. fclose() operators exactly opposite to fopen() method.</td>
</tr>
<tr>
<td><em>filesize()</em></td>
<td>Using this method we can retrieve the Size of a File.</td>
</tr>
<tr>
<td><em>readfile()</em></td>
<td>This method we use to read a file. Compare to fopen() readfile() writes the output to buffer.</td>
</tr>
<tr>
<td><em>unlink()</em></td>
<td>This method we use to delete a File.</td>
</tr>
</table>
<h3>Create a File using PHP</h3>
<p>To Create a File in PHP we use fopen() method with writing mode (w). Look at the below example how I am Creating a text file &#8220;demo.txt&#8221; using fopen() method.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$tempFile = 'demo.txt';
$handle = fopen($tempFile, 'w') or die('Unable to Open file:  '.$tempFile);
?&gt;</pre>
<h3>Open &amp; Read a File</h3>
<p>In this example I am using fopen to open and fread to read the file. To run the below example Create a text file (sample.txt) with few lines of Contents. Then use open and read methods.</p>
<pre class="brush: php; title: ; notranslate">$tempFile = 'sample.txt';
$handle = fopen($tempFile, 'r');
$data = fread($handle,filesize($tempFile));
echo $data;</pre>
<p>Also using readfile() you can read a file in PHP. This method is so simple to implement. Look at the example below.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo readfile(&quot;sample.txt&quot;);
?&gt;</pre>
<h3>Example to Write or Append a File in PHP</h3>
<p>In PHP to write contents into a file first we required to open the file. Once the file opened successfully we can use fwrite() method to write contents. In the below example I am writing 2 lines to a text file.</p>
<pre class="brush: php; title: ; notranslate">$tempFile = 'demo.txt';
$handle = fopen($tempFile, 'a') or die('Unable to Open file:  '.$tempFile);
$data = 'This is the First line.';
fwrite($handle, $data);
$new_line = &quot;\n&quot;.'This is the Second line I am appending.';
fwrite($handle, $new_line);</pre>
<h3>Close or Delete a File in PHP</h3>
<p>As a principle of PHP File handling make practice to Close a file after did with the required operations. To close a file we use fclose(). Look at the below example.</p>
<pre class="brush: php; title: ; notranslate">$tempFile = 'demo.txt';
$handle = fopen($tempFile, 'a') or die('Unable to Open file:  '.$tempFile);
$data = 'I am working at InfoSys.';
fwrite($handle, $data);
fclose($handle);</pre>
<p>Similarly to delete a file we use unlink() method. Assume that you have a text file in root folder. To delete that you can go for the below line codes.</p>
<pre class="brush: php; title: ; notranslate">$tempFile = 'demo.txt';
unlink($tempFile);</pre>
<p>The post <a href="https://jharaphula.com/php-file-handling-methods-examples/">PHP File Handling methods with suitable Examples</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/php-file-handling-methods-examples/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/05/PHP-File-Operation.png" medium="image" />
	</item>
		<item>
		<title>JQuey AJAX File Upload Example using PHP Server</title>
		<link>https://jharaphula.com/jquey-ajax-file-upload-example-php/</link>
					<comments>https://jharaphula.com/jquey-ajax-file-upload-example-php/#respond</comments>
		
		<dc:creator><![CDATA[Nibedita Panda]]></dc:creator>
		<pubDate>Sun, 15 May 2016 17:36:34 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[Ajax Example]]></category>
		<category><![CDATA[AJAX File Upload Example]]></category>
		<category><![CDATA[ASP.NET File Upload]]></category>
		<category><![CDATA[File Upload to Server]]></category>
		<category><![CDATA[How to implement AJAX?]]></category>
		<category><![CDATA[PHP upload Image File]]></category>
		<guid isPermaLink="false">http://box.jharaphula.com/?p=1663</guid>

					<description><![CDATA[<img width="300" height="187" src="https://jharaphula.com/wp-content/uploads/2016/05/Ajax-File-Uploader-300x187.png" class="webfeedsFeaturedVisual wp-post-image" alt="JQuey AJAX File Upload Example using PHP Server" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/Ajax-File-Uploader-300x187.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/Ajax-File-Uploader.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>Jquery is a Client Side programming language. Independently using jquery it is not possible to upload a file to PHP Server. To upload a file...</p>
<p>The post <a href="https://jharaphula.com/jquey-ajax-file-upload-example-php/">JQuey AJAX File Upload Example using PHP Server</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="187" src="https://jharaphula.com/wp-content/uploads/2016/05/Ajax-File-Uploader-300x187.png" class="webfeedsFeaturedVisual wp-post-image" alt="JQuey AJAX File Upload Example using PHP Server" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/Ajax-File-Uploader-300x187.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/Ajax-File-Uploader.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>Jquery is a Client Side programming language. Independently using jquery it is not possible to upload a file to PHP Server. To upload a file using jquery what we can do is we can use <a href="https://jharaphula.com/jquery-ajax-example-get-post-methods/" target="_blank" rel="noopener noreferrer">jquery post method</a> to send the file to the Server. Then in Server we required a PHP script to upload the file to the respective physical folder. In the below example I am uploading a file to PHP Server using JQuey AJAX File Upload technique.</p>
<p>In HTML I have 2 Controls an input box with type=&#8221;file&#8221; and a Submit button. These 2 controls are inside the form element. The form &#8220;frmUploading&#8221; is with action=&#8221;php-uploader.php&#8221; to my PHP page. The form enctype type is &#8220;multipart/form-data&#8221;. In head section I embedded 2 jquery libraries (jquery.min.js &amp; jquery.form.min.js). Using input type file after the user choose the file successfully I am submitting the form inside jquery document.ready() method using jquery form Ajax method ajaxForm().</p>
<h3>AJAX-File-Upload.htm</h3>
<pre class="brush: xml; title: ; notranslate">&lt;!DOCTYPE html&gt;
&lt;head&gt;
&lt;title&gt;JQuey AJAX File Upload Example&lt;/title&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;https://code.jquery.com/jquery-2.2.3.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h2&gt;AJAX File Upload Example&lt;/h2&gt;

&lt;form id=&quot;frmUploading&quot; action=&quot;php-uploader.php&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
&lt;input type=&quot;file&quot; size=&quot;70&quot; name=&quot;fileSelector&quot; /&gt;
&lt;input type=&quot;submit&quot; value=&quot;Upload your File&quot; /&gt;
&lt;/form&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
var options = { 
beforeSend: function() 
{
/*In this block you can initiate any value before Uploading. */
},
uploadProgress: function(event, position, total, percentComplete) 
{
/*During a large file uploading in this event you can show progress bar. */
},
success: function() 
{
/*This block executes after file successfully uploaded. */
},
complete: function(response) 
{
/*Once your file uploaded successful at the end you show a message here. */
},
error: function()
{
/*In-case file uploading get failure here you can show errors. */
}

$(document).ready(function()
{ 
/*Submitting the form using jquery form Ajax method. */
$(&quot;#frmUploading&quot;).ajaxForm(options); 
}); 
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>Using jquery form once the file post to the Server. There I am executing the below script. To upload the user file I created a folder in root with the name &#8220;uploads&#8221;. That folder path I am storing in &#8220;$upload_dir&#8221; php variable. Using isset($_FILES[&#8220;fileSelector&#8221;]) I am checking whether the user choose file successfully or not. If it is returning true then I am checking is there any error in fileSelector or else using php move_uploaded_file() method uploading the file. To run this demo app first create the above index.htm file. Then create the below php file in the same folder. Here I am uploading my files to &#8220;uploads&#8221; folder. You can update this as per your folder location.</p>
<h3>php-uploader.php</h3>
<pre class="brush: php; title: ; notranslate">&lt;?php
/* where you want to upload your file, define that folder path here. */
$upload_dir = &quot;uploads/&quot;;

if(isset($_FILES[&quot;fileSelector&quot;]))
{
/* using this block you can filter the file types */
if ($_FILES[&quot;fileSelector&quot;][&quot;error&quot;] &gt; 0)
{
echo &quot;Error Occurred: &quot; . $_FILES[&quot;file&quot;][&quot;error&quot;] . &quot;&lt;br /&gt;&quot;;
}
else
{
/* move the uploaded file to uploads folder */
move_uploaded_file($_FILES[&quot;fileSelector&quot;][&quot;tmp_name&quot;],$upload_dir. $_FILES[&quot;fileSelector&quot;][&quot;name&quot;]);
echo &quot;Your file :&quot; . $_FILES[&quot;fileSelector&quot;][&quot;name&quot;] . &quot; uploaded successfully.&quot;;
}
}
?&gt;</pre>
<p>The post <a href="https://jharaphula.com/jquey-ajax-file-upload-example-php/">JQuey AJAX File Upload Example using PHP Server</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/jquey-ajax-file-upload-example-php/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/05/Ajax-File-Uploader.png" medium="image" />
	</item>
		<item>
		<title>Techniques behind PHP Error Handling for Developer</title>
		<link>https://jharaphula.com/php-error-handling-techniques/</link>
					<comments>https://jharaphula.com/php-error-handling-techniques/#respond</comments>
		
		<dc:creator><![CDATA[Nibedita Panda]]></dc:creator>
		<pubDate>Sun, 15 May 2016 17:32:50 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[Error Handling for Developer]]></category>
		<category><![CDATA[Firebug]]></category>
		<category><![CDATA[PHP Error Handling]]></category>
		<category><![CDATA[PHP File Handling]]></category>
		<category><![CDATA[PHP String Functions]]></category>
		<guid isPermaLink="false">http://box.jharaphula.com/?p=1657</guid>

					<description><![CDATA[<img width="300" height="171" src="https://jharaphula.com/wp-content/uploads/2016/05/php-program-300x171.png" class="webfeedsFeaturedVisual wp-post-image" alt="Techniques behind PHP Error Handling for Developer" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/php-program-300x171.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/php-program.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>In Software Designing &#8220;Zero Defects&#8221; is a Challenge. To achieve &#8220;Zero Defects&#8221; we depends upon many factors. Starting from &#8220;Developers Team&#8221; to &#8220;Quality Assurance&#8221; all...</p>
<p>The post <a href="https://jharaphula.com/php-error-handling-techniques/">Techniques behind PHP Error Handling for Developer</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="171" src="https://jharaphula.com/wp-content/uploads/2016/05/php-program-300x171.png" class="webfeedsFeaturedVisual wp-post-image" alt="Techniques behind PHP Error Handling for Developer" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/php-program-300x171.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/php-program.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>In Software Designing &#8220;Zero Defects&#8221; is a Challenge. To achieve &#8220;Zero Defects&#8221; we depends upon many factors. Starting from &#8220;Developers Team&#8221; to &#8220;Quality Assurance&#8221; all are equally responsible for an error in production. To reduce error the primary role a developer&#8217;s play. I believe in the matter of Error or Exception handling a Experienced developer do better than a fresher. This is the cause we are hunting experience professionals. During an application development Coding Can any developer do but quality Coding is rare. To write an error free logic we required to understood &#8220;How Compiler works?&#8221; and what are the ways to handle exceptions. In this session let us share <a href="https://jharaphula.com/category/programming-solutions/php-demo-apps/" target="_blank" rel="noopener noreferrer">PHP</a> Error Handling technique for Developer.</p>
<h3>Practice to PHP Error Handling using Try Catch block</h3>
<p>While implementing a logic do the Complex part (Which has more Chance for Exception) in-side Try .. Catch block. Try Catch block has 3 units Try, Catch and Finally. Each try block must at-least required one catch block. More than one catch blocks can be used to catch different classes of exceptions.</p>
<p>Let us assume you are going to insert a record to the database. In this case after created the SQL query dynamically, while executing that query do that inside the try block. During run-time if connection will break with Server during database interaction the execution will jump to Catch block. In Catch block you can know the Error &amp; handle the Exception. Finally block execute at any case. If there is a error in try block then after Catch block finally block executes. Similarly if try block executes successfully then also Finally block executes. It is a best place for Close Database Connection.</p>
<p><strong>Example of Try .. Catch</strong></p>
<pre class="brush: php; title: ; notranslate">try {
throw new Exception('error');
}
catch(Exception $e) {
echo &quot;There is an Error.&quot;;
throw $e;
}
finally {
// Code in Finally block Overrides the exception
return &quot;\nException erased&quot;;
}</pre>
<p>Some Errors occurs in run-time for those errors Try Catch is the best approach to deal. Let&#8217;s talk an another example. While Sending mail execute the Send() method in-side Try Catch block. In run-time in-case the SMTP Server is down. System will show the real error message &#8220;Mail Server is Down. Please try later&#8221;.</p>
<h3>Use PHP die() method</h3>
<p>Die() is a simple and effective PHP Error Handling method. When ever there is a possibility of an error use die() method. Generally die() method is useful for Conditional Checking. For an example if you are going to upload a file here while you are checking &#8220;is file exists?&#8221; using <code>if(!file_exists("/tmp/logo.png"))</code> use die() method to handle possible errors. Look at the example below.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
if(!file_exists(&quot;/tmp/logo.png&quot;)) {
die(&quot;File is not exists Physically.&quot;);
} else {
$file = fopen(&quot;/tmp/logo.png&quot;,&quot;r&quot;);
print &quot;Able to Open the File Successfully.&quot;;
}
?&gt;</pre>
<p>In the above example before Opening the file I am checking is there any file exists to open. If there is no such files using die() method with message &#8220;File is not exists Physically.&#8221;. Die() method handles error as well as Clears memory whole. Kills unwanted process and helps to improve performance.</p>
<h3>Create Custom Error Handler</h3>
<p>Using PHP it is very easy to Create Custom Error handlers. The Syntax is as below.</p>
<p><code>error_function(error_level, error_message, error_file, error_line, error_context)</code></p>
<p>While Creating a Custom Error function keep remember that the first two parameters are mandatory. The rest 3 (error_file, error_line and error_context) are optional. Error_level must be a value in number. Refer the below table to know more about the error_level values.</p>
<table>
<tr>
<th>Value</th>
<th>Constants</th>
<th>Description</th>
</tr>
<tr>
<td>1</td>
<td>.E_ERROR</td>
<td>Error level with value 1 indicates run-time Fatal errors. Execution of the script is halted.</td>
</tr>
<tr>
<td>2</td>
<td>E_WARNING</td>
<td>Error level with value 2 indicated run-time Non-fatal errors. Compare to Error level 1 here execution of the script is not halted.</td>
</tr>
<tr>
<td>4</td>
<td>E_PARSE</td>
<td>Error level with value 4 indicates Compile-time parse errors.</td>
</tr>
<tr>
<td>8</td>
<td>E_NOTICE</td>
<td>Value 8 is for run-time notices. During execution the script found something that might be an error, but could also happen when running a script normally.</td>
</tr>
<tr>
<td>16</td>
<td>E_CORE_ERROR</td>
<td>Error level with value 16 indicates Fatal errors. Fatal Errors generally occur during PHP initial start-up.</td>
</tr>
<tr>
<td>32</td>
<td>E_CORE_WARNING</td>
<td>The error level value 32 speaks non-fatal run-time errors. This also occurs during PHP initial start-up.</td>
</tr>
<tr>
<td>256</td>
<td>E_USER_ERROR</td>
<td>Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error().</td>
</tr>
<tr>
<td>512</td>
<td>E_USER_WARNING</td>
<td>Error level with value 512 indicates Non-fatal user generated warning. It is similar to E_WARNING set by the developer using the PHP trigger_error() function.</td>
</tr>
<tr>
<td>1024</td>
<td>E_USER_NOTICE</td>
<td>The error code with 1024 value speaks user-generated notice. This is like an E_NOTICE set by the developer using the PHP function trigger_error().</td>
</tr>
<tr>
<td>4096</td>
<td>E_RECOVERABLE_ERROR</td>
<td>This error level says Catchable fatal error. It is like an E_ERROR but can be caught by a user defined error handlers.</td>
</tr>
<tr>
<td>8191</td>
<td>E_ALL</td>
<td>The error level value 8191 indicates all errors and warnings.</td>
</tr>
</table>
<p>All the listed error levels you can use with PHP in-built function &#8220;error_reporting()&#8221;. The Syntax is as &#8220;error_reporting ([int $level])&#8221;.</p>
<p>While defining a Custom error handler function you need to use PHP in-built library set_error_handler() function.</p>
<h3>Trigger an Error</h3>
<p>In Script where user inputs data use trigger_error() function to handle illegal inputs. Trigger error can be use for Server side validations.</p>
<p><strong>Example of trigger_error</strong></p>
<pre class="brush: php; title: ; notranslate">&lt;?php
$myVal = 3;
if ($myVal &gt; 2) {
trigger_error(&quot;Value must be 2 or below&quot;);
}
?&gt;</pre>
<h3>Exception Classes</h3>
<p>While Creating a Custom Error there are following functions which can be used from Exception class.</p>
<table>
<tr>
<th>Function</th>
<th>Description</th>
</tr>
<tr>
<td>getMessage()</td>
<td>This function shows exact message why error occurs. What are the possible factors generate the error.</td>
</tr>
<tr>
<td>getCode()</td>
<td>Using getCode() we can detect the block of Code showing Error.</td>
</tr>
<tr>
<td>getFile()</td>
<td>Shows Source File name.</td>
</tr>
<tr>
<td>getLine()</td>
<td>This function shows in which line error occurred. It saves programmer time to locate error.</td>
</tr>
<tr>
<td>getTrace()</td>
<td>It&#8217;s an array of the back-trace()</td>
</tr>
<tr>
<td>getTraceAsString()</td>
<td>Presents Formatted string of Trace.</td>
</tr>
</table>
<p><strong>Referrals:</strong></p>
<p><a href="http://www.tutorialspoint.com/php/php_error_handling.htm" target="_blank" rel="noopener noreferrer nofollow">http://www.tutorialspoint.com/php/php_error_handling.htm</a><br />
<a href="http://www.w3schools.com/php/php_error.asp" target="_blank" rel="nofollow noopener noreferrer">http://www.w3schools.com/php/php_error.asp</a></p>
<p>The post <a href="https://jharaphula.com/php-error-handling-techniques/">Techniques behind PHP Error Handling for Developer</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/php-error-handling-techniques/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/05/php-program.png" medium="image" />
	</item>
		<item>
		<title>Script for PHP upload image file to Server using move_uploaded_file()</title>
		<link>https://jharaphula.com/script-php-upload-image-file-server/</link>
					<comments>https://jharaphula.com/script-php-upload-image-file-server/#respond</comments>
		
		<dc:creator><![CDATA[Nibedita Panda]]></dc:creator>
		<pubDate>Sun, 15 May 2016 12:52:22 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[File Upload to Server]]></category>
		<category><![CDATA[move_uploaded_file]]></category>
		<category><![CDATA[PHP Mail Function]]></category>
		<category><![CDATA[PHP upload Image File]]></category>
		<category><![CDATA[Script for PHP]]></category>
		<guid isPermaLink="false">http://box.jharaphula.com/?p=1501</guid>

					<description><![CDATA[<img width="300" height="187" src="https://jharaphula.com/wp-content/uploads/2016/05/php-file-uploading-300x187.png" class="webfeedsFeaturedVisual wp-post-image" alt="Script for PHP upload image file to Server using move_uploaded_file()" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/php-file-uploading-300x187.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/php-file-uploading.png 746w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>PHP is a high level server side programming language. To upload an image file first you need to update the php.ini file. Open the php.ini...</p>
<p>The post <a href="https://jharaphula.com/script-php-upload-image-file-server/">Script for PHP upload image file to Server using move_uploaded_file()</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="187" src="https://jharaphula.com/wp-content/uploads/2016/05/php-file-uploading-300x187.png" class="webfeedsFeaturedVisual wp-post-image" alt="Script for PHP upload image file to Server using move_uploaded_file()" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/php-file-uploading-300x187.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/php-file-uploading.png 746w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>PHP is a high level server side <a href="https://jharaphula.com/how-to-become-a-programmer/" rel="noopener noreferrer" target="_blank">programming</a> language. To upload an image file first you need to update the php.ini file. Open the php.ini file. Search &#8220;file_uploads&#8221;. Update the line &#8220;file_uploads = On&#8221;.</p>
<p>Then to upload the file you need to Create HTML. Look at the example below. Here I have a input type=&#8221;file&#8221; control &amp; a submit button. Both these controls are inside the form element. With form I am using post method to send my image files to the server. Finally after successful uploading showing File Name, Size &amp; Type to the user using a UL li element.</p>
<p>To restrict user on file type to upload I created an array &#8220;expensions&#8221;. Here you can declare any specific file type you want to allow the user. In this example I allowed &#8220;jpeg&#8221;,&#8221;jpg&#8221;,&#8221;png&#8221;.</p>
<p>During file upload to track the errors I am with one more array &#8220;errorlog&#8221;. In case of a failure I am displaying the error details using echo function.</p>
<h3>Script for PHP upload image</h3>
<pre class="brush: php; title: ; notranslate">&lt;?php
if(isset($_FILES['uploader'])){

$errorlog = array();

$fileSize = $_FILES['uploader']['size'];
$fileType = $_FILES['uploader']['type'];
$fileTemp = $_FILES['uploader']['tmp_name'];
$fileName = $_FILES['uploader']['name'];

$fileExtension = strtolower(end(explode('.',$_FILES['uploader']['name'])));

$expensions= array(&quot;jpeg&quot;,&quot;jpg&quot;,&quot;png&quot;);

if(in_array($fileExtension,$expensions)=== false){
$errorlog[] = &quot;This file type is not allowed, Select a JPEG or PNG file.&quot;;
}

if($fileSize &gt; 2097152){
$errorlog[] = 'Your file size is more than 2 MB. Upload a file less then 2 MB.';
}

if(empty($errors)==true){
move_uploaded_file($fileTemp,&quot;images/&quot;.$fileName);
echo &quot;Successfully Uploaded.&quot;;
}
else {
print_r($errorlog);
}
}
?&gt;
&lt;html&gt;
&lt;body&gt;
&lt;form action=&quot;&quot; method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot;&gt;
&lt;input type=&quot;file&quot; name=&quot;uploader&quot; /&gt;
&lt;input type=&quot;submit&quot;/&gt;
&lt;ul&gt;
&lt;li&gt;Sent File - &lt;?php echo $_FILES['uploader']['name']; ?&gt;&lt;/li&gt;
&lt;li&gt;File Size - &lt;?php echo $_FILES['uploader']['size']; ?&gt;&lt;/li&gt;
&lt;li&gt;File Type - &lt;?php echo $_FILES['uploader']['type']; ?&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<h2>Security Considerations</h2>
<p>While the above example works, it lacks several critical security measures. Below are some best practices to ensure secure file uploads:</p>
<p>1. Restrict File Types Only allow specific file extensions to prevent malicious uploads.</p>
<p>2. Rename Uploaded Files Using predictable filenames can lead to security risks. Instead, generate a unique name for each file:</p>
<p>php $newFileName = uniqid() . &#8216;.&#8217; . $imageFileType; $targetFile = $targetDir . $newFileName;</p>
<p>3. Validate File Content Relying solely on file extensions is unsafe. Use functions like `getimagesize()` to verify the file is indeed an image.</p>
<p>4. Set File Size Limits Prevent denial-of-service attacks by restricting the maximum file size.</p>
<p>5. Store Files Outside the Web Root If possible, store uploaded files in a directory that is not publicly accessible.</p>
<h2>Conclusion</h2>
<p>Uploading image files to a server using PHP involves multiple steps, from creating an HTML form to implementing server-side validation and security measures. By following best practices—such as restricting file types, renaming files, and validating content—developers can ensure a robust and secure file upload system. Always test the implementation thoroughly to handle edge cases and provide meaningful feedback to users. Properly managing file uploads enhances both functionality and security in web applications.</p>
<p>The post <a href="https://jharaphula.com/script-php-upload-image-file-server/">Script for PHP upload image file to Server using move_uploaded_file()</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/script-php-upload-image-file-server/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/05/php-file-uploading.png" medium="image" />
	</item>
		<item>
		<title>PHP Mail Function to Send Email &#038; Encoded attachments</title>
		<link>https://jharaphula.com/php-mail-send-email-attachments/</link>
					<comments>https://jharaphula.com/php-mail-send-email-attachments/#respond</comments>
		
		<dc:creator><![CDATA[Nibedita Panda]]></dc:creator>
		<pubDate>Sun, 15 May 2016 07:58:57 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[Email with Encoded attachments]]></category>
		<category><![CDATA[Function to Send Email]]></category>
		<category><![CDATA[PHP Mail Function]]></category>
		<category><![CDATA[Web Designers]]></category>
		<guid isPermaLink="false">http://box.jharaphula.com/?p=1351</guid>

					<description><![CDATA[<img width="300" height="186" src="https://jharaphula.com/wp-content/uploads/2016/05/send-an-email-300x186.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="PHP mail function to Send email &amp; Encoded attachments" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/send-an-email-300x186.jpg 300w, https://jharaphula.com/wp-content/uploads/2016/05/send-an-email.jpg 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>Email is a cost effective solution to send &#38; receive massages faster &#38; secure. In web application development sending mail is a very common activity....</p>
<p>The post <a href="https://jharaphula.com/php-mail-send-email-attachments/">PHP Mail Function to Send Email &amp; Encoded attachments</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="186" src="https://jharaphula.com/wp-content/uploads/2016/05/send-an-email-300x186.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="PHP mail function to Send email &amp; Encoded attachments" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/send-an-email-300x186.jpg 300w, https://jharaphula.com/wp-content/uploads/2016/05/send-an-email.jpg 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>Email is a cost effective solution to send &amp; receive massages faster &amp; secure. In web application development sending mail is a very common activity. Whether a on-line job consultancy or an employee management system every where you required email facility. Email is a derived technology of postal service. To send an mail we required To, From at minimum. To means who is going to receive the mail &amp; from is the sender.</p>
<p>Among many web development <a href="https://jharaphula.com/category/programming-solutions/php-demo-apps/" target="_blank" rel="noopener noreferrer">programming languages PHP</a> is popular. It required open source environment to execute. The cause the server cost is less in PHP, compare to other web development technologies. In PHP to send a mail there is a mail() function. Look at the syntax below.</p>
<pre class="brush: xml; title: ; notranslate">mail(to,subject,message,headers,parameters);</pre>
<p>PHP mail() function accepts 5 parameters. First parameter is to whom you want to send the mail. This value is an email id. Next parameter is subject, here you can mention the Title of your message. This param accepts String value. Third parameter is the real message. These 3 parameters are mandatory. Rest 2 headers &amp; parameters are optional. Headers specify the additional headers like Content-type, From, CC &amp; BCC. Last param specify additional parameters to send mail function.</p>
<p>Normally two types of mails we send Text &amp; HTML based. To send text mail when declaring message for mail() function you need to add pure texts like $message = &#8220;This mail body contains simple text message.&#8221;;. But in case you want to send a mail with HTML format in this case if you have a small message you can do in-line HTML while declaring $message. If your message is bigger it was advisable to define a string variable &amp; concatenate HTML entries with message characters. Additionally in header declare content-type to text/html. Look at the example below.</p>
<h3>Example to send HTML format Mail using PHP</h3>
<pre class="brush: php; title: ; notranslate">&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Send HTML format mail using PHP&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;?php
$to = &quot;admin@jharaphula.com&quot;;
$subject = &quot;Demo PHP mail Function&quot;;
$message = &quot;&lt;b&gt;I am a regular reader of jharaphula.&lt;/b&gt;&quot;;
$message .= &quot;&lt;h2&gt;This is the Header.&lt;/h2&gt;&quot;;
$header = &quot;From:customer@yourdomain.com \r\n&quot;;
$header = &quot;Cc:panda.biswabhusan@gmail.com \r\n&quot;;
$header .= &quot;MIME-Version: 1.0\r\n&quot;;
$header .= &quot;Content-type: text/html\r\n&quot;;
$sendMail = mail ($to, $subject, $message, $header);
if($sendMail == true)
{
echo &quot;Your email sent successfully.&quot;;
}
else
{
echo &quot;Email could not be sent.&quot;;
}
?&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<h3>Example to send text Mail using PHP</h3>
<pre class="brush: php; title: ; notranslate">&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Send text mail using PHP&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;?php
$to = &quot;admin@jharaphula.com&quot;;
$subject = &quot;Demo PHP mail Function&quot;;
$message = &quot;I am a regular reader of jharaphula. This is a text msg.&quot;;
$header = &quot;From:customer@yourdomain.com \r\n&quot;;
$sendMail = mail ($to, $subject, $message, $header);
if($sendMail == true)
{
echo &quot;Your email sent successfully.&quot;;
}
else
{
echo &quot;Email could not be sent.&quot;;
}
?&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>During we send a mail we not only send the content but also some time we required to send attachments. Your attachment can be a file or an image too. So let us know how to send attachment using php mail() function.</p>
<p>To send an attachment first thing is to define is the content-type to <strong>multipart/mixed</strong>. Using this mail function will know that the email you are going to send is with an attachment. Then the next thing is when send a file over network to make the file transfer secure you can use php base64_encode() function. Look at the below example.</p>
<h3>Sending attachment using PHP mail function</h3>
<pre class="brush: php; title: ; notranslate">&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Send attachment based email using PHP&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;?php
$to = &quot;admin@jharaphula.com&quot;;
$subject = &quot;This is a demo mail&quot;;
$message = &quot;This message contents file attachment.&quot;;
# Using PHP file funtion Open the file.
$file = fopen( &quot;/tmp/demo.txt&quot;, &quot;r&quot; );
if($file == false)
{
echo &quot;Error in file. Unable to Open.&quot;;
exit();
}
# Read the file and store the content into a variable
$fsize = filesize(&quot;/tmp/demo.txt&quot;);
$fcontent = fread($file, $fsize);

# encode the data for secure transaction and insert \r\n after every 76 chars.
$encoded_Con = chunk_split(base64_encode($fcontent));

# Generate a random 32 bit number using time() function and md5 algorithm.
$number = md5(time());

$header = &quot;From:customer@yourdomain.com\r\n&quot;;
$header .= &quot;MIME-Version: 1.0\r\n&quot;;
$header .= &quot;Content-Type: multipart/mixed; &quot;;
$header .= &quot;boundary=$number\r\n&quot;;
$header .= &quot;--$number\r\n&quot;;

# Define the header information for message section
$header .= &quot;Content-Type: text/plain\r\n&quot;;
$header .= &quot;Content-Transfer-Encoding:8bit\r\n\n&quot;;
$header .= &quot;$message\r\n&quot;;
$header .= &quot;--$number\r\n&quot;;

# Define the header information for attachment section
$header .= &quot;Content-Type:  multipart/mixed; &quot;;
$header .= &quot;name=\&quot;demo.txt\&quot;\r\n&quot;;
$header .= &quot;Content-Transfer-Encoding:base64\r\n&quot;;
$header .= &quot;Content-Disposition:attachment; &quot;;
$header .= &quot;filename=\&quot;demo.txt\&quot;\r\n\n&quot;;
$header .= &quot;$encoded_Con\r\n&quot;;
$header .= &quot;--$number--&quot;;

$sendMail = mail ($to, $subject, &quot;&quot;, $header);
if($sendMail == true)
{
echo &quot;Your email sent successfully.&quot;;
}
else
{
echo &quot;Email could not be sent.&quot;;
}
?&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>The post <a href="https://jharaphula.com/php-mail-send-email-attachments/">PHP Mail Function to Send Email &amp; Encoded attachments</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/php-mail-send-email-attachments/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/05/send-an-email.jpg" medium="image" />
	</item>
		<item>
		<title>Create, Remove or Read a PHP Cookie using Setcookie method</title>
		<link>https://jharaphula.com/php-setcookie-remove-check-cookie/</link>
					<comments>https://jharaphula.com/php-setcookie-remove-check-cookie/#comments</comments>
		
		<dc:creator><![CDATA[Nibedita Panda]]></dc:creator>
		<pubDate>Sun, 15 May 2016 07:27:58 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[PHP Check Cookie Example]]></category>
		<category><![CDATA[PHP Cookie Examples]]></category>
		<category><![CDATA[PHP Remove Cookies]]></category>
		<category><![CDATA[setcookie]]></category>
		<guid isPermaLink="false">http://box.jharaphula.com/?p=1335</guid>

					<description><![CDATA[<img width="300" height="190" src="https://jharaphula.com/wp-content/uploads/2016/05/php-programming-300x190.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="Create, Remove or Read a PHP Cookie using Setcookie method" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/php-programming-300x190.jpg 300w, https://jharaphula.com/wp-content/uploads/2016/05/php-programming.jpg 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>HTTP is a stateless protocol. During Client Server communication to maintain state we use some techniques. Cookie is one of them. Generally we use Cookies...</p>
<p>The post <a href="https://jharaphula.com/php-setcookie-remove-check-cookie/">Create, Remove or Read a PHP Cookie using Setcookie method</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="190" src="https://jharaphula.com/wp-content/uploads/2016/05/php-programming-300x190.jpg" class="webfeedsFeaturedVisual wp-post-image" alt="Create, Remove or Read a PHP Cookie using Setcookie method" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/php-programming-300x190.jpg 300w, https://jharaphula.com/wp-content/uploads/2016/05/php-programming.jpg 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>HTTP is a stateless protocol. During Client Server communication to maintain state we use some techniques. Cookie is one of them. Generally we use Cookies to identify an user. When first time user send request to the server in response server sends a set of Cookies. Which browser stores in Client machine. Next time when the same user request again browser send the information store in Cookies. Through which server get to identify the user.</p>
<p>Cookie is a text file. It can store maximum upto 4mb data. While creating a Cookie its mandatory to provide Expiry date. Compare to session Cookies is not secured. <a href="https://jharaphula.com/category/programming-solutions/" target="_blank" rel="noopener noreferrer">For programmers</a> it is advisable to not store secured data in Cookies. PHP is a server side programming language. In this session let us share Cookie related operations using PHP.</p>
<h2>What are Cookies?</h2>
<p>Cookies are small pieces of data stored on a user&#8217;s device by a web browser while browsing a website. They are used to remember user preferences, track sessions, and enhance user experience. In PHP, cookies are a fundamental tool for maintaining state between page loads, as HTTP is a stateless protocol.</p>
<p>In PHP to create a Cookie there is a <strong>setcookie()</strong> method. setcookie accepts 6 parameters. The syntax to create Cookie in PHP is as below.</p>
<pre class="brush: php; title: ; notranslate">setcookie(name, value, expire, path, domain, security);</pre>
<h2>PHP setcookie() method parameters</h2>
<table>
<tbody>
<tr>
<td>name</td>
<td>Using this parameter you can set the name of the Cookie. In future if you want to access value of the Cookie name is required. Physically Cookie name stored in an environment variable HTTP_COOKIE_VARS.</td>
</tr>
<tr>
<td>value</td>
<td>Cookie stores data in key value pair. Key is the name where value is the real data.</td>
</tr>
<tr>
<td>expire</td>
<td>While creating a Cookies we need to decide how long the cookie need to reside in Client machine. This can be set using expire property. By default if you will not set expire time cookie will get destroy after browser get close.</td>
</tr>
<tr>
<td>path</td>
<td>Path specifies the physical directories for which the cookie is valid. Using single forward slash permits the cookie to be valid for all directories.</td>
</tr>
<tr>
<td>domain</td>
<td>Using this property you can specify the domain name in very large domains. By default all cookies are only valid for the host &amp; domain which created them.</td>
</tr>
<tr>
<td>security</td>
<td>This parameter accepts 2 values 1 or 0. By passing 1 you can specify that cookie need to travel only by secure transmission (HTTPS). By passing 0 cookie can be travel using regular HTTP.</td>
</tr>
</tbody>
</table>
<h2>PHP Write Cookie Example using Setcookie</h2>
<pre class="brush: php; title: ; notranslate">&lt;?php
setcookie(&quot;empName&quot;, &quot;Baby Roy&quot;, time()+3600, &quot;/&quot;,&quot;&quot;, 0);
setcookie(&quot;empID&quot;, &quot;996782&quot;, time()+3600, &quot;/&quot;, &quot;&quot;,  0);
?&gt;</pre>
<h2>Read a PHP Cookie?</h2>
<p>There are 2 methods to access Cookies in PHP. $_COOKIE &amp; $HTTP_COOKIE_VARS.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
echo $HTTP_COOKIE_VARS[&quot;empName&quot;];
echo $_COOKIE[&quot;empID&quot;];
?&gt;</pre>
<h2>PHP Check Cookie Example</h2>
<p>In PHP there is a method <strong>isset()</strong> using this you can know whether there is a Cookie exists or not. Look at the example below.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
if( isset($_COOKIE[&quot;empName&quot;]))
echo &quot;Welcome &quot; . $_COOKIE[&quot;empName&quot;];
else
echo &quot;No Cookies&quot;;
?&gt;</pre>
<h2>PHP Remove Cookies Example</h2>
<p>To delete a Cookie in PHP you required to set expiry time less than the current time. For an example refer to above we have two cookies empName &amp; empID. To delete these cookies we required to call setcookie() method with expiry time less than the Current time. Look at the example below.</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
setcookie(&quot;empName&quot;, &quot;Baby Roy&quot;, time()-60, &quot;/&quot;,&quot;&quot;, 0);
setcookie(&quot;empID&quot;, &quot;996782&quot;, time()-60, &quot;/&quot;, &quot;&quot;,  0);
?&gt;</pre>
<h2>Common Use Cases for PHP Cookies</h2>
<p>1. Session Management Cookies are often used to maintain user sessions. For example, an e-commerce site might use cookies to keep track of a user’s shopping cart.</p>
<p>2. Personalization Websites use cookies to remember user preferences, such as language settings or theme choices.</p>
<p>3. Tracking and Analytics Cookies help websites gather data on user behavior, enabling improvements in content and marketing strategies.</p>
<h2>Security Considerations</h2>
<p>1. Cross-Site Scripting (XSS) If a cookie is not set with `HttpOnly`, JavaScript can access it, making it vulnerable to XSS attacks.</p>
<p>2. Cross-Site Request Forgery (CSRF) Attackers can manipulate cookies to perform unauthorized actions. Using secure tokens helps mitigate this risk.</p>
<p>3. Data Privacy Compliance Regulations like GDPR require websites to obtain user consent before storing non-essential cookies.</p>
<h2>Best Practices for Using PHP Cookies</h2>
<p>1. Use &#8216;HttpOnly&#8217; and &#8216;Secure&#8217; Flags: Prevent JavaScript access and ensure cookies are transmitted securely.<br />
2. Limit Cookie Lifespan: Avoid setting excessively long expiration times.<br />
3. Encrypt Sensitive Data: Never store passwords or personal information directly in cookies.<br />
4. Validate and Sanitize Input: Prevent malicious data from being stored in cookies.</p>
<h2>Alternatives to PHP Cookies</h2>
<p>1. Sessions PHP sessions store data on the server, making them more secure than cookies. However, they still rely on a session ID stored in a cookie.</p>
<p>2. LocalStorage and SessionStorage JavaScript-based storage options that persist data on the client side but are not sent to the server with every request.</p>
<h2>Conclusion</h2>
<p>PHP cookies are essential for maintaining user state and improving website functionality. By understanding their usage, security implications, and best practices, developers can implement cookies effectively while safeguarding user data. Whether for session management, personalization, or analytics, cookies remain a vital tool in web development when used responsibly.</p>
<p>The post <a href="https://jharaphula.com/php-setcookie-remove-check-cookie/">Create, Remove or Read a PHP Cookie using Setcookie method</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/php-setcookie-remove-check-cookie/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/05/php-programming.jpg" medium="image" />
	</item>
		<item>
		<title>How to Check is Browser Cookie enabled or disabled using PHP?</title>
		<link>https://jharaphula.com/check-is-browser-cookie-enabled-php/</link>
					<comments>https://jharaphula.com/check-is-browser-cookie-enabled-php/#comments</comments>
		
		<dc:creator><![CDATA[Nibedita Panda]]></dc:creator>
		<pubDate>Sat, 14 May 2016 10:07:51 +0000</pubDate>
				<category><![CDATA[Learn PHP with Examples]]></category>
		<category><![CDATA[Browser Cookie enabled]]></category>
		<category><![CDATA[Check is Browser Cookie]]></category>
		<category><![CDATA[create a cookie]]></category>
		<category><![CDATA[setcookie]]></category>
		<guid isPermaLink="false">http://box.jharaphula.com/?p=988</guid>

					<description><![CDATA[<img width="300" height="210" src="https://jharaphula.com/wp-content/uploads/2016/05/HTTP-Cookie-300x210.png" class="webfeedsFeaturedVisual wp-post-image" alt="How to Check is Browser Cookie enabled or disabled using PHP?" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/HTTP-Cookie-300x210.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/HTTP-Cookie.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>As we know HTTP is a stateless protocol. In web during Client Server communication to identify a particular user it is required to maintain state....</p>
<p>The post <a href="https://jharaphula.com/check-is-browser-cookie-enabled-php/">How to Check is Browser Cookie enabled or disabled using PHP?</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></description>
										<content:encoded><![CDATA[<img width="300" height="210" src="https://jharaphula.com/wp-content/uploads/2016/05/HTTP-Cookie-300x210.png" class="webfeedsFeaturedVisual wp-post-image" alt="How to Check is Browser Cookie enabled or disabled using PHP?" style="display: block; margin-bottom: 10px; clear: both; max-width: 100%;" decoding="async" loading="lazy" srcset="https://jharaphula.com/wp-content/uploads/2016/05/HTTP-Cookie-300x210.png 300w, https://jharaphula.com/wp-content/uploads/2016/05/HTTP-Cookie.png 750w" sizes="auto, (max-width: 300px) 100vw, 300px" /><p>As we know HTTP is a stateless protocol. In web during Client Server communication to identify a particular user it is required to maintain state. In this cause there are several state management techniques. State management techniques are available for both the side client &amp; server. Cookie is a client side state management technique.</p>
<p>A Cookie is a simple text file. It can store maximum 4MB data. Due to cookies are resides in client machine in text format storing data in a cookie is not secured. Cookies are two types session cookies &amp; persistent cookies. Session cookies are available for only that time user is interacting. Once the user close the instance of browser session cookies get destroyed. Where persistent cookies having an expiry time. During we create a cookie we have to set the expiry time for persistent cookies. Expiry time can be a day, month or a year too. Cookies are generally used for websites that have huge databases, having signup &amp; login, have customization themes other advanced features.</p>
<p>Before create a cookie using any <a href="https://jharaphula.com/category/programming-solutions/" target="_blank" rel="noopener noreferrer">programming language</a> we need to check first is Cookies enabled in the client browser or not. Programmatically to check this here I wrote a small php script. Which will tell you is in your machine cookies are enabled or disabled.</p>
<p>The logic I implemented in below script is so simple. Using setcookie() method in php I am creating a cookie with the name demo-cookie. Later using php count() function I am counting the number of cookies available in your machine. If it is greater then 0 then my cookie demo-cookie is created successfully. It means in your browser cookies are enabled. In reverse case if count is not grater then 0 then in your browser cookies are disabled. To enable cookies in your browser go to the browser setting.</p>
<p><strong>is-Cookie-enabled.php</strong></p>
<pre class="brush: php; title: ; notranslate">&lt;?php
setcookie(&quot;demo-cookie&quot;, &quot;demo-data&quot;, time() + 3600, '/');
?&gt;
&lt;html&gt;
&lt;body&gt;
&lt;?php
if(count($_COOKIE) &gt; 0) {
echo &quot;Cookies are enabled in your Browser.&quot;;
} else {
echo &quot;Cookies are disabled in your Browser.&quot;;
}
?&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<h2>Creating Cookies in PHP</h2>
<p>PHP provides the `setcookie()` function to create cookies. The basic structure is:</p>
<p>php setcookie(name, value, expire, path, domain, secure, httponly); </p>
<p>name: The cookie&#8217;s identifier. &#8211; value: The data stored in the cookie.<br />
expire: The Unix timestamp when the cookie expires (optional).<br />
path: The directory where the cookie is valid (optional).<br />
domain: The domain where the cookie is accessible (optional).<br />
secure: If `TRUE`, the cookie is sent only over HTTPS (optional).<br />
httponly: If `TRUE`, the cookie is accessible only via HTTP (not JavaScript) for security (optional).</p>
<p>Example:</p>
<p>php setcookie(&#8220;username&#8221;, &#8220;JohnDoe&#8221;, time() + 3600, &#8220;/&#8221;);</p>
<p>This creates a cookie named &#8220;username&#8221; with the value &#8220;JohnDoe&#8221; that expires in one hour (3600 seconds) and is accessible across the entire domain.</p>
<h2>Security Considerations</h2>
<p>Cookies can pose security risks if mishandled:</p>
<p>1. Secure Flag: Always use the `secure` flag for cookies containing sensitive data to ensure they are transmitted only over HTTPS. </p>
<p>2. HttpOnly Flag: Prevents JavaScript access, reducing the risk of cross-site scripting (XSS) attacks. </p>
<p>3. SameSite Attribute: Restricts cookie transmission to same-site requests, mitigating cross-site request forgery (CSRF).</p>
<h2>Common Use Cases</h2>
<p>1. User Authentication: Storing session IDs to keep users logged in. </p>
<p>2. Personalization: Remembering user preferences like themes or language settings. </p>
<p>3. Tracking: Analyzing user behavior for analytics or advertising.</p>
<h2>Alternatives to Cookies</h2>
<p>While cookies are widely used, alternatives include:</p>
<p><strong>LocalStorage</strong>: Stores data persistently in the browser but lacks server-side accessibility.</p>
<p><strong>SessionStorage</strong>: Similar to LocalStorage but cleared when the session ends. &#8211; Server-Side Sessions: Stores data on the server, reducing client-side exposure.</p>
<h2>Conclusion</h2>
<p>PHP cookies are a powerful tool for enhancing user experience by storing and retrieving data across web sessions. By understanding their functionality, security implications, and best practices, developers can implement cookies effectively while safeguarding user privacy. Properly managed cookies contribute to seamless, personalized, and secure web interactions.</p>
<p>The post <a href="https://jharaphula.com/check-is-browser-cookie-enabled-php/">How to Check is Browser Cookie enabled or disabled using PHP?</a> appeared first on <a href="https://jharaphula.com">OneStop Shop</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jharaphula.com/check-is-browser-cookie-enabled-php/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			<media:content url="https://jharaphula.com/wp-content/uploads/2016/05/HTTP-Cookie.png" medium="image" />
	</item>
	</channel>
</rss>
