Logicationz Tech

More Intelligent Solutionz…!

Automatic configbase url

Don’t you just hate it, when you move from development server to production server that you have to change the $config[’base_url’] setting?

Well I do. Because I do it a lot, specially when I’m demoing a web application, that’s why I added this code to the config.php

$config['base_url'] = "http://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

Once thats added, Codeigniter base_url will adapt to whatever the url you’re using.

Here a version that works for both: http and https:

$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

Or you can just put use this (pretty much the same as above):

$config['base_url'] = 'http' . ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 's' : '')


January 29, 2010 Posted by | CodeIgniter, Helpful Tips and Tricks | , , | Leave a comment

Why CodeIgniter HTML helper functions rock

A complaint I often hear about CodeIgniter is one about HTML helper functions like form_open(), doctype() and img().

The complaint boils down to these points:

  • heading(‘Hello’, 1) is ugly compared to <h1>Hello</h1>!
  • Putting HTML in PHP functions is “bad MVC”.
  • My favourite “I know how to write HTML, I don’t need a helper”.

These points of view come from people who do not understanding the potential benefits of using HTML helpers – whichis fair enough as I used to think they were useless too.

Two small things to mention first, then on to the “meat” of the article.

It looks ugly

If you are reading this you are quite likely a programmer who stares at PHP for large amounts of time. Who cares if it does not look as clean as plain HTML in your view files? As far as readability goes, if a designer was to look at heading() im sure it would make perfect sense to them as much as a <h1>.

MVC pattern

Due to CodeIgniter being a MVC framework, people try to apply those three letters to everything. The people who see HTML helpers as “bad MVC” say so mainly because they have HTML outside of the view, which to them “goes against the rules” but I don’t think it should be as cut-and-dry as “ALL HTML ALWAYS GOES IN VIEWS”.

The way I see it is simple, views should contain your custom chunks of HTML (i.e. displaying content, forms, RSS feeds, etc) and helpers/plugins should contain whatever they need to do their helpful job and if that happens to be a small amount of HTML, who gives a damn? It doesn’t “break MVC” in the slightest.

Wrapping your data

The main interest to me comes in the extra abstraction layer these HTML helpers provide you with. The “whats the point?” comments can be answered in the same way as “What’s the point in using jQuery?” or “Why use CodeIgniter over PHP?”. The extra layer of abstraction, combined with helper extending/overriding makes it very easy to change simple bits of logic throughout your application output with minimal fuss.

To explain what the f**k I am talking about, I’ll use an example.

<form action="<?php echo site_url('controller/method'); ?>" method="post">
<?php echo form_open('controller/method');

First you will see the standard HTML way to do it, with the site_url() function used to create the link to the form action. Second you will see the form_open() tag – and in this example its shorter too, wahey!

I wanted a way to set accept-charset=”UTF-8″ in all my forms to help keep my data all <a href=”/news/2009/08/UTF-8-support-for-CodeIgniter”>UTF-8 in CodeIgniter</a>. If I was using just HTML then I would have to go through <strong>all</strong> my forms and add that in myself, which would be wasting time I could have spent at the pub.

Instead, as CodeIgniter allows you to extend helpers, I just made my own slightly modified form_open() inapplication/helpers/MY_form_helper.php which contained this logic. Because I was using PHP to wrap my useful data, I could make one simple change and update all of my <form> tags.

The main problem is people are looking at these HTML helper functions and seeing them purely as different syntax.

Think big

My example shows one useful application of this beyond shorter syntax, but there are plenty more applications for

HTML helper functions.

  • Store your DOCTYPE in a config variable and update your entire site from XHTML 1.1 to HTML 5 easily
  • Developing your app with <h1>Something</h1> then relizing your headers in 500 different view files need <h1><span>Something</span></h1>
  • Fetching metadata from a database and outputting with meta()
  • Adding Google event tracking to images loaded with img()
  • Set your page titles (display headers, not title tag) to use a config variable 1 to 6 in case your CMS needs to change what level the links are.
  • XSS protection for forms using form_open() and form_close(). Derek Allard hinted at this some time ago and I still hope to see it happen.

There are all sorts of crazy things you can do with HTML helpers and while it might be hard to see their value before you have the “aha!” moment, it is a pain to realise you need to use them when it is too late.

January 19, 2010 Posted by | CodeIgniter | , | Leave a comment

