<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Binary Tides</title>
	<atom:link href="http://www.binarytides.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.binarytides.com/blog</link>
	<description>Socket Programming , Game Programming , PHP , Mysql , Ubuntu etc.</description>
	<lastBuildDate>Sun, 06 May 2012 07:02:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Login into phpmyadmin without username and password</title>
		<link>http://www.binarytides.com/blog/login-into-phpmyadmin-without-username-and-password/</link>
		<comments>http://www.binarytides.com/blog/login-into-phpmyadmin-without-username-and-password/#comments</comments>
		<pubDate>Sun, 06 May 2012 07:01:02 +0000</pubDate>
		<dc:creator>Silver Moon</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[passwordless login phpmyadmin]]></category>
		<category><![CDATA[phpmyadmin autologin]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1895</guid>
		<description><![CDATA[Auto login When working or developing on localhost , its better to make phpmyadmin login automatically without asking for username and password everytime. It is a time wasting thing. Edit config.inc.php To do this the config.inc.php file needs to be edited as follows : 1. Make auth_type = config $cfg['Servers'][$i]['auth_type'] = &#8216;config&#8217;; 2. Add your mysql username and password to the config file : $cfg['Servers'][$i]['auth_type'] = &#8216;config&#8217;; $cfg['Servers'][$i]['username'] = &#8216;root&#8217;; $cfg['Servers'][$i]['password'] = &#8216;your_password&#8217;; 3. Save [...]]]></description>
			<content:encoded><![CDATA[<div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/login-into-phpmyadmin-without-username-and-password/';
var dzone_title = 'Login into phpmyadmin without username and password';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div><h3>Auto login</h3>
<p>When working or developing on localhost , its better to make phpmyadmin login automatically without asking for username and password everytime. It is a time wasting thing.</p>
<h3>Edit config.inc.php</h3>
<p>To do this the config.inc.php file needs to be edited as follows :</p>
<p>1. Make auth_type = config</p>
<div class="highlight">
$cfg['Servers'][$i]['auth_type'] = &#8216;config&#8217;;
</div>
<p>2. Add your mysql username and password to the config file :</p>
<div class="highlight">
$cfg['Servers'][$i]['auth_type'] = &#8216;config&#8217;;<br />
$cfg['Servers'][$i]['username'] = &#8216;root&#8217;;<br />
$cfg['Servers'][$i]['password'] = &#8216;your_password&#8217;;
</div>
<p>3. Save the configuration file , clear browser cache and then reopen phpmyadmin in your browser. Make sure you clear the browser cache , otherwise the login page may still come back.</p>
<p>If the &#8216;config.inc.php&#8217; file is not found then look for &#8216;config.sample.inc.php&#8217;. Make a copy of it and name it as &#8216;config.inc.php&#8217; , then edit the file.</p>
<h3>Resources</h3>
<p>1. <a target="_blank" href="http://wiki.phpmyadmin.net/pma/auth_types" >http://wiki.phpmyadmin.net/pma/auth_types</a></p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1895&type=feed" alt="" /><div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/login-into-phpmyadmin-without-username-and-password/';
var dzone_title = 'Login into phpmyadmin without username and password';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/login-into-phpmyadmin-without-username-and-password/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>10+ tips to localise your php application</title>
		<link>http://www.binarytides.com/blog/10-tips-to-localise-your-php-application/</link>
		<comments>http://www.binarytides.com/blog/10-tips-to-localise-your-php-application/#comments</comments>
		<pubDate>Sat, 14 Apr 2012 06:03:37 +0000</pubDate>
		<dc:creator>Silver Moon</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[localise php application]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[php localisation techniques]]></category>
		<category><![CDATA[php localise]]></category>
		<category><![CDATA[php techniques]]></category>
		<category><![CDATA[php tips]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1766</guid>
		<description><![CDATA[The tips Localisation involves changing various parts of application output like display of dates , time , numbers , language etc according to the standards of the geographical region of a user. Localisation is an important feature of applications that targets users across the globe and not just one region. So here are a set of simple tips and techniques every php application can do to make itself more locale-friendly. 1. Set timezone of the [...]]]></description>
			<content:encoded><![CDATA[<div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/10-tips-to-localise-your-php-application/';
var dzone_title = '10+ tips to localise your php application';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div><h2>The tips</h2>
<p><b>Localisation</b> involves changing various parts of application output like display of dates , time , numbers , language etc according to the standards of the geographical region of a user. Localisation is an important feature of applications that targets users across the globe and not just one region.</p>
<p>So here are a set of simple tips and techniques every php application can do to make itself more locale-friendly.</p>
<h3>1. Set timezone of the application</h3>
<p>The application should explicitly set a timezone for itself. Otherwise the timezone of the machine/server would be taken up, which may not be what the user wants.</p>
<pre class="brush: php; title: Code; notranslate">
date_default_timezone_set( 'America/Chicago' );
</pre>
<p>This should be done at the earliest in the script.</p>
<p>The <code>timezone_identifiers_list()</code> function can be used to generate a list of timezones from which the user can select. Here is a quick example :</p>
<pre class="brush: php; title: Code; notranslate">
/**
	@brief
	Get a list of timezones available for use in the application
*/
function get_timezones()
{
	$o = array();
	$t = timezone_identifiers_list();

	foreach($t as $a)
	{
		$t = '';

		//Get the time difference
		$zone = new DateTimeZone($a);
		$seconds = $zone-&gt;getOffset( new DateTime(&quot;now&quot;, $zone) );
		$hours = sprintf( &quot;%+02d&quot; , intval($seconds/3600));
		$minutes = sprintf( &quot;%02d&quot; , ($seconds%3600)/60 );

		$t = $a .&quot;  [ $hours:$minutes ]&quot; ;
		$o[$a] = $t;
	}
	ksort($o);

	return $o;
}
</pre>
<p>This would give you a complete list like this :</p>
<div class="highlight">
[Africa/Abidjan] => Africa/Abidjan  [ +0:00 ]<br />
[Africa/Accra] => Africa/Accra  [ +0:00 ]<br />
[Africa/Addis_Ababa] => Africa/Addis_Ababa  [ +3:00 ]<br />
[Africa/Algiers] => Africa/Algiers  [ +1:00 ]<br />
[Africa/Asmara] => Africa/Asmara  [ +3:00 ]<br />
[Africa/Bamako] => Africa/Bamako  [ +0:00 ]<br />
[Africa/Bangui] => Africa/Bangui  [ +1:00 ]<br />
[Africa/Banjul] => Africa/Banjul  [ +0:00 ]<br />
[Africa/Bissau] => Africa/Bissau  [ +0:00 ]
</div>
<p>Make a select tag dropdown out of it and let the user select his/her timezone.</p>
<h3>2. Set the mysql timezone from the application</h3>
<p>Applications are often hosted on servers that are in a different timezone , compared to that of the developer or the application user. Hence the timezone of mysql needs to be set properly to that of the application.</p>
<p>Mysql can be put in the same timezone as the application by doing :</p>
<pre class="brush: php; title: Code; notranslate">
$c = mysqli_connect($host, $username, $password);
mysqli_query($c , &quot;SET `time_zone` = '&quot;.date('P').&quot;'&quot;);
</pre>
<p>The php date function with P parameter gives the time difference between GMT and the applications timezone. The same is passed to mysql.</p>
<p><b>TIMESTAMP</b></p>
<p>For timestamp columns in mysql , any date-time combinations passed would be converted to correct timestamp by mysql , since mysql itself is in the correct timezone.</p>
<p><b>DATETIME</b></p>
<p>When using datetime columns , the application must convert the date-time values to UTC , and then save in mysql.<br />
When fetching back from database they must be converted to the application&#8217;s timezone.</p>
<p>Save to database :</p>
<pre class="brush: php; title: Code; notranslate">
$time_to_save = date('Y-m-d h:i:s');	//Current time of user that is to be saved in a datetime mysql column

$d = new DateTime($time_to_save , new DateTimeZone(date_default_timezone_get()) );

$d-&gt;setTimezone( new DateTimeZone('UTC') );	//Move to UTC

$mysql_datetime = $d-&gt;format(&quot;Y-m-d h:i:s&quot;);	//BUZZ!! Ready to save datetime value in database
</pre>
<p><b>Note : </b></p>
<p>1. Since the mysql timezone is being set from within the application , certain queries may give tricky output. Here is an example :</p>
<p>You are developing an application on your local system and have set the timezone to &#8216;Asia/Singapore&#8217; , but your own computer&#8217;s timezone is &#8216;Asia/Kolkata&#8217;</p>
<p>Now inside your application you are running a certain query :</p>
<pre class="brush: php; title: Code; notranslate">
$time_schedule = &quot;2012-04-13 10:30:00&quot;
$query = &quot;SELECT * FROM table WHERE time_schedule = '$time_schedule'&quot;;
//Execute the query

//some rows
</pre>
<p>When you run the same query in phpmyadmin or mysql terminal and you might get different output/rows selected.</p>
<p>This happens because timezone of application+mysql is different from mysql outside. You application sees different time in the database column time_schedule and phpmyadmin/mysql terminal sees a different time.</p>
<h3>3. Set collation for database at the time of creation</h3>
<p>The collation of the database should be set to the correct one , right in the beginning.</p>
<div class="highlight">
ALTER DATABASE db_name CHARACTER SET utf8 COLLATE utf8_unicode_ci;
</div>
<p>Or modify it from the Operations tab in phpmyadmin. Setting the collation and character set in the beginning ensures that all later tables, columns take up the same by default.</p>
<h3>4. Set character set of mysql connection object</h3>
<p>When the application is displaying non english charaters , then it must set the mysql connection&#8217;s character encoding. Its simple :</p>
<pre class="brush: php; title: Code; notranslate">
mysqli_set_charset ( $c , 'UTF8' );
</pre>
<h3>5. Set correct character set for htmlentities</h3>
<p>Function htmlentities is used to echo content , that was previously provided by the user.<br />
Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display languages like hindi , bengali , russian etc.</p>
<pre class="brush: php; title: Code; notranslate">
$value = htmlentities($value , ENT_QUOTES , 'UTF-8');
echo $value;
</pre>
<p>Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.</p>
<p>The function mb_list_encodings can be used to generate a list.</p>
<pre class="brush: php; title: Code; notranslate">
/**
	@brief
	Get the list of supported encodings using the mb_list_encodings function
*/
function get_supported_encodings()
{
	$e = mb_list_encodings();

	$list = array();

	foreach($e as $c =&gt; $val)
	{
		$list[$val] = $val;
	}

	return $list;
}
</pre>
<p>Would generate a list like this :</p>
<div class="highlight">
[UTF-32BE] => UTF-32BE<br />
[UTF-32LE] => UTF-32LE<br />
[UTF-16] => UTF-16<br />
[UTF-16BE] => UTF-16BE<br />
[UTF-16LE] => UTF-16LE<br />
[UTF-8] => UTF-8<br />
[UTF-7] => UTF-7<br />
[UTF7-IMAP] => UTF7-IMAP<br />
[ASCII] => ASCII<br />
[EUC-JP] => EUC-JP<br />
[SJIS] => SJIS
</div>
<p>Select one and save in the database.</p>
<h3>6. Set encoding for non html content by sending the correct headers</h3>
<p>When echoing content like css , javascript , xml etc. set the correct encoding via the header function like this :</p>
<p><b>XML</b></p>
<div class="highlight">
header(&#8216;Content-Type: text/xml; charset=utf-8&#8242;);<br />
//Echo rest of the xml content
</div>
<p><b>Javascript</b></p>
<div class="highlight">
header(&#8216;Content-Type: text/javascript; charset=utf-8&#8242;);<br />
//Echo rest of the javascript content
</div>
<h3>7. Set correct character set for html and xml output</h3>
<p>HTML : This goes in the head tag of an html document</p>
<pre class="brush: xml; title: Code; notranslate">
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot;&gt;
</pre>
<p>html5 supports :</p>
<pre class="brush: xml; title: Code; notranslate">
&lt;meta charset=&quot;utf-8&quot;&gt;
</pre>
<p>XML : The first line of an xml document has the encoding specified</p>
<pre class="brush: xml; title: Code; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
</pre>
<h3>8. Set correct locale</h3>
<p>Locale settings provide useful locale related settings like how to format numbers , currency symbol etc. The correct locale for the application should be setup as early as possible in the script.</p>
<pre class="brush: php; title: Code; notranslate">
setlocale(LC_ALL, 'en_US.UTF-8');
</pre>
<p>Provide the user with a list of locales to select from. Check <a href="http://www.binarytides.com/blog/php-get-list-of-locales-installed-on-system/" >here</a> to learn how to do that.</p>
<h3>9. Format numbers according to locale</h3>
<p>When displaying numbers like plain number or currency numbers , format them with comma , decimal etc properly using function money_format. Here is a quick example :</p>
<pre class="brush: php; title: Code; notranslate">

$amount = '100000';

//Format numbers in Indian format - Lakh , Crore
setlocale(LC_MONETARY, 'en_IN');
$am = money_format('%!i', $amount);
echo $am;    //1,00,000.00

//Format in million , billion
echo &quot;&lt;br /&gt;&quot;;
setlocale(LC_MONETARY, 'en_US.utf8');
$am = money_format('%!i', $amount);
echo $am;    //100,000.00
</pre>
<h3>10. Format display of dates</h3>
<p>Format dates properly according to what the user expects to see.</p>
<div class="highlight">
ISO Format : 2012-04-13 (YYYY-MM-DD)<br />
Asian countries : 13-04-2012 (DD-MM-YYYY)<br />
USA : 04-13-2012 (MM-DD-YYYY)
</div>
<p>Dates have to be formatted both when displaying and when being entered in a form.</p>
<div class="highlight">
Form entry : 13/04/2012 or 04/13/2012<br />
Display : 13 Apr 2012 or Apr 13, 2012
</div>
<p>Formatting date with <b>strftime</b> :</p>
<pre class="brush: php; title: Code; notranslate">
$format = '%d-%b-%Y';
$stamp = time();
$display_format = strftime( $format , $stamp);

echo $display_format; 	//Output 14-04-2012
</pre>
<p>Formatting with <b>DateTime</b> object :</p>
<pre class="brush: php; title: Code; notranslate">
$t = date('Y-m-d h:i:s');
$d = new DateTime($t , new DateTimeZone(date_default_timezone_get()) );
$display_format = $d-&gt;format(&quot;d-m-Y&quot;);
echo $display_format;    //15-04-2012
</pre>
<p>User should be have the option to select formats for displaying date and entering dates in forms. The user selected format , for example d-m-Y can be saved in database and reloaded next time.</p>
<h3>11. Make the application multilingual</h3>
<p>Finally change the language of the application to what the user wants. There are many ways to make your application multilingual. One way is to collect all label text in your application and fetch the translations from google translate service. Find out more on google.</p>
<h2>Conclusion</h2>
<p>Applications should be localised properly for better user experience. Applications should allow the user to select the localisation settings like timezone , locale , language , date display format etc.</p>
<div class="updated_on">Updated on 16-Apr-2012</div>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1766&type=feed" alt="" /><div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/10-tips-to-localise-your-php-application/';
var dzone_title = '10+ tips to localise your php application';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/10-tips-to-localise-your-php-application/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>40+ Techniques to enhance your php code &#8211; Part 3</title>
		<link>http://www.binarytides.com/blog/40-techniques-to-enhance-your-php-code-part-3/</link>
		<comments>http://www.binarytides.com/blog/40-techniques-to-enhance-your-php-code-part-3/#comments</comments>
		<pubDate>Sat, 07 Apr 2012 09:19:30 +0000</pubDate>
		<dc:creator>Silver Moon</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[amazing php techniques]]></category>
		<category><![CDATA[amazing php tips]]></category>
		<category><![CDATA[enhance php code]]></category>
		<category><![CDATA[improve php code]]></category>
		<category><![CDATA[master php code]]></category>
		<category><![CDATA[masters php techniques]]></category>
		<category><![CDATA[optimize php code]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[php advanced techniques]]></category>
		<category><![CDATA[php best practices]]></category>
		<category><![CDATA[php techniques]]></category>
		<category><![CDATA[php tips]]></category>
		<category><![CDATA[php tips and tricks]]></category>
		<category><![CDATA[php tutorial]]></category>
		<category><![CDATA[useful php techniques]]></category>
		<category><![CDATA[write efficient php code]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1693</guid>
		<description><![CDATA[Part 2 26. Avoid direct SQL query , abstract it Writing too many queries like this : Not a robust approach. It has drawbacks : escape the values everytime manually Verify if the query is correct Wrong queries may go undetected for a long time (unless if else checking done everytime) Difficult to maintain large queries like that Therefore write up for yourself simple functions like these : Saw that ? it makes things simpler [...]]]></description>
			<content:encoded><![CDATA[<div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/40-techniques-to-enhance-your-php-code-part-3/';
var dzone_title = '40+ Techniques to enhance your php code &#8211; Part 3';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div><p><a href="http://www.binarytides.com/blog/40-techniques-to-enhance-your-php-code-part-2/" >Part 2</a></p>
<h3>26. Avoid direct SQL query , abstract it</h3>
<p>Writing too many queries like this :</p>
<pre class="brush: php; title: Code; notranslate">
$query = &quot;INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')&quot;;
$db-&gt;query($query); //call to mysqli_query()
</pre>
<p>Not a robust approach. It has drawbacks :</p>
<ul>
<li>escape the values everytime manually</li>
<li>Verify if the query is correct</li>
<li>Wrong queries may go undetected for a long time (unless if else checking done everytime)</li>
<li>Difficult to maintain large queries like that</li>
</ul>
<p>Therefore write up for yourself simple functions like these :</p>
<pre class="brush: php; title: Code; notranslate">

function insert_record($table_name , $data)
{
    foreach($data as $key =&gt; $value)
    {
	//mysqli_real_escape_string
        $data[$key] = $db-&gt;mres($value);
    }

    $fields = implode(',' , array_keys($data));
    $values = &quot;'&quot; . implode(&quot;','&quot; , array_values($data)) . &quot;'&quot;;

    //Final query
    $query = &quot;INSERT INTO {$table}($fields) VALUES($values)&quot;;

    return $db-&gt;query($query);
}

$data = array('name' =&gt; $name , 'email' =&gt; $email  , 'address' =&gt; $address , 'phone' =&gt; $phone);

insert_record('users' , $data);
</pre>
<p>Saw that ? it makes things simpler and scalable. The function insert_record takes care of escaping data correctly.<br />
Biggest advantage here is that since the data is being prepared as a php array , any syntax mistake is caught instantly.</p>
<p>This function should be a part of your database class , which you can call like this $db->insert_record.<br />
Check this article on how to make your own database class for easy database handling.</p>
<p>Similar functions should be written for update , select , delete as well. Try doing it.</p>
<h3>27. Cache database generated content to static files</h3>
<p>For all pages that are generated by fetching content from the database , they should be cached. It means that once generated , save a copy in a temporary directory. Next time the same page is requested , then fetch it from the cache directory , dont query the database again.</p>
<p>Benefits :</p>
<ul>
<li>Save php processing to generate the page , hence faster execution</li>
<li>Lesser database queries means lesser load on mysql database</li>
</ul>
<h3>28. Store sessions in database</h3>
<p>File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers , since files are stoed on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting , the session files reside in the tmp directory , which is readable by other accounts. This can be a security issue.</p>
<p>Storing session in database makes many other things easier like :</p>
<ul>
<li>Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time.
</li>
<li>Check online status of users more accurately.</li>
</ul>
<h3>29. Avoid using globals</h3>
<ul>
<li>Use defines/constants</li>
<li>Get value using a function</li>
<li>Use Class and access via $this</li>
</ul>
<h3>30. Use base url in head tag</h3>
<p>Heard of this ? It looks like this :</p>
<pre class="brush: xml; title: Code; notranslate">
&lt;head&gt;
&lt;base href=&quot;http://www.domain.com/store/&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;img src=&quot;happy.jpg&quot; /&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>This base tag is a very useful thing. Suppose you are organising your webpages in sub directories , but all of them need to contain a consistent navigation menu.</p>
<p>www.domain.com/store/home.php<br />
www.domain.com/store/products/ipad.php</p>
<p>In your home.php you can write</p>
<pre class="brush: xml; title: Code; notranslate">
&lt;a href=&quot;home.php&quot;&gt;Home&lt;/a&gt;
&lt;a href=&quot;products/ipad.php&quot;&gt;Ipad&lt;/a&gt;
</pre>
<p>But in your ipad.php you have to write</p>
<pre class="brush: xml; title: Code; notranslate">
&lt;a href=&quot;../home.php&quot;&gt;Home&lt;/a&gt;
&lt;a href=&quot;ipad.php&quot;&gt;Ipad&lt;/a&gt;
</pre>
<p>Because directories are different. For this multiple versions of the navigation html code has to be maintained , which is a bad idea. So use base tag</p>
<pre class="brush: xml; title: Code; notranslate">
&lt;head&gt;
&lt;base href=&quot;http://www.domain.com/store/&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;a href=&quot;home.php&quot;&gt;Home&lt;/a&gt;
&lt;a href=&quot;products/ipad.php&quot;&gt;Ipad&lt;/a&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php </p>
<p>Thats it.</p>
<h3>31. Manage error reporting</h3>
<p>Just switch off the not so relevant errors. E_FATAL errors are important to know. </p>
<p>During development this is can be done :</p>
<pre class="brush: php; title: Code; notranslate">
ini_set('display_errors', 1);
error_reporting(~E_WARNING &amp; ~E_NOTICE &amp; ~E_STRICT); //or E_ALL ?? that will report too much ...
</pre>
<p>On production , the display should be disabled.</p>
<pre class="brush: php; title: Code; notranslate">
ini_set('display_errors', 0);
error_reporting(~E_WARNING &amp; ~E_NOTICE &amp; ~E_STRICT);
</pre>
<p>Its a good idea to log all errors to a file for later analysis. This can be done inside the script using init_set.</p>
<pre class="brush: php; title: Code; notranslate">
ini_set('log_errors' , '1');
ini_set('error_log' , '/path/to/errors.txt');

ini_set('display_errors' , 0);
error_reporting(~E_WARNING &amp; ~E_NOTICE &amp; ~E_STRICT);
</pre>
<p><b>Note :</b></p>
<p>1. The path &#8216;/path/to/errors.txt&#8217; should be writable by the web server for errors to be logged there.</p>
<p>2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. </p>
<p>3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).</p>
<p>4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched.</p>
<p>5. Dont set error_reporting to 0. It will not log anything then.</p>
<p><b>Set &#8216;display_errors=On&#8217; in php.ini on development machine</b></p>
<p>On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set)<br />
This is because any compile time fatal errors will now allow ini_set to execute , hence no error display</p>
<p>Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.</p>
<p><b>Set &#8216;display_errors=Off&#8217; in php.ini on production machine</b></p>
<p>Do not rely on init_set(&#8216;display_errors&#8217; , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.</p>
<h3>32. Be aware of platform architecture</h3>
<p>The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.</p>
<p>On a 64 bit machine you can see such output.</p>
<pre class="brush: php; title: Code; notranslate">
$ php -a
Interactive shell

php &gt; echo strtotime(&quot;0000-00-00 00:00:00&quot;);
-62170005200
php &gt; echo strtotime('1000-01-30');
-30607739600
php &gt; echo strtotime('2100-01-30');
4104930600
</pre>
<p>But on a 32 bit machine all of them would give bool(false). Check <a href="http://www.binarytides.com/blog/php-strtotime-in-64-bit-environment/" >here</a> for more.</p>
<p>What would happen if an integer is left shifted more than 32 bits &#8230; the result would be different on different machines.</p>
<h3>33. Dont rely on set_time_limit too much</h3>
<p>If you are limiting the maximum run-time of a script , by doing this :</p>
<pre class="brush: php; title: Code; notranslate">
set_time_limit(30);

//Rest of the code
</pre>
<p>it may not always work. Any execution that happens outside the script via system calls/os functions like socket operations , database operations etc. will not be under control of set_time_limit.</p>
<p>So if a database operation takes lot of time or &#8220;hangs&#8221; then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.</p>
<h3>34. Make a portable function for executing shell commands</h3>
<p>system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. </p>
<p>A better solution :</p>
<pre class="brush: php; title: Code; notranslate">
/**
	Method to execute a command in the terminal
	Uses :

	1. system
	2. passthru
	3. exec
	4. shell_exec

*/
function terminal($command)
{
	//system
	if(function_exists('system'))
	{
		ob_start();
		system($command , $return_var);
		$output = ob_get_contents();
		ob_end_clean();
	}
	//passthru
	else if(function_exists('passthru'))
	{
		ob_start();
		passthru($command , $return_var);
		$output = ob_get_contents();
		ob_end_clean();
	}

	//exec
	else if(function_exists('exec'))
	{
		exec($command , $output , $return_var);
		$output = implode(&quot;\n&quot; , $output);
	}

	//shell_exec
	else if(function_exists('shell_exec'))
	{
		$output = shell_exec($command) ;
	}

	else
	{
		$output = 'Command execution not possible on this system';
		$return_var = 1;
	}

	return array('output' =&gt; $output , 'status' =&gt; $return_var);
}

terminal('ls');
</pre>
<p>The above function will execute the shell command using whichever function is available , keeping your code consistent.</p>
<h3>35. Localize your application</h3>
<p>Format dates and numbers properly. Show the time according to timezone of the user.<br />
Check <a href="http://www.binarytides.com/blog/10-tips-to-localise-your-php-application/" target="_blank" >here</a> to learn more.</p>
<h3>36. Use a profiler like xdebug if you need to</h3>
<p>If you are writing large scale applications in php that do a lot of processing , then speed is an important factor. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrid.</p>
<h3>37. Use plenty of external libraries</h3>
<p>Here are few :</p>
<ul>
<li>mPDF &#8211; Generate pdf documents, by converting html to pdf beautifully.</li>
<li>PHPExcel &#8211; Read and write Excel files</li>
<li>PhpMailer &#8211; Send html emails with attachments easily</li>
<li>pChart &#8211; Generate graphs in php</li>
</ul>
<p>Use open source libraries for complex tasks like generating pdf , ms-excel files , charts etc.</p>
<h3>38. Have a look at phpbench for some micro-optimisation stats</h3>
<p>If you really want to achieve optimisation at the level of microtime then check <a target="_blank" href="http://www.phpbench.com/" >phpbench</a> &#8230; it has some benchmarks for various syntax variations that can create significant difference.</p>
<h3>39. Use an MVC framework</h3>
<p>Its time to start using an MVC framework like codeigniter. MVC framework dont really make you write object oriented code. They just make you separate PHP code from HTML code.</p>
<ul>
<li>Clean separation of php and html code. Good for team work , when designers and coders are working together.</li>
<li>Functions and functionalities are organised in classes making maintenance easy.</li>
<li>Inbuilt libraries for lots of things , you may not need to code again</li>
<li>Is a must when writing big applications</li>
<li>Lots of tips, techniques, hacks are already implemented in the framework</li>
</ul>
<h3>40. Read the comments on the php documentation website</h3>
<p>They contain user feedback , expert advice and useful code snippets. Check them out.</p>
<h3>41. Go to the IRC channel to ask</h3>
<p>Have a question , got stuck somewhere in your code ?<br />
Go to the irc channel #php and ask. Its the best place to get answers and instantly.</p>
<h3>42. Read open source code</h3>
<p>Read other open source applications. You get to learn a lot about techniques , coding style , commenting style etc. Here are a few to begin with (all on github) :</p>
<p>1. <a target="_blank" href="https://github.com/EllisLab/CodeIgniter" >Codeigniter</a><br />
2. <a target="_blank" href="https://github.com/WordPress/WordPress" >WordPress</a><br />
3. <a target="_blank" href="https://github.com/joomla/joomla-cms" >Joomla CMS</a></p>
<h3>43. Develop on Linux</h3>
<p>Do php development on a Linux (or may be Mac ?) machine. This will help in many ways like :</p>
<ul>
<li>Php applications are installed on servers which are mostly linux. So by developing on a Linux machine you get a change to work in an environment which is similar to the deployment environment.</li>
<li>Linux is the OS for developers. It has plenty of developer tools and all are free.</li>
</ul>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1693&type=feed" alt="" /><div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/40-techniques-to-enhance-your-php-code-part-3/';
var dzone_title = '40+ Techniques to enhance your php code &#8211; Part 3';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/40-techniques-to-enhance-your-php-code-part-3/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>40+ Techniques to enhance your php code &#8211; Part 2</title>
		<link>http://www.binarytides.com/blog/40-techniques-to-enhance-your-php-code-part-2/</link>
		<comments>http://www.binarytides.com/blog/40-techniques-to-enhance-your-php-code-part-2/#comments</comments>
		<pubDate>Sat, 07 Apr 2012 09:13:44 +0000</pubDate>
		<dc:creator>Silver Moon</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[amazing php techniques]]></category>
		<category><![CDATA[amazing php tips]]></category>
		<category><![CDATA[enhance php code]]></category>
		<category><![CDATA[improve php code]]></category>
		<category><![CDATA[master php code]]></category>
		<category><![CDATA[masters php techniques]]></category>
		<category><![CDATA[optimize php code]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[php advanced techniques]]></category>
		<category><![CDATA[php best practices]]></category>
		<category><![CDATA[php techniques]]></category>
		<category><![CDATA[php tips]]></category>
		<category><![CDATA[php tips and tricks]]></category>
		<category><![CDATA[php tutorial]]></category>
		<category><![CDATA[useful php techniques]]></category>
		<category><![CDATA[write efficient php code]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1686</guid>
		<description><![CDATA[Part 1 11. Do not gzip output in your application , make apache do that Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the .htaccess file. 12. Use json_encode when echoing javascript code from php There are times when some javascript code [...]]]></description>
			<content:encoded><![CDATA[<div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/40-techniques-to-enhance-your-php-code-part-2/';
var dzone_title = '40+ Techniques to enhance your php code &#8211; Part 2';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div><p><a href="http://www.binarytides.com/blog/35-techniques-to-enhance-your-php-code/" >Part 1</a></p>
<h3>11. Do not gzip output in your application , make apache do that</h3>
<p>Thinking of using <code>ob_gzhandler</code> ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.</p>
<p>Use apache mod_gzip/mod_deflate to compress content via the .htaccess file.</p>
<h3>12. Use json_encode when echoing javascript code from php</h3>
<p>There are times when some javascript code is generated dynamically from php.</p>
<pre class="brush: php; title: Code; notranslate">

$images = array(
 'myself.png' , 'friends.png' , 'colleagues.png'
);

$js_code = '';

foreach($images as $image)
{
$js_code .= &quot;'$image' ,&quot;;
}

$js_code = 'var images = [' . $js_code . ']; ';

echo $js_code;

//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];
</pre>
<p>Be smart. use json_encode :</p>
<pre class="brush: php; title: Code; notranslate">

$images = array(
 'myself.png' , 'friends.png' , 'colleagues.png'
);

$js_code = 'var images = ' . json_encode($images);

echo $js_code;

//Output is : var images = [&quot;myself.png&quot;,&quot;friends.png&quot;,&quot;colleagues.png&quot;]
</pre>
<p>Isn&#8217;t that neat ?</p>
<h3>13. Check if directory is writable before writing any files</h3>
<p>Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of &#8220;debugging&#8221; time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.</p>
<p>Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.</p>
<pre class="brush: php; title: Code; notranslate">

$contents = &quot;All the content&quot;;
$file_path = &quot;/var/www/project/content.txt&quot;;

file_put_contents($file_path , $contents);
</pre>
<p>That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :</p>
<ul>
<li>Parent directory does not exist</li>
<li>Directory exists , but is not writable</li>
<li>File locked for writing ?</li>
</ul>
<p>So its better to make everything clear before writing out to a file.</p>
<pre class="brush: php; title: Code; notranslate">
$contents = &quot;All the content&quot;;
$dir = '/var/www/project';
$file_path = $dir . &quot;/content.txt&quot;;

if(is_writable($dir))
{
    file_put_contents($file_path , $contents);
}
else
{
    die(&quot;Directory $dir is not writable, or does not exist. Please check&quot;);
}
</pre>
<p>By doing this you get the accurate information that where is a file write failing and why</p>
<h3>14. Change permission of files that your application creates</h3>
<p>When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are &#8220;accessible&#8221; outside. Otherwise for example the files may be created by &#8220;php&#8221; user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.</p>
<pre class="brush: php; title: Code; notranslate">
// Read and write for owner, read for everybody else
chmod(&quot;/somedir/somefile&quot;, 0644);

// Everything for owner, read and execute for others
chmod(&quot;/somedir/somefile&quot;, 0755);
</pre>
<h3>15. Don&#8217;t check submit button value to check form submission</h3>
<pre class="brush: php; title: Code; notranslate">
if($_POST['submit'] == 'Save')
{
    //Save the things
}
</pre>
<p>The above is mostly correct , except when your application is multi-lingual. Then the &#8216;Save&#8217; can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :</p>
<pre class="brush: php; title: Code; notranslate">
if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) )
{
    //Save the things
}
</pre>
<p>Now you are free from the value the submit button</p>
<h3>16. Use static variables in function where they always have same value</h3>
<pre class="brush: php; title: Code; notranslate">

//Delay for some time
function delay()
{
    $sync_delay = get_option('sync_delay');

    echo &quot;&lt;br /&gt;Delaying for $sync_delay seconds...&quot;;
    sleep($sync_delay);
    echo &quot;Done &lt;br /&gt;&quot;;
}
</pre>
<p>Instead use static variables as :</p>
<pre class="brush: php; title: Code; notranslate">

//Delay for some time
function delay()
{
    static $sync_delay = null;

    if($sync_delay == null)
    {
	$sync_delay = get_option('sync_delay');
    }

    echo &quot;&lt;br /&gt;Delaying for $sync_delay seconds...&quot;;
    sleep($sync_delay);
    echo &quot;Done &lt;br /&gt;&quot;;
}
</pre>
<h3>17. Don&#8217;t use the $_SESSION variable directly</h3>
<p>Some simple examples are  :</p>
<pre class="brush: php; title: Code; notranslate">
$_SESSION['username'] = $username;
$username = $_SESSION['username'];
</pre>
<p>But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.</p>
<p>Hence use application specific keys with wrapper functions :</p>
<pre class="brush: php; title: Code; notranslate">
define('APP_ID' , 'abc_corp_ecommerce');

//Function to get a session variable
function session_get($key)
{
    $k = APP_ID . '.' . $key;

    if(isset($_SESSION[$k]))
    {
        return $_SESSION[$k];
    }

    return false;
}

//Function set the session variable
function session_set($key , $value)
{
    $k = APP_ID . '.' . $key;
    $_SESSION[$k] = $value;

    return true;
}
</pre>
<h3>18. Wrap utility helper functions into a class</h3>
<p>So you have a lot of utility functions in a file like :</p>
<pre class="brush: php; title: Code; notranslate">
function utility_a()
{
    //This function does a utility thing like string processing
}

function utility_b()
{
    //This function does nother utility thing like database processing
}

function utility_c()
{
    //This function is ...
}
</pre>
<p>And you use the function throughout your application freely. You may want to wrap them into a class as static functions :</p>
<pre class="brush: php; title: Code; notranslate">

class Utility
{
    public static function utility_a()
    {

    }

    public static function utility_b()
    {

    }

    public static function utility_c()
    {

    }
}

//and call them as 

$a = Utility::utility_a();
$b = Utility::utility_b();
</pre>
<p>One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict.<br />
Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.</p>
<h3>19. Bunch of silly tips</h3>
<ul>
<li>Use echo instead of print</li>
<li>Use str_replace instead of preg_replace , unless you need it absolutely</li>
<li>Do not use short tags</li>
<li>Use single quotes instead of double quotes for simple strings</li>
<li>Always remember to do an exit after a header redirect</li>
<li>Never put a function call in a for loop control line.</li>
<li>isset is faster than strlen</li>
<li>Format your code correctly and consistently</li>
<li>
Do not drop the brackets of loops or if-else blocks.<br />
Do not code like this :</p>
<pre class="brush: php; title: Code; notranslate">
if($a == true) $a_count++;
</pre>
<p>Its absolutely a WASTE.</p>
<p>Write</p>
<pre class="brush: php; title: Code; notranslate">
if($a == true)
{
    $a_count++;
}
</pre>
<p>Dont try to make your code shorter by eating up syntax. <b>Rather make your logic shorter.</b>
</li>
<li>Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors.</li>
</ul>
<h3>20. Process arrays quickly with array_map</h3>
<p>Lets say you want to trim all elements of an array. Newbies do it like this :</p>
<pre class="brush: php; title: Code; notranslate">
foreach($arr as $c =&gt; $v)
{
	$arr[$c] = trim($v);
}
</pre>
<p>But it can more cleaner with array_map :</p>
<pre class="brush: php; title: Code; notranslate">
$arr = array_map('trim' , $arr);
</pre>
<p>This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the<br />
documentation on these to know more.</p>
<h3>21. Validate data with php filters</h3>
<p>Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets<br />
try something different, called filters.</p>
<p>The php filter extension provides simple way to validate or check values as being a valid &#8216;something&#8217;.</p>
<h3>22. Force type checking</h3>
<pre class="brush: php; title: Code; notranslate">

$amount = intval( $_GET['amount'] );
$rate = (int) $_GET['rate'];
</pre>
<p>Its a good habit.</p>
<h3>23. Write Php errors to file using set_error_handler()</h3>
<p>set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose</p>
<h3>24. Handle large arrays carefully</h3>
<p>Large arrays  or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :</p>
<pre class="brush: php; title: Code; notranslate">

$db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB

$cc = $db_records_in_array_format; //2MB more

some_function($cc); //Another 2MB ?
</pre>
<p>The above thing is common when importing a csv file or exporting table to a csv file</p>
<p>Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.</p>
<p>Consider passing them by reference , or storing them in a class variable :</p>
<pre class="brush: php; title: Code; notranslate">
$a = get_large_array();
pass_to_function(&amp;$a);
</pre>
<p>by doing this the same variable (and not its copy) will be available to the function. Check <a target="_blank" href="http://php.net/manual/en/language.references.pass.php" >documentation</a></p>
<pre class="brush: php; title: Code; notranslate">
class A
{
    function first()
    {
        $this-&gt;a = get_large_array();
        $this-&gt;pass_to_function();
    }

    function pass_to_function()
    {
        //process $this-&gt;a
    }
}
</pre>
<p>unset them as soon as possible , so that memory is freed and rest of the script can relax.</p>
<p>Here is a simple demonstration of how assign by reference can save memory in some cases</p>
<pre class="brush: php; title: Code; notranslate">
&lt;?php

ini_set('display_errors' , true);
error_reporting(E_ALL);

$a = array();

for($i = 0; $i &lt; 100000 ; $i++)
{
	$a[$i] = 'A'.$i;
}

echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '&lt;br /&gt;';

$b = $a;
$b[0] = 'B';

echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '&lt;br /&gt;';

$c = $a;
$c[0] = 'B';

echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '&lt;br /&gt;';

$d =&amp; $a;
$d[0] = 'B';

echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '&lt;br /&gt;';
</pre>
<p>The output on a typical php 5.4 machine is :</p>
<div class="highlight">
Memory usage in MB : 18.08208<br />
Memory usage in MB after 1st copy : 27.930944<br />
Memory usage in MB after 2st copy : 37.779808<br />
Memory usage in MB after 3st copy (reference) : 37.779864
</div>
<p>So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.</p>
<h3>25. Use a single database connection, throughout the script</h3>
<p>Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :</p>
<pre class="brush: php; title: Code; notranslate">

function add_to_cart()
{
    $db = new Database();
    $db-&gt;query(&quot;INSERT INTO cart .....&quot;);
}

function empty_cart()
{
    $db = new Database();
    $db-&gt;query(&quot;DELETE FROM cart .....&quot;);
}
</pre>
<p>Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.</p>
<p>Use the singleton pattern for special cases like database connection.</p>
<p><a href="http://www.binarytides.com/blog/40-techniques-to-enhance-your-php-code-part-3/" >Part 3</a></p>
<div class="updated_on">Updated on 12-Apr-2012</div>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1686&type=feed" alt="" /><div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/40-techniques-to-enhance-your-php-code-part-2/';
var dzone_title = '40+ Techniques to enhance your php code &#8211; Part 2';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/40-techniques-to-enhance-your-php-code-part-2/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>40+ Techniques to enhance your php code &#8211; Part 1</title>
		<link>http://www.binarytides.com/blog/35-techniques-to-enhance-your-php-code/</link>
		<comments>http://www.binarytides.com/blog/35-techniques-to-enhance-your-php-code/#comments</comments>
		<pubDate>Thu, 29 Mar 2012 08:44:56 +0000</pubDate>
		<dc:creator>Silver Moon</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[amazing php techniques]]></category>
		<category><![CDATA[amazing php tips]]></category>
		<category><![CDATA[enhance php code]]></category>
		<category><![CDATA[improve php code]]></category>
		<category><![CDATA[master php code]]></category>
		<category><![CDATA[masters php techniques]]></category>
		<category><![CDATA[optimize php code]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[php advanced techniques]]></category>
		<category><![CDATA[php best practices]]></category>
		<category><![CDATA[php techniques]]></category>
		<category><![CDATA[php tips]]></category>
		<category><![CDATA[php tips and tricks]]></category>
		<category><![CDATA[php tutorial]]></category>
		<category><![CDATA[useful php techniques]]></category>
		<category><![CDATA[write efficient php code]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1593</guid>
		<description><![CDATA[The Techniques 1. Do not use relative paths , instead define a ROOT path Its quite common to see such lines : This approach has many drawbacks : It first searches for directories specified in the include paths of php , then looks from the current directory. So many directories are checked. When a script is included by another script in a different directory , its base directory changes to that of the including script. [...]]]></description>
			<content:encoded><![CDATA[<div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/35-techniques-to-enhance-your-php-code/';
var dzone_title = '40+ Techniques to enhance your php code &#8211; Part 1';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div><h2>The Techniques</h2>
<h3>1. Do not use relative paths , instead define a ROOT path</h3>
<p>Its quite common to see such lines :</p>
<pre class="brush: php; title: Code; notranslate">
require_once('../../lib/some_class.php');
</pre>
<p>This approach has many drawbacks :</p>
<p>It first searches for directories specified in the include paths of php , then looks from the current directory.<br />
So many directories are checked.</p>
<p>When a script is included by another script in a different directory , its base directory changes to that of the including script.</p>
<p>Another issue , is that when a script is being run from cron , it may not have its parent directory as the working directory.</p>
<p>So its a good idea to have absolute paths :</p>
<pre class="brush: php; title: Code; notranslate">
define('ROOT' , '/var/www/project/');
require_once(ROOT . '../../lib/some_class.php');

//rest of the code
</pre>
<p>Now this is an absolute path and will always stay constant. But we can improve this further. The directory /var/www/project can change , so do we change it everytime ? No instead we make it portable using magic constants like __FILE__ . Take a closer look :</p>
<pre class="brush: php; title: Code; notranslate">
//suppose your script is /var/www/project/index.php
//Then __FILE__ will always have that full path.

define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
require_once(ROOT . '../../lib/some_class.php');

//rest of the code
</pre>
<p>So now even if you shift your project to a different directory , like moving it to an online server , the same code will run without any changes.</p>
<h3>2. Dont use require , include , require_once or include_once</h3>
<p>Your script could be including various files on top , like class libraries , files for utility and helper functions etc like this :</p>
<pre class="brush: php; title: Code; notranslate">
require_once('lib/Database.php');
require_once('lib/Mail.php');

require_once('helpers/utitlity_functions.php');
</pre>
<p>This is rather primitive. The code needs to be more flexible. Write up helper functions to include things more easily. Lets take an example :</p>
<pre class="brush: php; title: Code; notranslate">
function load_class($class_name)
{
    //path to the class file
    $path = ROOT . '/lib/' . $class_name . '.php');
    require_once( $path );
}

load_class('Database');
load_class('Mail');
</pre>
<p>See any difference ? You must. It does not need any more explanation.<br />
You can improve this further if you wish to like this :</p>
<pre class="brush: php; title: Code; notranslate">
function load_class($class_name)
{
    //path to the class file
    $path = ROOT . '/lib/' . $class_name . '.php');

    if(file_exists($path))
    {
        require_once( $path );
    }
}
</pre>
<p>There are a lot of things that can be done with this :</p>
<p>Search multiple directories for the same class file.<br />
Change the directory containing class files easily , without breaking the code anywhere.<br />
Use similar functions for loading files that contain helper functions , html content etc.</p>
<h3>3. Maintain debugging environment in your application</h3>
<p>During development we echo database queries , dump variables which are creating problems , and then once the problem is solved , we comment them or erase them. But its a good idea to let everything stay and help in the long run</p>
<p>On your development machine you can do this :</p>
<pre class="brush: php; title: Code; notranslate">

define('ENVIRONMENT' , 'development');

if(! $db-&gt;query( $query )
{
    if(ENVIRONMENT == 'development')
    {
        echo &quot;$query failed&quot;;
    }
    else
    {
        echo &quot;Database error. Please contact administrator&quot;;
    }
}
</pre>
<p>And on the server you can do this :</p>
<pre class="brush: php; title: Code; notranslate">

define('ENVIRONMENT' , 'production');

if(! $db-&gt;query( $query )
{
    if(ENVIRONMENT == 'development')
    {
        echo &quot;$query failed&quot;;
    }
    else
    {
        echo &quot;Database error. Please contact administrator&quot;;
    }
}
</pre>
<h3>4. Propagate status messages via session</h3>
<p>Status messages are those messages that are generated after doing a task.</p>
<pre class="brush: php; title: Code; notranslate">
&lt;?php
if($wrong_username || $wrong_password)
{
    $msg = 'Invalid username or password';
}
?&gt;
&lt;html&gt;
&lt;body&gt;

&lt;?php echo $msg; ?&gt;

&lt;form&gt;
...
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Code like that is common. Using variables to show status messages has limitations. They cannot be send via redirects (unless you propagate them as GET variables to the next script , which is very silly). In large scripts there might be multiple messages etc.</p>
<p>Best way is to use session to propagate them (even if on same page). For this there has to be a session_start on every page.</p>
<pre class="brush: php; title: Code; notranslate">

function set_flash($msg)
{
    $_SESSION['message'] = $msg;
}

function get_flash()
{
    $msg = $_SESSION['message'];
    unset($_SESSION['message']);
    return $msg;
}
</pre>
<p>and in your script :</p>
<pre class="brush: php; title: Code; notranslate">
&lt;?php
if($wrong_username || $wrong_password)
{
    set_flash('Invalid username or password');
}
?&gt;
&lt;html&gt;
&lt;body&gt;

Status is : &lt;?php echo get_flash(); ?&gt;
&lt;form&gt;
...
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h3>5. Make your functions flexible</h3>
<pre class="brush: php; title: Code; notranslate">
function add_to_cart($item_id , $qty)
{
    $_SESSION['cart'][$item_id] = $qty;
}

add_to_cart( 'IPHONE3' , 2 );
</pre>
<p>When adding a single item you use the above function. When adding multiple items , will you create another function ? NO. Just make the function flexible enough to take different kinds of parameters. Have a closer look :</p>
<pre class="brush: php; title: Code; notranslate">

function add_to_cart($item_id , $qty)
{
    if(!is_array($item_id))
    {
        $_SESSION['cart'][$item_id] = $qty;
    }

    else
    {
        foreach($item_id as $i_id =&gt; $qty)
        {
            $_SESSION['cart'][$i_id] = $qty;
        }
    }
}

add_to_cart( 'IPHONE3' , 2 );
add_to_cart( array('IPHONE3' =&gt; 2 , 'IPAD' =&gt; 5) );
</pre>
<p>So now the same function can accept different kinds of output. The above can be applied in lots of places to make your code more agile.</p>
<h3>6. Omit the closing php tag if it is the last thing in a script</h3>
<p>I wonder why this tip is omitted from so many blog posts on php tips.</p>
<pre class="brush: php; title: Code; notranslate">
&lt;?php

echo &quot;Hello&quot;;

//Now dont close this tag
</pre>
<p>This will save you lots of problem. Lets take an example :</p>
<p>A class file super_class.php</p>
<pre class="brush: php; title: Code; notranslate">
&lt;?php
class super_class
{
    function super_function()
    {
        //super code
    }
}
?&gt;
//super extra character after the closing tag
</pre>
<p>Now index.php</p>
<pre class="brush: php; title: Code; notranslate">
require_once('super_class.php');

//echo an image or pdf , or set the cookies or session data
</pre>
<p>And you will get Headers already send error. Why ? because the &#8220;super extra character&#8221; has been echoed , and all headers went along with that. Now you start debugging. You may have to waste many hours to find the super extra space.</p>
<p>Hence make it a habit to omit the closing tag :</p>
<pre class="brush: php; title: Code; notranslate">
&lt;?php
class super_class
{
    function super_function()
    {
        //super code
    }
}

//No closing tag
</pre>
<p>Thats better.</p>
<h3>7. Collect all output at one place , and output at one shot to the browser</h3>
<p>This is called output buffering. Lets say you have been echoing content from different functions like this :</p>
<pre class="brush: php; title: Code; notranslate">

function print_header()
{
    echo &quot;&lt;div id='header'&gt;Site Log and Login links&lt;/div&gt;&quot;;
}

function print_footer()
{
    echo &quot;&lt;div id='footer'&gt;Site was made by me&lt;/div&gt;&quot;;
}

print_header();
for($i = 0 ; $i &lt; 100; $i++)
{
    echo &quot;I is : $i &lt;br /&gt;';
}
print_footer();
</pre>
<p>Instead of doing like that , first collect all output in one place. You can either store it inside variables in the functions or use ob_start and ob_end_clean. So now it should look like</p>
<pre class="brush: php; title: Code; notranslate">
function print_header()
{
    $o = &quot;&lt;div id='header'&gt;Site Log and Login links&lt;/div&gt;&quot;;
    return $o;
}

function print_footer()
{
    $o = &quot;&lt;div id='footer'&gt;Site was made by me&lt;/div&gt;&quot;;
    return $o;
}

echo print_header();
for($i = 0 ; $i &lt; 100; $i++)
{
    echo &quot;I is : $i &lt;br /&gt;';
}
echo print_footer();
</pre>
<p>So why should you do output buffering :</p>
<ul>
<li>You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output</li>
<li>
Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed.
</li>
</ul>
<h3>8. Send correct mime types via header when outputting non-html content</h3>
<p>Lets echo some xml.</p>
<pre class="brush: php; title: Code; notranslate">

$xml = '&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; standalone=&quot;yes&quot;?&gt;';
$xml = &quot;&lt;response&gt;
  &lt;code&gt;0&lt;/code&gt;
&lt;/response&gt;&quot;;

//Send xml data
echo $xml;
</pre>
<p>Works fine. But it needs some improvement.</p>
<pre class="brush: php; title: Code; notranslate">

$xml = '&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; standalone=&quot;yes&quot;?&gt;';
$xml = &quot;&lt;response&gt;
  &lt;code&gt;0&lt;/code&gt;
&lt;/response&gt;&quot;;

//Send xml data
header(&quot;content-type: text/xml&quot;);
echo $xml;
</pre>
<p>Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.</p>
<p>Similarly for javascript , css , jpg image , png image :</p>
<p><b>Javascript</b></p>
<pre class="brush: php; title: Code; notranslate">
header(&quot;content-type: application/x-javascript&quot;);
echo &quot;var a = 10&quot;;
</pre>
<p><b>CSS</b></p>
<pre class="brush: php; title: Code; notranslate">
header(&quot;content-type: text/css&quot;);
echo &quot;#div id { background:#000; }&quot;;
</pre>
<h3>9. Set the correct character encoding for a mysql connection</h3>
<p>Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.</p>
<pre class="brush: php; title: Code; notranslate">

$host = 'localhost';
$username = 'root';
$password = 'super_secret';

//Attempt to connect to database
$c = mysqli_connect($host , $username, $password);

//Check connection validity
if (!$c) 
{
	die (&quot;Could not connect to the database host: &lt;br /&gt;&quot;. mysqli_connect_error());
}

//Set the character set of the connection
if(!mysqli_set_charset ( $c , 'UTF8' ))
{
	die('mysqli_set_charset() failed');
}
</pre>
<p>Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.</p>
<p>Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.</p>
<h3>10. Use htmlentities with the correct characterset option</h3>
<p>Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.</p>
<pre class="brush: php; title: Code; notranslate">
$value = htmlentities($this-&gt;value , ENT_QUOTES , 'UTF-8');
</pre>
<p>Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.</p>
<h2>Part 2</h2>
<p>Its here :: <a href="http://www.binarytides.com/blog/40-techniques-to-enhance-your-php-code-part-2/" >Part 2</a></p>
<div class="updated_on">Updated on 12-Apr-2012</div>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1593&type=feed" alt="" /><div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/35-techniques-to-enhance-your-php-code/';
var dzone_title = '40+ Techniques to enhance your php code &#8211; Part 1';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/35-techniques-to-enhance-your-php-code/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>CSSDeck &#8211; Collection of Pure CSS Creations</title>
		<link>http://www.binarytides.com/blog/cssdeck-collection-of-pure-css-creations/</link>
		<comments>http://www.binarytides.com/blog/cssdeck-collection-of-pure-css-creations/#comments</comments>
		<pubDate>Thu, 29 Mar 2012 03:41:03 +0000</pubDate>
		<dc:creator>f00</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[css3]]></category>
		<category><![CDATA[cssdeck]]></category>
		<category><![CDATA[html5]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1590</guid>
		<description><![CDATA[One of the great aspects of Frontend development compared to the world of programming is the ease of access to source code. You can find the source code easily by accessing few source files. For example, if you have a website opened in front of you, you can view the HTML source in the browser, view the CSS and JS source too. Browsers like Firefox have tools like firebug while Chrome has Web Developer Tools [...]]]></description>
			<content:encoded><![CDATA[<div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/cssdeck-collection-of-pure-css-creations/';
var dzone_title = 'CSSDeck &#8211; Collection of Pure CSS Creations';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div><p>One of the great aspects of Frontend development compared to the world of programming is the ease of access to source code. You can find the source code easily by accessing few source files. For example, if you have a website opened in front of you, you can view the HTML source in the browser, view the CSS and JS source too. Browsers like Firefox have tools like firebug while Chrome has Web Developer Tools that facilitates the vieweing of source, debugging it, etc.</p>
<p>Think of <a target="_blank" href="http://cssdeck.com" >CSSDeck</a> as a collection or gallery of Items that have been made with Pure HTML and CSS using least to no images. Some of them are awesome but useless, while some are amazing and reusable in real world projects. Some are not supported by Internet explorer 8 and below so it&#8217;s up to you to decide.</p>
<p>From the website -</p>
<blockquote><p>A Collection of Pure CSS Creations! Let’s form a big collection of items built with pure CSS and HTML and help frontend coders realize the power and flexibility of CSS.</p></blockquote>
<p>Find items that interests you, browser the source code right below the Live Preview of the item, edit the source and see the live preview change, write comments to praise or get help, <a target="_blank" href="http://cssdeck.com/t" >play on their playground</a> to create test cases, write <a target="_blank" href="http://cssdeck.com/post/show" >Articles</a>, submit <a target="_blank" href="http://cssdeck.com/snippet" >snippets</a>, share on <a target="_blank" href="http://twitter.com/cssdeck" >twitter</a> and <a target="_blank" href="http://facebook.com/cssdeck" >facebook</a>, there&#8217;s just SO MUCH.</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1590&type=feed" alt="" /><div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/cssdeck-collection-of-pure-css-creations/';
var dzone_title = 'CSSDeck &#8211; Collection of Pure CSS Creations';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/cssdeck-collection-of-pure-css-creations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Execute shell commands in PHP</title>
		<link>http://www.binarytides.com/blog/execute-shell-commands-in-php/</link>
		<comments>http://www.binarytides.com/blog/execute-shell-commands-in-php/#comments</comments>
		<pubDate>Tue, 27 Mar 2012 08:36:59 +0000</pubDate>
		<dc:creator>Silver Moon</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[php execute shell command]]></category>
		<category><![CDATA[php shell command]]></category>
		<category><![CDATA[php terminal command execution]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1535</guid>
		<description><![CDATA[There are a number of ways shell commands can be executed in php. 1. system &#8220;system() is just like the C version of the function in that it executes the given command and outputs the result. The system() call also tries to automatically flush the web server&#8217;s output buffer after each line of output if PHP is running as a server module.&#8221; 2. passthru &#8220;The passthru() function is similar to the exec() function in that [...]]]></description>
			<content:encoded><![CDATA[<div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/execute-shell-commands-in-php/';
var dzone_title = 'Execute shell commands in PHP';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div><p>There are a number of ways shell commands can be executed in php.</p>
<p>1. <a target="_blank" href="http://php.net/manual/en/function.system.php" >system</a> </p>
<p>&#8220;system() is just like the C version of the function in that it executes the given command and outputs the result.<br />
The system() call also tries to automatically flush the web server&#8217;s output buffer after each line of output if PHP is running as a server module.&#8221;</p>
<p>2. <a target="_blank" href="http://www.php.net/manual/en/function.passthru.php" >passthru</a></p>
<p>&#8220;The passthru() function is similar to the exec() function in that it executes a command. This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser. A common use for this is to execute something like the pbmplus utilities that can output an image stream directly. By setting the Content-type to image/gif and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly.&#8221;</p>
<p>3. <a target="_blank" href="http://www.php.net/manual/en/function.exec.php" >exec</a></p>
<p>&#8220;exec() executes the given command.&#8221;</p>
<p>4. <a target="_blank" href="http://www.php.net/manual/en/function.shell-exec.php" >shell_exec</a></p>
<p>&#8220;This function is identical to the backtick operator.&#8221;</p>
<h3>Portable solution</h3>
<p>A common problem with the above functions is that they are often disabled selectively on shared hostings. For example all function expect passthru may be disabled , or only exec would be available and so on. So it creates a small issue to keep changing code to fit according to the hosting server.</p>
<p>Here is a function that combines all the above functions into 1 and creates a portable solution that tries to work on all kinds of shared hostings where atleast 1 of them is enabled :</p>
<pre class="brush: php; title: Code; notranslate">
/**
	Method to execute a command in the terminal
	Uses :

	1. system
	2. passthru
	3. exec
	4. shell_exec

*/
function terminal($command)
{
	//system
	if(function_exists('system'))
	{
		ob_start();
		system($command , $return_var);
		$output = ob_get_contents();
		ob_end_clean();
	}
	//passthru
	else if(function_exists('passthru'))
	{
		ob_start();
		passthru($command , $return_var);
		$output = ob_get_contents();
		ob_end_clean();
	}

	//exec
	else if(function_exists('exec'))
	{
		exec($command , $output , $return_var);
		$output = implode(&quot;\n&quot; , $output);
	}

	//shell_exec
	else if(function_exists('shell_exec'))
	{
		$output = shell_exec($command) ;
	}

	else
	{
		$output = 'Command execution not possible on this system';
		$return_var = 1;
	}

	return array('output' =&gt; $output , 'status' =&gt; $return_var);
}
</pre>
<p>To use :</p>
<pre class="brush: php; title: Code; notranslate">
$o = terminal('ls');
if($status == 0)
{
    echo $o['output'];
}
else
{
    //some problem
}
</pre>
<p><code>system</code> and <code>passthru</code> echo the output directly to output stream , hence its necessary to use buffering to catch their output before it gets dumped. <code>shell_exec</code> and <code>exec</code> simply return the output.</p>
<p>So using the <code>terminal</code> function your code is more portable across different kinds of hostings and lot of command execution issues can be avoided.</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1535&type=feed" alt="" /><div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/execute-shell-commands-in-php/';
var dzone_title = 'Execute shell commands in PHP';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/execute-shell-commands-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Php get list of locales installed on system</title>
		<link>http://www.binarytides.com/blog/php-get-list-of-locales-installed-on-system/</link>
		<comments>http://www.binarytides.com/blog/php-get-list-of-locales-installed-on-system/#comments</comments>
		<pubDate>Mon, 26 Mar 2012 10:19:54 +0000</pubDate>
		<dc:creator>Silver Moon</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[get locales php]]></category>
		<category><![CDATA[locale list in php]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[php available locales]]></category>
		<category><![CDATA[php locale linux]]></category>
		<category><![CDATA[php locales]]></category>
		<category><![CDATA[php localisation]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1508</guid>
		<description><![CDATA[On linux , the list of locales installed on the system can be fetched through the terminal command locale -a : Now this command can be used inside php to get the list. Along with this list we can also add some information like language name and country name using a list of countries and languages. Here is a list of country codes : And now a list of languages : Now the list of [...]]]></description>
			<content:encoded><![CDATA[<div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/php-get-list-of-locales-installed-on-system/';
var dzone_title = 'Php get list of locales installed on system';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div><p>On linux , the list of locales installed on the system can be fetched through the terminal command <code>locale -a</code> :</p>
<pre class="brush: bash; class-name: small_code; title: Code; notranslate">
$ locale -a
C
C.UTF-8
en_AG
en_AG.utf8
en_AU.utf8
en_BW.utf8
en_CA.utf8
en_DK.utf8
en_GB.utf8
en_HK.utf8
en_IE.utf8
en_IN
en_IN.utf8
en_NG
en_NG.utf8
en_NZ.utf8
en_PH.utf8
en_SG.utf8
en_US.utf8
en_ZA.utf8
en_ZM
en_ZM.utf8
en_ZW.utf8
es_AR.utf8
es_BO.utf8
es_CL.utf8
es_CO.utf8
es_CR.utf8
es_DO.utf8
es_EC.utf8
es_ES.utf8
es_GT.utf8
es_HN.utf8
es_MX.utf8
es_NI.utf8
es_PA.utf8
es_PE.utf8
es_PR.utf8
es_PY.utf8
es_SV.utf8
es_US.utf8
es_UY.utf8
es_VE.utf8
hi_IN
hi_IN.utf8
nl_AW
nl_AW.utf8
nl_BE.utf8
nl_NL.utf8
POSIX
si_LK
si_LK.utf8
zh_CN.utf8
zh_SG.utf8
</pre>
<p>Now this command can be used inside php to get the list. Along with this list we can also add some information like language name and country name using a list of countries and languages.</p>
<p>Here is a list of country codes :</p>
<pre class="brush: php; class-name: small_code; title: Code; notranslate">
&lt;?php
/**
	References :
	1. http://en.wikipedia.org/wiki/ISO_3166-1#Officially_assigned_code_elements
*/
$country_codes = array(

'AF' =&gt; &quot;AFGHANISTAN&quot; ,
'AL' =&gt; &quot;ALBANIA&quot; ,
'DZ' =&gt; &quot;ALGERIA&quot; ,
'AS' =&gt; &quot;AMERICAN SAMOA&quot; ,
'AD' =&gt; &quot;ANDORRA&quot; ,
'AO' =&gt; &quot;ANGOLA&quot; ,
'AI' =&gt; &quot;ANGUILLA&quot; ,
'AQ' =&gt; &quot;ANTARCTICA&quot; ,
'AG' =&gt; &quot;ANTIGUA AND BARBUDA&quot; ,
'AR' =&gt; &quot;ARGENTINA&quot; ,
'AM' =&gt; &quot;ARMENIA&quot; ,
'AW' =&gt; &quot;ARUBA&quot; ,
'AU' =&gt; &quot;AUSTRALIA&quot; ,
'AT' =&gt; &quot;AUSTRIA&quot; ,
'AZ' =&gt; &quot;AZERBAIJAN&quot; ,
'BS' =&gt; &quot;BAHAMAS&quot; ,
'BH' =&gt; &quot;BAHRAIN&quot; ,
'BD' =&gt; &quot;BANGLADESH&quot; ,
'BB' =&gt; &quot;BARBADOS&quot; ,
'BY' =&gt; &quot;BELARUS&quot; ,
'BE' =&gt; &quot;BELGIUM&quot; ,
'BZ' =&gt; &quot;BELIZE&quot; ,
'BJ' =&gt; &quot;BENIN&quot; ,
'BM' =&gt; &quot;BERMUDA&quot; ,
'BT' =&gt; &quot;BHUTAN&quot; ,
'BO' =&gt; &quot;BOLIVIA&quot; ,
'BA' =&gt; &quot;BOSNIA AND HERZEGOVINA&quot; ,
'BW' =&gt; &quot;BOTSWANA&quot; ,
'BV' =&gt; &quot;BOUVET ISLAND&quot; ,
'BR' =&gt; &quot;BRAZIL&quot; ,
'IO' =&gt; &quot;BRITISH INDIAN OCEAN TERRITORY&quot; ,
'BN' =&gt; &quot;BRUNEI DARUSSALAM&quot; ,
'BG' =&gt; &quot;BULGARIA&quot; ,
'BF' =&gt; &quot;BURKINA FASO&quot; ,
'BI' =&gt; &quot;BURUNDI&quot; ,
'KH' =&gt; &quot;CAMBODIA&quot; ,
'CM' =&gt; &quot;CAMEROON&quot; ,
'CA' =&gt; &quot;CANADA&quot; ,
'CV' =&gt; &quot;CAPE VERDE&quot; ,
'KY' =&gt; &quot;CAYMAN ISLANDS&quot; ,
'CF' =&gt; &quot;CENTRAL AFRICAN REPUBLIC&quot; ,
'TD' =&gt; &quot;CHAD&quot; ,
'CL' =&gt; &quot;CHILE&quot; ,
'CN' =&gt; &quot;CHINA&quot; ,
'CX' =&gt; &quot;CHRISTMAS ISLAND&quot; ,
'CC' =&gt; &quot;COCOS (KEELING) ISLANDS&quot; ,
'CO' =&gt; &quot;COLOMBIA&quot; ,
'KM' =&gt; &quot;COMOROS&quot; ,
'CG' =&gt; &quot;CONGO&quot; ,
'CD' =&gt; &quot;CONGO, THE DEMOCRATIC REPUBLIC OF THE&quot; ,
'CK' =&gt; &quot;COOK ISLANDS&quot; ,
'CR' =&gt; &quot;COSTA RICA&quot; ,
'CI' =&gt; &quot;COTE D'IVOIRE&quot; ,
'HR' =&gt; &quot;CROATIA&quot; ,
'CU' =&gt; &quot;CUBA&quot; ,
'CY' =&gt; &quot;CYPRUS&quot; ,
'CZ' =&gt; &quot;CZECH REPUBLIC&quot; ,
'DK' =&gt; &quot;DENMARK&quot; ,
'DJ' =&gt; &quot;DJIBOUTI&quot; ,
'DM' =&gt; &quot;DOMINICA&quot; ,
'DO' =&gt; &quot;DOMINICAN REPUBLIC&quot; ,
'EC' =&gt; &quot;ECUADOR&quot; ,
'EG' =&gt; &quot;EGYPT&quot; ,
'SV' =&gt; &quot;EL SALVADOR&quot; ,
'GQ' =&gt; &quot;EQUATORIAL GUINEA&quot; ,
'ER' =&gt; &quot;ERITREA&quot; ,
'EE' =&gt; &quot;ESTONIA&quot; ,
'ET' =&gt; &quot;ETHIOPIA&quot; ,
'FK' =&gt; &quot;FALKLAND ISLANDS (MALVINAS)&quot; ,
'FO' =&gt; &quot;FAROE ISLANDS&quot; ,
'FJ' =&gt; &quot;FIJI&quot; ,
'FI' =&gt; &quot;FINLAND&quot; ,
'FR' =&gt; &quot;FRANCE&quot; ,
'GF' =&gt; &quot;FRENCH GUIANA&quot; ,
'PF' =&gt; &quot;FRENCH POLYNESIA&quot; ,
'TF' =&gt; &quot;FRENCH SOUTHERN TERRITORIES&quot; ,
'GA' =&gt; &quot;GABON&quot; ,
'GM' =&gt; &quot;GAMBIA&quot; ,
'GE' =&gt; &quot;GEORGIA&quot; ,
'DE' =&gt; &quot;GERMANY&quot; ,
'GH' =&gt; &quot;GHANA&quot; ,
'GI' =&gt; &quot;GIBRALTAR&quot; ,
'GR' =&gt; &quot;GREECE&quot; ,
'GL' =&gt; &quot;GREENLAND&quot; ,
'GD' =&gt; &quot;GRENADA&quot; ,
'GP' =&gt; &quot;GUADELOUPE&quot; ,
'GU' =&gt; &quot;GUAM&quot; ,
'GT' =&gt; &quot;GUATEMALA&quot; ,
'GN' =&gt; &quot;GUINEA&quot; ,
'GW' =&gt; &quot;GUINEA-BISSAU&quot; ,
'GY' =&gt; &quot;GUYANA&quot; ,
'HT' =&gt; &quot;HAITI&quot; ,
'HM' =&gt; &quot;HEARD ISLAND AND MCDONALD ISLANDS&quot; ,
'VA' =&gt; &quot;HOLY SEE (VATICAN CITY STATE)&quot; ,
'HN' =&gt; &quot;HONDURAS&quot; ,
'HK' =&gt; &quot;HONG KONG&quot; ,
'HU' =&gt; &quot;HUNGARY&quot; ,
'IS' =&gt; &quot;ICELAND&quot; ,
'IN' =&gt; &quot;INDIA&quot; ,
'ID' =&gt; &quot;INDONESIA&quot; ,
'IR' =&gt; &quot;IRAN, ISLAMIC REPUBLIC OF&quot; ,
'IQ' =&gt; &quot;IRAQ&quot; ,
'IE' =&gt; &quot;IRELAND&quot; ,
'IL' =&gt; &quot;ISRAEL&quot; ,
'IT' =&gt; &quot;ITALY&quot; ,
'JM' =&gt; &quot;JAMAICA&quot; ,
'JP' =&gt; &quot;JAPAN&quot; ,
'JO' =&gt; &quot;JORDAN&quot; ,
'KZ' =&gt; &quot;KAZAKHSTAN&quot; ,
'KE' =&gt; &quot;KENYA&quot; ,
'KI' =&gt; &quot;KIRIBATI&quot; ,
'KP' =&gt; &quot;KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF&quot; ,
'KR' =&gt; &quot;KOREA, REPUBLIC OF&quot; ,
'KW' =&gt; &quot;KUWAIT&quot; ,
'KG' =&gt; &quot;KYRGYZSTAN&quot; ,
'LA' =&gt; &quot;LAO PEOPLE'S DEMOCRATIC REPUBLIC&quot; ,
'LV' =&gt; &quot;LATVIA&quot; ,
'LB' =&gt; &quot;LEBANON&quot; ,
'LS' =&gt; &quot;LESOTHO&quot; ,
'LR' =&gt; &quot;LIBERIA&quot; ,
'LY' =&gt; &quot;LIBYAN ARAB JAMAHIRIYA&quot; ,
'LI' =&gt; &quot;LIECHTENSTEIN&quot; ,
'LT' =&gt; &quot;LITHUANIA&quot; ,
'LU' =&gt; &quot;LUXEMBOURG&quot; ,
'MO' =&gt; &quot;MACAO&quot; ,
'MK' =&gt; &quot;MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF&quot; ,
'MG' =&gt; &quot;MADAGASCAR&quot; ,
'MW' =&gt; &quot;MALAWI&quot; ,
'MY' =&gt; &quot;MALAYSIA&quot; ,
'MV' =&gt; &quot;MALDIVES&quot; ,
'ML' =&gt; &quot;MALI&quot; ,
'MT' =&gt; &quot;MALTA&quot; ,
'MH' =&gt; &quot;MARSHALL ISLANDS&quot; ,
'MQ' =&gt; &quot;MARTINIQUE&quot; ,
'MR' =&gt; &quot;MAURITANIA&quot; ,
'MU' =&gt; &quot;MAURITIUS&quot; ,
'YT' =&gt; &quot;MAYOTTE&quot; ,
'MX' =&gt; &quot;MEXICO&quot; ,
'FM' =&gt; &quot;MICRONESIA, FEDERATED STATES OF&quot; ,
'MD' =&gt; &quot;MOLDOVA, REPUBLIC OF&quot; ,
'MC' =&gt; &quot;MONACO&quot; ,
'MN' =&gt; &quot;MONGOLIA&quot; ,
'MS' =&gt; &quot;MONTSERRAT&quot; ,
'MA' =&gt; &quot;MOROCCO&quot; ,
'MZ' =&gt; &quot;MOZAMBIQUE&quot; ,
'MM' =&gt; &quot;MYANMAR&quot; ,
'NA' =&gt; &quot;NAMIBIA&quot; ,
'NR' =&gt; &quot;NAURU&quot; ,
'NP' =&gt; &quot;NEPAL&quot; ,
'NL' =&gt; &quot;NETHERLANDS&quot; ,
'AN' =&gt; &quot;NETHERLANDS ANTILLES&quot; ,
'NC' =&gt; &quot;NEW CALEDONIA&quot; ,
'NZ' =&gt; &quot;NEW ZEALAND&quot; ,
'NI' =&gt; &quot;NICARAGUA&quot; ,
'NE' =&gt; &quot;NIGER&quot; ,
'NG' =&gt; &quot;NIGERIA&quot; ,
'NU' =&gt; &quot;NIUE&quot; ,
'NF' =&gt; &quot;NORFOLK ISLAND&quot; ,
'MP' =&gt; &quot;NORTHERN MARIANA ISLANDS&quot; ,
'NO' =&gt; &quot;NORWAY&quot; ,
'OM' =&gt; &quot;OMAN&quot; ,
'PK' =&gt; &quot;PAKISTAN&quot; ,
'PW' =&gt; &quot;PALAU&quot; ,
'PS' =&gt; &quot;PALESTINIAN TERRITORY, OCCUPIED&quot; ,
'PA' =&gt; &quot;PANAMA&quot; ,
'PG' =&gt; &quot;PAPUA NEW GUINEA&quot; ,
'PY' =&gt; &quot;PARAGUAY&quot; ,
'PE' =&gt; &quot;PERU&quot; ,
'PH' =&gt; &quot;PHILIPPINES&quot; ,
'PN' =&gt; &quot;PITCAIRN&quot; ,
'PL' =&gt; &quot;POLAND&quot; ,
'PT' =&gt; &quot;PORTUGAL&quot; ,
'PR' =&gt; &quot;PUERTO RICO&quot; ,
'QA' =&gt; &quot;QATAR&quot; ,
'RE' =&gt; &quot;REUNION&quot; ,
'RO' =&gt; &quot;ROMANIA&quot; ,
'RU' =&gt; &quot;RUSSIAN FEDERATION&quot; ,
'RW' =&gt; &quot;RWANDA&quot; ,
'SH' =&gt; &quot;SAINT HELENA&quot; ,
'KN' =&gt; &quot;SAINT KITTS AND NEVIS&quot; ,
'LC' =&gt; &quot;SAINT LUCIA&quot; ,
'PM' =&gt; &quot;SAINT PIERRE AND MIQUELON&quot; ,
'VC' =&gt; &quot;SAINT VINCENT AND THE GRENADINES&quot; ,
'WS' =&gt; &quot;SAMOA&quot; ,
'SM' =&gt; &quot;SAN MARINO&quot; ,
'ST' =&gt; &quot;SAO TOME AND PRINCIPE&quot; ,
'SA' =&gt; &quot;SAUDI ARABIA&quot; ,
'SN' =&gt; &quot;SENEGAL&quot; ,
'CS' =&gt; &quot;SERBIA AND MONTENEGRO&quot; ,
'SC' =&gt; &quot;SEYCHELLES&quot; ,
'SL' =&gt; &quot;SIERRA LEONE&quot; ,
'SG' =&gt; &quot;SINGAPORE&quot; ,
'SK' =&gt; &quot;SLOVAKIA&quot; ,
'SI' =&gt; &quot;SLOVENIA&quot; ,
'SB' =&gt; &quot;SOLOMON ISLANDS&quot; ,
'SO' =&gt; &quot;SOMALIA&quot; ,
'ZA' =&gt; &quot;SOUTH AFRICA&quot; ,
'GS' =&gt; &quot;SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS&quot; ,
'ES' =&gt; &quot;SPAIN&quot; ,
'LK' =&gt; &quot;SRI LANKA&quot; ,
'SD' =&gt; &quot;SUDAN&quot; ,
'SR' =&gt; &quot;SURINAME&quot; ,
'SJ' =&gt; &quot;SVALBARD AND JAN MAYEN&quot; ,
'SZ' =&gt; &quot;SWAZILAND&quot; ,
'SE' =&gt; &quot;SWEDEN&quot; ,
'CH' =&gt; &quot;SWITZERLAND&quot; ,
'SY' =&gt; &quot;SYRIAN ARAB REPUBLIC&quot; ,
'TW' =&gt; &quot;TAIWAN, PROVINCE OF CHINA&quot; ,
'TJ' =&gt; &quot;TAJIKISTAN&quot; ,
'TZ' =&gt; &quot;TANZANIA, UNITED REPUBLIC OF&quot; ,
'TH' =&gt; &quot;THAILAND&quot; ,
'TL' =&gt; &quot;TIMOR-LESTE&quot; ,
'TG' =&gt; &quot;TOGO&quot; ,
'TK' =&gt; &quot;TOKELAU&quot; ,
'TO' =&gt; &quot;TONGA&quot; ,
'TT' =&gt; &quot;TRINIDAD AND TOBAGO&quot; ,
'TN' =&gt; &quot;TUNISIA&quot; ,
'TR' =&gt; &quot;TURKEY&quot; ,
'TM' =&gt; &quot;TURKMENISTAN&quot; ,
'TC' =&gt; &quot;TURKS AND CAICOS ISLANDS&quot; ,
'TV' =&gt; &quot;TUVALU&quot; ,
'UG' =&gt; &quot;UGANDA&quot; ,
'UA' =&gt; &quot;UKRAINE&quot; ,
'AE' =&gt; &quot;UNITED ARAB EMIRATES&quot; ,
'GB' =&gt; &quot;UNITED KINGDOM&quot; ,
'US' =&gt; &quot;UNITED STATES&quot; ,
'UM' =&gt; &quot;UNITED STATES MINOR OUTLYING ISLANDS&quot; ,
'UY' =&gt; &quot;URUGUAY&quot; ,
'UZ' =&gt; &quot;UZBEKISTAN&quot; ,
'VU' =&gt; &quot;VANUATU&quot; ,
'VE' =&gt; &quot;VENEZUELA&quot; ,
'VN' =&gt; &quot;VIET NAM&quot; ,
'VG' =&gt; &quot;VIRGIN ISLANDS, BRITISH&quot; ,
'VI' =&gt; &quot;VIRGIN ISLANDS, U.S.&quot; ,
'WF' =&gt; &quot;WALLIS AND FUTUNA&quot; ,
'EH' =&gt; &quot;WESTERN SAHARA&quot; ,
'YE' =&gt; &quot;YEMEN&quot; ,
'ZM' =&gt; &quot;ZAMBIA&quot; ,
'ZW' =&gt; &quot;ZIMBABWE&quot; ,
);

//End of country codes
</pre>
<p>And now a list of languages :</p>
<pre class="brush: php; class-name: small_code; title: Code; notranslate">
&lt;?php
/**
	ISO 639-1 Language Codes
	Useful in Locale analysis

	References :
	1. http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
	2. http://blog.xoundboy.com/?p=235
*/

$language_codes = array(
		'en' =&gt; 'English' ,
		'aa' =&gt; 'Afar' ,
		'ab' =&gt; 'Abkhazian' ,
		'af' =&gt; 'Afrikaans' ,
		'am' =&gt; 'Amharic' ,
		'ar' =&gt; 'Arabic' ,
		'as' =&gt; 'Assamese' ,
		'ay' =&gt; 'Aymara' ,
		'az' =&gt; 'Azerbaijani' ,
		'ba' =&gt; 'Bashkir' ,
		'be' =&gt; 'Byelorussian' ,
		'bg' =&gt; 'Bulgarian' ,
		'bh' =&gt; 'Bihari' ,
		'bi' =&gt; 'Bislama' ,
		'bn' =&gt; 'Bengali/Bangla' ,
		'bo' =&gt; 'Tibetan' ,
		'br' =&gt; 'Breton' ,
		'ca' =&gt; 'Catalan' ,
		'co' =&gt; 'Corsican' ,
		'cs' =&gt; 'Czech' ,
		'cy' =&gt; 'Welsh' ,
		'da' =&gt; 'Danish' ,
		'de' =&gt; 'German' ,
		'dz' =&gt; 'Bhutani' ,
		'el' =&gt; 'Greek' ,
		'eo' =&gt; 'Esperanto' ,
		'es' =&gt; 'Spanish' ,
		'et' =&gt; 'Estonian' ,
		'eu' =&gt; 'Basque' ,
		'fa' =&gt; 'Persian' ,
		'fi' =&gt; 'Finnish' ,
		'fj' =&gt; 'Fiji' ,
		'fo' =&gt; 'Faeroese' ,
		'fr' =&gt; 'French' ,
		'fy' =&gt; 'Frisian' ,
		'ga' =&gt; 'Irish' ,
		'gd' =&gt; 'Scots/Gaelic' ,
		'gl' =&gt; 'Galician' ,
		'gn' =&gt; 'Guarani' ,
		'gu' =&gt; 'Gujarati' ,
		'ha' =&gt; 'Hausa' ,
		'hi' =&gt; 'Hindi' ,
		'hr' =&gt; 'Croatian' ,
		'hu' =&gt; 'Hungarian' ,
		'hy' =&gt; 'Armenian' ,
		'ia' =&gt; 'Interlingua' ,
		'ie' =&gt; 'Interlingue' ,
		'ik' =&gt; 'Inupiak' ,
		'in' =&gt; 'Indonesian' ,
		'is' =&gt; 'Icelandic' ,
		'it' =&gt; 'Italian' ,
		'iw' =&gt; 'Hebrew' ,
		'ja' =&gt; 'Japanese' ,
		'ji' =&gt; 'Yiddish' ,
		'jw' =&gt; 'Javanese' ,
		'ka' =&gt; 'Georgian' ,
		'kk' =&gt; 'Kazakh' ,
		'kl' =&gt; 'Greenlandic' ,
		'km' =&gt; 'Cambodian' ,
		'kn' =&gt; 'Kannada' ,
		'ko' =&gt; 'Korean' ,
		'ks' =&gt; 'Kashmiri' ,
		'ku' =&gt; 'Kurdish' ,
		'ky' =&gt; 'Kirghiz' ,
		'la' =&gt; 'Latin' ,
		'ln' =&gt; 'Lingala' ,
		'lo' =&gt; 'Laothian' ,
		'lt' =&gt; 'Lithuanian' ,
		'lv' =&gt; 'Latvian/Lettish' ,
		'mg' =&gt; 'Malagasy' ,
		'mi' =&gt; 'Maori' ,
		'mk' =&gt; 'Macedonian' ,
		'ml' =&gt; 'Malayalam' ,
		'mn' =&gt; 'Mongolian' ,
		'mo' =&gt; 'Moldavian' ,
		'mr' =&gt; 'Marathi' ,
		'ms' =&gt; 'Malay' ,
		'mt' =&gt; 'Maltese' ,
		'my' =&gt; 'Burmese' ,
		'na' =&gt; 'Nauru' ,
		'ne' =&gt; 'Nepali' ,
		'nl' =&gt; 'Dutch' ,
		'no' =&gt; 'Norwegian' ,
		'oc' =&gt; 'Occitan' ,
		'om' =&gt; '(Afan)/Oromoor/Oriya' ,
		'pa' =&gt; 'Punjabi' ,
		'pl' =&gt; 'Polish' ,
		'ps' =&gt; 'Pashto/Pushto' ,
		'pt' =&gt; 'Portuguese' ,
		'qu' =&gt; 'Quechua' ,
		'rm' =&gt; 'Rhaeto-Romance' ,
		'rn' =&gt; 'Kirundi' ,
		'ro' =&gt; 'Romanian' ,
		'ru' =&gt; 'Russian' ,
		'rw' =&gt; 'Kinyarwanda' ,
		'sa' =&gt; 'Sanskrit' ,
		'sd' =&gt; 'Sindhi' ,
		'sg' =&gt; 'Sangro' ,
		'sh' =&gt; 'Serbo-Croatian' ,
		'si' =&gt; 'Singhalese' ,
		'sk' =&gt; 'Slovak' ,
		'sl' =&gt; 'Slovenian' ,
		'sm' =&gt; 'Samoan' ,
		'sn' =&gt; 'Shona' ,
		'so' =&gt; 'Somali' ,
		'sq' =&gt; 'Albanian' ,
		'sr' =&gt; 'Serbian' ,
		'ss' =&gt; 'Siswati' ,
		'st' =&gt; 'Sesotho' ,
		'su' =&gt; 'Sundanese' ,
		'sv' =&gt; 'Swedish' ,
		'sw' =&gt; 'Swahili' ,
		'ta' =&gt; 'Tamil' ,
		'te' =&gt; 'Tegulu' ,
		'tg' =&gt; 'Tajik' ,
		'th' =&gt; 'Thai' ,
		'ti' =&gt; 'Tigrinya' ,
		'tk' =&gt; 'Turkmen' ,
		'tl' =&gt; 'Tagalog' ,
		'tn' =&gt; 'Setswana' ,
		'to' =&gt; 'Tonga' ,
		'tr' =&gt; 'Turkish' ,
		'ts' =&gt; 'Tsonga' ,
		'tt' =&gt; 'Tatar' ,
		'tw' =&gt; 'Twi' ,
		'uk' =&gt; 'Ukrainian' ,
		'ur' =&gt; 'Urdu' ,
		'uz' =&gt; 'Uzbek' ,
		'vi' =&gt; 'Vietnamese' ,
		'vo' =&gt; 'Volapuk' ,
		'wo' =&gt; 'Wolof' ,
		'xh' =&gt; 'Xhosa' ,
		'yo' =&gt; 'Yoruba' ,
		'zh' =&gt; 'Chinese' ,
		'zu' =&gt; 'Zulu' ,
		);
</pre>
<p>Now the list of locales + countries + languages can be used to present information properly. Here is the code :</p>
<pre class="brush: php; title: locale.php; notranslate">
$locale_data = array();

//Get locales from Linux terminal command locale
$locales = shell_exec('locale -a');

$locales = explode(&quot;\n&quot; , $locales);

foreach($locales as $c =&gt; $l)
{
	if(strlen($l))
	{
		$parts = explode('.' , $l);
		$lc = $parts[0];

		list($lcode , $ccode) = explode('_' , $lc);

		$lcode = strtolower($lcode);

		$language = $language_codes[$lcode];
		$country = $country_codes[$ccode];

		if(strlen($language) and strlen($country))
		{
			$locale_data[$l] = &quot;$language - $country - {$parts[1]}&quot;;
		}
	}
}

print_r($locale_data);
</pre>
<h3>Output</h3>
<pre class="brush: php; class-name: small_code; title: Code; notranslate">

Array
(
    [en_AG] =&gt; English - ANTIGUA AND BARBUDA -
    [en_AG.utf8] =&gt; English - ANTIGUA AND BARBUDA - utf8
    [en_AU.utf8] =&gt; English - AUSTRALIA - utf8
    [en_BW.utf8] =&gt; English - BOTSWANA - utf8
    [en_CA.utf8] =&gt; English - CANADA - utf8
    [en_DK.utf8] =&gt; English - DENMARK - utf8
    [en_GB.utf8] =&gt; English - UNITED KINGDOM - utf8
    [en_HK.utf8] =&gt; English - HONG KONG - utf8
    [en_IE.utf8] =&gt; English - IRELAND - utf8
    [en_IN] =&gt; English - INDIA -
    [en_IN.utf8] =&gt; English - INDIA - utf8
    [en_NG] =&gt; English - NIGERIA -
    [en_NG.utf8] =&gt; English - NIGERIA - utf8
    [en_NZ.utf8] =&gt; English - NEW ZEALAND - utf8
    [en_PH.utf8] =&gt; English - PHILIPPINES - utf8
    [en_SG.utf8] =&gt; English - SINGAPORE - utf8
    [en_US.utf8] =&gt; English - UNITED STATES - utf8
    [en_ZA.utf8] =&gt; English - SOUTH AFRICA - utf8
    [en_ZM] =&gt; English - ZAMBIA -
    [en_ZM.utf8] =&gt; English - ZAMBIA - utf8
    [en_ZW.utf8] =&gt; English - ZIMBABWE - utf8
    [es_AR.utf8] =&gt; Spanish - ARGENTINA - utf8
    [es_BO.utf8] =&gt; Spanish - BOLIVIA - utf8
    [es_CL.utf8] =&gt; Spanish - CHILE - utf8
    [es_CO.utf8] =&gt; Spanish - COLOMBIA - utf8
    [es_CR.utf8] =&gt; Spanish - COSTA RICA - utf8
    [es_DO.utf8] =&gt; Spanish - DOMINICAN REPUBLIC - utf8
    [es_EC.utf8] =&gt; Spanish - ECUADOR - utf8
    [es_ES.utf8] =&gt; Spanish - SPAIN - utf8
    [es_GT.utf8] =&gt; Spanish - GUATEMALA - utf8
    [es_HN.utf8] =&gt; Spanish - HONDURAS - utf8
    [es_MX.utf8] =&gt; Spanish - MEXICO - utf8
    [es_NI.utf8] =&gt; Spanish - NICARAGUA - utf8
    [es_PA.utf8] =&gt; Spanish - PANAMA - utf8
    [es_PE.utf8] =&gt; Spanish - PERU - utf8
    [es_PR.utf8] =&gt; Spanish - PUERTO RICO - utf8
    [es_PY.utf8] =&gt; Spanish - PARAGUAY - utf8
    [es_SV.utf8] =&gt; Spanish - EL SALVADOR - utf8
    [es_US.utf8] =&gt; Spanish - UNITED STATES - utf8
    [es_UY.utf8] =&gt; Spanish - URUGUAY - utf8
    [es_VE.utf8] =&gt; Spanish - VENEZUELA - utf8
    [hi_IN] =&gt; Hindi - INDIA -
    [hi_IN.utf8] =&gt; Hindi - INDIA - utf8
    [nl_AW] =&gt; Dutch - ARUBA -
    [nl_AW.utf8] =&gt; Dutch - ARUBA - utf8
    [nl_BE.utf8] =&gt; Dutch - BELGIUM - utf8
    [nl_NL.utf8] =&gt; Dutch - NETHERLANDS - utf8
    [si_LK] =&gt; Singhalese - SRI LANKA -
    [si_LK.utf8] =&gt; Singhalese - SRI LANKA - utf8
    [zh_CN.utf8] =&gt; Chinese - CHINA - utf8
    [zh_SG.utf8] =&gt; Chinese - SINGAPORE - utf8
)
</pre>
<p>Now the above array can be used to generate a dropdown , from which the locale can be selected and saved.<br />
The locales C and POSIX have been omitted.</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1508&type=feed" alt="" /><div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/php-get-list-of-locales-installed-on-system/';
var dzone_title = 'Php get list of locales installed on system';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/php-get-list-of-locales-installed-on-system/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sound cracking in Ubuntu 11.10</title>
		<link>http://www.binarytides.com/blog/sound-cracking-in-ubuntu-11-10/</link>
		<comments>http://www.binarytides.com/blog/sound-cracking-in-ubuntu-11-10/#comments</comments>
		<pubDate>Thu, 22 Mar 2012 11:31:14 +0000</pubDate>
		<dc:creator>Silver Moon</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1495</guid>
		<description><![CDATA[I recently upgraded my ubuntu 11.04 to 11.10 and then noticed that sound output started cracking when I played mp3 files or youtube videos. The only solution at the moment is to reduce PCM value in alsamixer terminal window Type alsamixed at terminal : A window would come up with multiple vertical bars. 3rd one in them is PCM. Reduce it , this should remove the cracking sound problem. Or you can try reducing the [...]]]></description>
			<content:encoded><![CDATA[<div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/sound-cracking-in-ubuntu-11-10/';
var dzone_title = 'Sound cracking in Ubuntu 11.10';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div><p>I recently upgraded my ubuntu 11.04 to 11.10 and then noticed that sound output started cracking when I played mp3 files or youtube videos.</p>
<p>The only solution at the moment is to reduce PCM value in alsamixer terminal window<br />
Type alsamixed at terminal :</p>
<pre class="brush: bash; title: Code; notranslate">
$ alsamixer
</pre>
<p>A window would come up with multiple vertical bars. 3rd one in them is PCM. Reduce it , this should remove the cracking sound problem. Or you can try reducing the sound in gnome-sound-applet</p>
<p>Some description of the bug :</p>
<p>https://bugs.launchpad.net/ubuntu/+source/pulseaudio/+bug/827393</p>
<p>http://www.mail-archive.com/ubuntu-bugs@lists.ubuntu.com/msg3153558.html</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1495&type=feed" alt="" /><div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/sound-cracking-in-ubuntu-11-10/';
var dzone_title = 'Sound cracking in Ubuntu 11.10';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/sound-cracking-in-ubuntu-11-10/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP script to perform IP whois</title>
		<link>http://www.binarytides.com/blog/php-script-to-perform-ip-whois/</link>
		<comments>http://www.binarytides.com/blog/php-script-to-perform-ip-whois/#comments</comments>
		<pubDate>Tue, 20 Mar 2012 13:05:08 +0000</pubDate>
		<dc:creator>Silver Moon</dc:creator>
				<category><![CDATA[Networking]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[php code for ip whois]]></category>
		<category><![CDATA[php whois code]]></category>
		<category><![CDATA[whois code in php]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1493</guid>
		<description><![CDATA[Theory To fetch the whois data of an IP address , the steps are as follows : 1. Contact whois.iana.org and ask for the RIR whois server of the ip address. 2. Contact the whois server of the RIR and get the whois details of the ip address. Code The function get_whois_from_server is a generic function that can contact any whois server and make a request based on the ip address provided. It then collects [...]]]></description>
			<content:encoded><![CDATA[<div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/php-script-to-perform-ip-whois/';
var dzone_title = 'PHP script to perform IP whois';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div><h3>Theory</h3>
<p>To fetch the whois data of an IP address , the steps are as follows :</p>
<p>1. Contact whois.iana.org and ask for the RIR whois server of the ip address.<br />
2. Contact the whois server of the RIR and get the whois details of the ip address. </p>
<h3>Code</h3>
<pre class="brush: php; title: Code; notranslate">
&lt;?php
/**
	Program to perform ip whois
	Silver Moon
	m00n.silv3r@gmail.com
*/

$ip = &quot;74.65.112.23&quot;;

$whois = get_whois($ip);

echo &quot;&lt;pre&gt;$whois&lt;/pre&gt;&quot;;

/**
	Get the whois content of an ip by selecting the correct server
*/
function get_whois($ip)
{
	$w = get_whois_from_server('whois.iana.org' , $ip);

	preg_match('@whois\.[\w\.]*@si' , $w , $data);

	$whois_server = $data[0];

	//echo $whois_server;

	//now get actual whois data
	$whois_data = get_whois_from_server($whois_server , $ip);

	return $whois_data;
}

/**
	Get the whois result from a whois server
	return text
*/
function get_whois_from_server($server , $ip)
{
	$data = '';

	#Before connecting lets check whether server alive or not

	#Create the socket and connect
	$f = fsockopen($server, 43, $errno, $errstr, 3);	//Open a new connection
	if(!$f)
	{
		return '';
	}

	#Set the timeout limit for read
	if(!stream_set_timeout($f , 3))
	{
		die('Unable to set set_timeout');	#Did this solve the problem ?
	}

	#Send the IP to the whois server
	if($f)
	{
		fputs($f, &quot;$ip\r\n&quot;);
	}

	/*
		Theory : stream_set_timeout must be set after a write and before a read for it to take effect on the read operation
		If it is set before the write then it will have no effect : http://in.php.net/stream_set_timeout
	*/

	//Set the timeout limit for read
	if(!stream_set_timeout($f , 3))
	{
		die('Unable to stream_set_timeout');	#Did this solve the problem ?
	}

	//Set socket in non-blocking mode
	stream_set_blocking ($f, 0 );

	//If connection still valid
	if($f)
	{
		while (!feof($f))
		{
			$data .= fread($f , 128);
		}
	}

	//Now return the data
	return $data;
}
</pre>
<p>The function <code>get_whois_from_server</code> is a generic function that can contact any whois server and make a request based on the ip address provided. It then collects the results and returns it back.</p>
<h3>Output</h3>
<pre class="brush: cpp; class-name: small_code; title: Code; notranslate">
#
# Query terms are ambiguous.  The query is assumed to be:
#     &quot;n 74.65.112.23&quot;
#
# Use &quot;?&quot; to get help.
#

#
# The following results may also be obtained via:
# http://whois.arin.net/rest/nets;q=74.65.112.23?showDetails=true&amp;showARIN=false&amp;ext=netref2
#

NetRange:       74.64.0.0 - 74.79.255.255
CIDR:           74.64.0.0/12
OriginAS:
NetName:        RRNY
NetHandle:      NET-74-64-0-0-1
Parent:         NET-74-0-0-0-0
NetType:        Direct Allocation
RegDate:        2006-03-27
Updated:        2007-01-29
Ref:            http://whois.arin.net/rest/net/NET-74-64-0-0-1

OrgName:        Road Runner HoldCo LLC
OrgId:          RRNY
Address:        13820 Sunrise Valley Drive
City:           Herndon
StateProv:      VA
PostalCode:     20171
Country:        US
RegDate:        2000-09-28
Updated:        2011-07-06
Comment:        Allocations for this OrgID serve Road Runner residential customers out of the New York City, NY and Syracuse, NY RDCs.
Ref:            http://whois.arin.net/rest/org/RRNY

ReferralServer: rwhois://ipmt.rr.com:4321

OrgTechHandle: IPTEC-ARIN
OrgTechName:   IP Tech
OrgTechPhone:  +1-703-345-3416
OrgTechEmail:  abuse@rr.com
OrgTechRef:    http://whois.arin.net/rest/poc/IPTEC-ARIN

OrgAbuseHandle: ABUSE10-ARIN
OrgAbuseName:   Abuse
OrgAbusePhone:  +1-703-345-3416
OrgAbuseEmail:  abuse@rr.com
OrgAbuseRef:    http://whois.arin.net/rest/poc/ABUSE10-ARIN

#
# ARIN WHOIS data and services are subject to the Terms of Use
# available at: https://www.arin.net/whois_tou.html
#
</pre>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1493&type=feed" alt="" /><div class="dzone_button" style="float: right; margin-left: 10px;">
<script type="text/javascript">
var dzone_url = 'http://www.binarytides.com/blog/php-script-to-perform-ip-whois/';
var dzone_title = 'PHP script to perform IP whois';
var dzone_blurb = '';
var dzone_style = '2';
</script>
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/php-script-to-perform-ip-whois/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  www.binarytides.com/blog/feed/ ) in 0.63873 seconds, on May 20th, 2012 at 3:07 am UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 20th, 2012 at 4:07 am UTC -->