Country Name and ISO 3166 Code MySQL Import File

Download iso_country_list.sql (18662 bytes, Last updated Sat Dec 01 23:19:11 2007)
Download usps_states_list.sql (4202 bytes, Last updated Sat Dec 01 23:19:11 2007)

I recently had a project at work which required a web-based user registration sort of feature. Because the project
had an international flavor, I had to let people from every country register. And since we were going to need to
generate reports broken down by country and eventually make mailing labels from the data stored in our MySQL database,
I wanted the data to be pretty clean. Thus, I didn’t want people to either have to or be able to type in their
country of origin by hand. I wanted a select list they could choose from.

What I wound up doing was making a table which listed the names and
ISO 3166 codes
of all the countries of the world. I then referenced this table in my main user registration table as a foreign key.
This would allow us to look at all the people that had registered from Europe, let’s say, and then make graphs with the
two-letter ISO codes on them for clarity. It should work out pretty well.

To make a long story short, I realized that this was the fourth time I had made such a table, and the fourth time
I had done it from scratch (and it was the third time I had done it by writing
a perl script which screen-scraped
a list off the
). This is silly and a waste of time. So I decided to put my SQL file up here where I can get it later if
I needed it. Since sharing is good, I made it public here so other people can get it if they find it useful (I
didn’t find much when I went googling for such a list…).


It’s been brought to my attention that the SQL file shows Taiwan as a “Province of China”, and that some people (the Taiwanese in particular) have some sensitivity towards the issue of Taiwan’s sovereignty.

After some consideration, I’ve decided that it’s not my place to second-guess a standards body and a world governing organization by editing information coming from the U.N. and ISO. Because the SQL file is generated automatically from those sources, and because both bodies hold Taiwan to be a province of China, I’m leaving the SQL as is with respect to Taiwan.

If you have a certain insight into the topic, or deal with those who may be sensitive to the issue, you might want to edit the SQL file such that Taiwan is listed simply as “Taiwan”.

If you’re looking for U.S. and Canada telephone area codes, try a site called areacodedownload.com.


More mail, more changes. I got a couple requests for non-upper case country names (like you’d use in text
or something. It’s not really an easy thing to do in SQL, so I added it to the perl script that makes the SQL
insert file. There’s now another column called ‘printable_name’ and it has the country names with their
proper capitalization. This seems kind of redundant to me, but it’s not a very big file, and not a very big
database table. Besides, the extra storage space needed by the ‘redundant’ column is probably preferrable
to the CPU overhead caused by making printable names in code or SQL at the time of the select.

I’ve been getting a lot of email recently and ask if I have the 3-letter and 3-digit codes for each country (this
is what is contained in ISO 3166-2).
ISO charges for 3166-2, and up until now I’ve just been grabbing the free 3166-1 list off their web site.
I did some
looking into it, and I found a place that has the extra codes, for free.

It turns out that ISO gets their country names from the
United Nations’ country list. Well, it’s really
pretty easy for me to get that info and correlate it. In fact, there’s a Perl module that helps make this happen.
The Geography::Countries module aims to give you the county names, the 2-letter codes, the 3-letter codes,
and the 3-digit numeric codes. The country names were slightly different than what ISO hands out,
but the two-letter
codes were the same. (I suspect that the module is slightly out of date, another reason why I want to keep
getting the data off the web.)
Because of this, and in the interests of backward compatibility, I decided to keep the ISO names.

As an aside, there are 12 countries (as of 5/20/03) that don’t have the ISO 3166-2 data.
Since the data are free,
the price is right for what I did manage to get.
Anyway, run SELECT name FROM
country WHERE iso3 IS NULL;
if you want to see which ones don’t have the 3-letter/digit codes.

I’ve updated the perl script to create a SQL file which includes the new 3166-2 info where available.

I’ve had a few people email me and ask if I had a similar SQL import file for
U.S. Postal Service state names and their
. I didn’t have an actual downloadable file, but it was made easily enough with mysqldump.
It’s linked up there at the top of the page. You use
it exactly like the country import file, and a select list can be made with only a little bit of jiggering to the
example code I’ve given below.

I did a little googling for such a file and couldn’t find much. Oddly enough, the ones that I did find were
incomplete since they didn’t have the Armed Forces “states” or territories/protectorates like Samoa and Virgin
Islands. Granted, probably not many people do business with those in Puerto Rico or the Republic of Palau, but
if you want to have a drop-down of U.S. states and you don’t provide the lesser-known ones you make it hard for
those people to use your site. This SQL file has the names and two-letter abbreviations for all the states that
the USPS considers “domestic”.


To import this into a MySQL database, just do like so:

mysql -u username -ppassword database_name < iso_country_list.sql

If you have create permissions on ‘database_name’, you’ll then have a table called ‘country’ which has all your country info.
You’d use this table in another table like so:

CREATE TABLE register (
  name VARCHAR(255) NOT NULL,
  address1 VARCHAR(255) NOT NULL,
  address2 VARCHAR(255),
  address3 VARCHAR(255),
  city VARCHAR(150) NOT NULL,
  state VARCHAR(100),
  zip VARCHAR(20),
  country_iso CHAR(2) REFERENCES country (iso)

Then you can do selects and such against all the tables. The table above is purely hypothetical, by the way. I made it
just now off the top of my head, so you’ll probably want to use something which is better tailored to your specific needs
(phone number, two-character states, indexes for faster selects with ‘where’ clauses, etc).

Some code also might come in handy. Here’s a snippet of PHP which will make an HTML select list from all the countries
listed in your database:

@ $db = mysql_pconnect($hostname, $dbusername, $dbpasswd);
if (!$db) {
    print "Failed to connect to the database.  Please try again later.\n";
$sql = "select id,name from country order by iso";
if (!(@ $result = mysql_query($sql))) {
    print "There was an error running your query:<p>\n". $sql . "<p>\n";
print '<select name="country"><br>\n';
print '<option value="">  Choose One   ';
while ($row = mysql_fetch_row($result)) {
    $country_iso   = $row[0];
    $country_name  = $row[1];

    print "<option value=\"$country_iso\"";
    if ($_REQUEST["country"] == $country_iso) { print " selected"; }
    print "> $country_name <br>\n";
print '</select>\n';

Obviously, you’ll have to supply all the connection variables and such. This code is useful for PHP scripts which
call themselves, by the way. It checks the incoming $_REQUEST array for value for the ‘country’ element and if it
finds one which matches the value stored in the database, then it makes that choice selected. This is handy if you
do error checking on your scripts. I usually check for required fields and if one is not found, I just call the
PHP bits which made my form initially. By “keeping” the original values, the form elements will be set to what they
were when the form was first filled out. It’s a nice feature and good code re-use. Oh yeah, your script can also
check to see if the country has been left blank, since the “Choose One” option has an explicitly empty value. Without it,
the choice would literally be “Choose One”.

One more side effect of this snippet is that the value of the options in the select list will be the id number of
the country. This is (mostly) good, because when you go to insert the form contents into the database, you simply insert
this numerical value in your main table (the ‘country_id’ field in my pretend table above). This avoids having to
look up the numerical code of a two-letter code or a country name and insert that. It’s one less trip to the
database, and so quick and handy. (Although it presents a race condition which may make the choice of convenience
one you don’t want to make: if something updates the table between the time the user loads the
initial form and when they submit the form, they might be submitting the wrong id number.)
When you do selects on the ‘register’ table, you just do a plain natural join on the country table,
like so:

select applicant.name,city,country.name
from applicant,country
where country_id=country.id and country.iso='my';

select applicant.name,city,country.name
from applicant,country
where country_id=country.id and country.name='Malaysia';

Those queries will do the same thing: find the name, city and country name for all the registrants from Malaysia. The
first one uses the country code (good if looping through like from an array of ISO codes or something) and the second
is by canonical country name (good if you’re doing something like giving someone a web-based form with a select list
of country names — although you could use the code snippet above to access the id numbers directly).

If you wanted to do this with Perl or Python, the concepts are identical, BTW.

January 8, 2010 Posted by | Helpful Tips and Tricks, MySql | , , | 1 Comment

The Ternary Operator – Working same as If-Else

We know, in programming there are three operators named Unary Operator , Binary Operator and Ternary Operator.

Operator’s name itself says that if it is a Unary Operator(e.g. Increment – Decrement operators) than it will take only one operand, If it is Binary operator(e.g. Relational operators) than it will take two operands and if it is Ternary operator than it will take three operands.

As discussed above, Ternary operator takes three operands – a condition, a result for true, and a result for false. It works similar to IF statement. Ternary operator will compact the 4-5 lines of code(IF statement) in to single line. This makes a difference when you will work with big application and writing thousand lines of code.

Look at below links for solutions.

Look at the below example of IF condition code in PHP.


echo “$a is greater than $b”;
echo “$b is greater than $a”;

Now same thing can also be done by Ternary operator.

echo $a>$b ? “$a is greater than $b” : “$b is greater than $a” ;

To know more about programming,MYSQL database,php info,php editor,programming php,Open-source,php help and php script , subscribe to our feed by entering email address below. You will get updates via email about every tutorial posted on this site . It will not take more than a sec.

January 3, 2010 Posted by | Helpful Tips and Tricks | , | Leave a comment

Merging Arrays with Reindex and without Reindexing

Hello Friends,

All we know about array_merge(param1,param2) array function in PHP. It may be possible that some begineers didn’t come across this function. For those people, array_merge(param1,param2) will merge two arrays and reindex all elements in array.


   $merged_array = array_merge($firstarray,$secondarray);


Above code will merge both array ($firstarray and $secondarray) in $merged_array and reindex all element starting from zero index.

But there are some cases in which you need to keep the same indexes(preserve numeric keys) of this arrays in newly created merged array. For this situation you can’t go for array_merge function. You can simply use ‘+’ operator and it will append both arrays without reindexing elements.


   $merged_array = $firstarray + $secondarray;


This are the two ways in which you can merge two arrays with reindexing and without reindexing.Look at below links for solutions.

To know more about programming,MYSQL database,php info,php editor,programming php,Open-source,php help and php script , subscribe to our feed by entering email address below. You will get updates via email about every tutorial posted on this site . It will not take more than a sec.

January 3, 2010 Posted by | Helpful Tips and Tricks | , | Leave a comment

How to remove index.php from url using .htaccess (mod_rewrite)

For better SEO optimization and make urls more search engine friendly , remove index.php from URL and make it easier to read.

This can be done by writing only two lines in your .htaccess(mod_rewrite in apache) file. Before writing this rule in .htaccess , make sure that your mod_rewrite is enabled(On) in your apache server. Most probably mod_rewrite is enabled in Linux server but for windows server , you need to contact hosting people to make mod_rewrite enabled. You can check this by looking in phpinfo().

Below is the Rules which will remove index.php from URL using .htaccess. Look at below links for .htaccess rules.


RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /index.php HTTP/

RewriteRule ^index.php$ http://www.%{HTTP_HOST}/ [R=301,NS,L]

Redirect 301 means Moved Permanently so most search engines will remove index.php from URL.

To know more about programming,MYSQL database,php info,php editor,programming php,Open-source,php help and php script , subscribe to our feed by entering email address below. You will get updates via email about every tutorial posted on this site . It will not take more than a sec.

January 3, 2010 Posted by | Helpful Tips and Tricks, htaccess | , , | 1 Comment

For vs Foreach – Difference between For and Foreach

You must familiar with all loops if you are a programmer/developer. There are so many loops available and you can select appropriate one when you develop an application. I found For and Foreach loops almost same. I googled for finding the difference between For and Foreach(For Vs Foreach) but didn’t get any clear idea. Here i am sharing my knowledge about some of difference between For and Foreach loop.

For can be used to run statements for a fixed number of times, foreach can be used to run statements for dynamically generated arrays(may be result of database query).We can also used for loop for dynamically generated array(may be result of database query) but foreach is the ideal way to iterate dynamic array. The reason behind this, we don’t know the index of array as it may be associate result from database query. So if we use foreach than it will iterate the result one by one.

Look at below links for more results.

Foreach will works only and only with arrays.For will works for any logical operation and i will continue until given condition fails.There is not much execution time difference. They works almost same way and same speed as foreach loop will takes time for getting next element while iterating array while for loop will takes time to re-initialize the variable.

In Summary, For loop can be more optimized if we know the count of array and index of array while foreach is better when we have dynamic array without knowing index of array and size of an array.

To know more about programming,JavaScript issues,jQuery,Expression Engine,MYSQL database,php info,php editor,programming php,Open-source,php help and php script , subscribe to our feed by entering email address below. You will get updates via email about every tutorial posted on this site . It will not take more than a sec.

January 3, 2010 Posted by | Helpful Tips and Tricks | | Leave a comment