CSS Browser Compatibility

August 28, 2008

There is a great challenge for CSS Web Designer, that will be the CSS compatibility with browsers. This is due to some browser introduces their own CSS set which is not a common CSS recognized by all browsers. And some browsers is though claiming itself as web browsers but it does not even support all common CSS. May be budget issue or the developer does not have the skills to code into their browser to support it.

The one I respect most is the browser which are able to support all common CSS and do have its own additional set of CSS which enhances the web design for a neat and well organised look.

The one I will look down will be the browser which does not support all common CSS and ignoring web user requests by just telling the user that “This is xxx browser propriety which we do not support”. This is some how ridiculous. When a user giving this feed back, this means that this feature is usefull and the user are expecting that this CSS can be supported. Of course, if one or two users requesting, then it is not a commonly required. But if there is thousands or even millions requests, they should consider to do so rather than giving crap reason.

To be most benefits to users, an agreement or a body should be form to make sure that all the browser do support on all the CSS available no matter it is a proprietary or non-proprietary CSS. This is to make sure there is a standard are met.

Well, human is a very self fish creature where they reserved the best for themselves. This has drag down the unity of human world wide.

Enough for crap talking, below are some CSS that I have found which is having compatibility issue among browsers. I will update more when I came accross more:

Style Internet Explorer Firefox
word-wrap All No

Data Encryption via Mcrypt

May 13, 2008

Others than securing data using encoding such as base64, if you are good in ciphers, you may utilise the mcrypt encryptions instead for better data encryptions.

Mcrypt is the utilities where you can use it to encrypt the data with your own desirable ciphers for encryptions.

The most common ciphers used will be Rijndael, TwoFish, DES, TripleDES (3DES). To see what other available ciphers, you may refer to the follow url links:

http://my.php.net/manual/en/mcrypt.ciphers.php

Before start using mcrypt, please make sure that you have enable it for PHP. PHP by default is having this component/module disabled. For Linux, compile or recompile your PHP engine with “–with-mcrypt”. For Windows, enable it via php.ini by uncomment the line which contains “extension=php_mcrypt.dll”.

If you are compiling PHP as Apache module, please make sure that you restarted the apache service once the PHP finishes compiling with mcrypt.

Using mycrypt is rather simple if you have already understand how each function works and how the function call sequence.

The basic function which you will use for data encryption/decryption via mcrypt:

mcrypt_get_iv_size() function

mcrypt_get_iv_size ( string $cipher , string $mode )

mcrypt_get_iv_size() returns the size of the Initialisation Vector (IV) in bytes. On error the function returns FALSE. If the IV is ignored in the specified cipher/mode combination zero is returned.

cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

mode is one of the MCRYPT_MODE_modename constants or one of “ecb”, “cbc”, “cfb”, “ofb”, “nofb” or “stream”. The IV is ignored in ECB mode as this mode does not require it. You will need to have the same IV (think: starting point) both at encryption and decryption stages, otherwise your encryption will fail.

mcrypt_create_iv() function

mcrypt_create_iv ( int $size [, int $source ] )

mcrypt_create_iv() is used to create an IV.

Parameter size determines the size of the IV, parameter source (defaults to random value) specifies the source of the IV.

The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom). MCRYPT_RAND is the only one supported on Windows because Windows (of course) doesn’t have /dev/random or /dev/urandom.

mcrypt_encrypt() function

mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] )

mcrypt_encrypt() encrypts the data and returns the encrypted data.

Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

Key is the key with which the data will be encrypted. If it’s smaller that the required keysize, it is padded with ‘\0′. It is better not to use ASCII strings for keys. It is recommended to use the mhash functions to create a key from a string.

Data is the data that will be encrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with ‘\0′. The returned crypttext can be larger that the size of the data that is given by data .

Mode is one of the MCRYPT_MODE_modename constants of one of “ecb”, “cbc”, “cfb”, “ofb”, “nofb” or “stream”.

The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to ‘\0′.

mcrypt_decrypt() function

mcrypt_decrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] )

cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

key is the key with which the data is encrypted. If it’s smaller that the required keysize, it is padded with ‘\0′.

data is the data that will be decrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with ‘\0′.

mode is one of the MCRYPT_MODE_modename constants of one of “ecb”, “cbc”, “cfb”, “ofb”, “nofb” or “stream”.

The iv parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to ‘\0′.

The sequence of the function call for encrypting a data will be as below:

mcrypt_get_iv_size() >> mcrypt_create_iv() >> mcrypt_encrypt() 

The sequence of the function call for decrypting an encrypted string will be as below:

mcrypt_get_iv_size() >> mcrypt_create_iv() >> mcrypt_decrypt() 

The sample encryption and decryption are shown below:

function encrypt_data($keystr,$datastring)
{
   $iv
_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256,MCRYPT_MODE_ECB);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
   $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $keystr, $datastring, MCRYPT_MODE_ECB, $iv);
   return $crypttext;
}

function decrypt_data($keystr,$encryptedstr)
{
   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256,MCRYPT_MODE_ECB);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
   $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $keystr, $encryptedstr, MCRYPT_MODE_ECB, $iv);
   return $decrypttext;
}

Notes:
Programmers hate internet browsers. Why? This is due to the more variety the internet browser is, the more consideration they need to make when doing the codes to make sure that the codes are compatible with majorities of the browsers.

For MCRYPT, there is compatibility issue found with Firefox where you will see question mark “?” symbol appear when trying to display out the decrypted message.

To fix this, contact Mozilla to check on their browsers or boycott em’ :p. Just kidding.. to fix it, just simply use the trim() function to trim the decrypted message before display the value.

 You may click here to download the sample scripts for data encryption using mcrypt.

Basic Data Encryption via Base64

May 08, 2008

Security is important, especially to those application which deals with the sensitive data accross internet network. When a data is sent out from your computer, while it is on its way to the destinated terminal, it is exposed to the security threats which may either harm or sniff your data. If that is the case, precaution steps should be taken to minimized the possibilities of data stolen/sniffed.

You may utilize the available security options such as using SSL or Certificates. Another way will be done in the application it self where the data is already encrypted before sealed with SSL or certificate.

For PHP, you may utilize the most common base64 conversion to secure your data.

base64_encode() function

base64_encode ( string $data )

This function accept one parameter which will be a string value. The function encode the given string with Base64 and return the value back to the caller in string format.

Below are the sample on how the function is being used:

$myencrypteddata = base64_encode(”This is a sample string”);

base64_decode() function

base64_decode ( string $data )

This function accept one parameter which will be a string value. The function decode the given string with Base64 and return the value back to the caller in string format.

Below are the sample on how the function is being used:

$myencrypteddata = base64_encode (”This is a sample string”);
$myencrypteddata = base64_decode($myencrypteddata);

Using the string that passed by the base64_encode seems to be secure, but it is actually not. This is due to there are many web tools available online which enable you to decode the encoded string. For example:

http://makcoder.sourceforge.net/demo/base64.php
http://base64-encoder-online.waraxe.us/

In order to have the data secured, you may form your own security algorithm by using base64 functions. There is a simple hint which you may refer:

  1. Add some alphabet into certain position of the data
  2. Encode it with base64_encode() function
  3. Add some alphabet into certain position of the string returned from the base64_encode() executed on option (2).
  4. Encode it with base64_encode() function again
  5. You can use the string returned from the base64_encode() funtion executed on option (4)

The above is the steps that you will need to encode/encrypt the data. You will need to know how to reverse it so that you can get back the raw data. The encoding will be rather simple if you understand your encoding algorithm. By referring to the above hints, the encoding is just a reverse steps start from (5) back to (1).

Practice will makes you understand more. You may download the sample source code here for further study and understand on the base64 functions.

Managing Folder with PHP

May 07, 2008

PHP programming allows directory management where you can list contents of the folder and create or delete a folder. The PHP function that can be used are as below:

  1. dir() : return a directory class which contains information about the folder specified
  2. mkdir() : creates a new directory
  3. rmdir() : deletes a directory

dir() function

This function accept one parameter which will be the folder path which you wish to check on the contents or folder propeties. This function returns a class which do have some function in it that is :

  1. rewinddir() : resets the folder content pointer to the beginning
  2. read() : read the folder contents one by one upon execution
  3. close() : close the folder object

Sample script are shown below:

$mydir = dir(”/this/is/the/folder/path”);
echo “Path: ” . $d->path . “<br>”;
while (false !== ($entry = $d->read()))�
{
     echo $entry.”<br>”;
}
$d->close();
echo “<br>”;

mkdir() function

This is used to create a folder by using the name/path specified. This function returns boolean values where TRUE is successfully created and FALSE is otherwise.

The sample script are as below:

mkdir(”newfolder”);
mkdir(”/this/is/newfolderpath”);

If you are using path, you will need to make sure the new folder parent directory exists. The function will not create the folder if the specified parent folder is not valid.

rmdir() function

This is used to delete a folder by using the name/path specified. This function returns boolean values where TRUE is successfully deleted and FALSE is otherwise.

The sample script are as below:

rmdir(”newfolder”);
rmdir(”/this/is/newfolderpath”);

You may download the sample script here.

PHP Date Calculation

May 07, 2008

It is interesting when comes to the topic on calculating the date difference between two given date.  The easiest and most straight forward method will be :

  1. Convert both date into seconds since Unix EPOCH (January 1 1970 00:00:00 GMT)
  2. Do the calculation by using simple arithmethic “-” calculation.
  3. Convert the differences back to number of days

Convert Date into Seconds since Unix EPOCH

To convert it you may either use date() function by passing “U” to its first parameters. Or, you may consider to use mktime() function. Use the date() function when you plan to to capture the seconds of the current date or if you do have a timestamp ready to be passed to the second parameters.

If you wish to do calculation from the data posted from the HTML forms, I would suggest that you use mktime() and explode().

Use explode() function to extract out the day, month, and year into a single array storage. Then use mktime() function to create a Unix timestamp (in seconds) for both date.

Convert the differences back to number of days

Once you have done the calculation of the difference between date using arithmathic calculation, the results will be seconds. To convert to number of days, you will need to do conversion by using normal time conversion algorithm where:

1 day = 60×60x24

Converting to number of months or years may be challenging. You may consider to fix that 1 month is 30 days and 1 year is 365 days to ease your work.

Assume that $date1 and $date2 is the variables posted from the HTML form, below are the sample scripts:

$date1 = “1-1-2008″; //using dd-mm-yyyy format
$date2 = “5-1-2008″; //using dd-mm-yyyy format

$date1 = explode(”-”,$date1);
$date2 = explode(”-”,$date2);

$date1 = mktime(0,0,0,$date1[1],$date1[0],$date1[2]);
$date2 = mktime(0,0,0,$date2[1],$date2[0],$date2[2]);

$datedifference = $date2 - $date1;

echo(”This difference of the date are “.$datedifference/(60*60*24).” days”);

 

You may click here to download the sample source.

Basic PHP and MySQL Connections

May 06, 2008

PHP Team have done a great job where the built-in function for MySQL database are awesome!! Thumbs up!! The functions are straight forward and easy to understand.

Defnitely this will not serve the positive results to all users especially those newbies who just starts their interest in PHP programming.

Hope the below hints may helps those who aren’t sure on how to conenct and query data from MySQL databse server via PHP scripts.

Before starts, get ready some information about the built-in php function:

  1. mysql_connect : used to connect to MySQL database. This will be the first function initiated before query the database.
  2. mysql_db_query : used to parse sql commands to the MySQL database for results
  3. mysql_fetch_array : get the data from the records row by row in array format
  4. mysql_close : close the connection to MySQL database server once the queries is done

mysql_connect() function

mysql_connect ([ string $server [, string $username [, string $password [, bool $new_link [, int $client_flags ]]]]] )

This function allows 5 parameters where 3 are normally used, that is $server, $username, and $password. From the name itself you know that this is something relates to the database server login information where:

  1. $server : mysql server hostname or IP address
  2. $username : username to login to MySQL database server which is having over the queried database
  3. $password : password for the username mentioned on option “2″

This functions returns link identifier which will be used by the mysql_db_query() function or return FALSE if the connection fails.

The sample mysql connect are as below:

$connlink = mysql_connect(”localhost”,”myusername”,”mypassword”);

mysql_db_query() function

mysql_db_query ( string $database , string $query [, resource $link_identifier ] )

This function by the name itself shown that it has to be related to database query. The function itself cannot query the database if there is no information passed to this function. It will be like you are asking people a favor to get a pair of sock ( data ) of your preference inside a room without stating exact location ( which database or table ) of the socks and what is your preferences (queries).

This function accepts three parameters which will be :

  1. $database : database name that you are going to query from
  2. $query : your sql statements
  3. $link_identifier : tells the function which connection that it should refer. This will be the link identifiers returned by the mysql_connect() function

This function will return Positive MySQL results of the query or FALSE if the query fails.

The sample function used are as below:

$dbresults = mysql_db_query(”mydbname”,”select * from userlogins”,$connlink);

mysql_fetch_array() function

mysql_fetch_array ( resource $result [, int $result_type ] )

This function is to grab data from the MySQL results row by row upon execution. This means that this function will grab data on the first row of records on its first execution, second row of records on second, and so on..

This function allow two parameters where the common parameter passed to the function will be $results which is a compulsory field. This parameters tells the function which MySQL results should it grab the data from. This MySQL result will be from the result returned by the mysql_db_query() function.

This function will return data in the form of array where table’s field name are used as the array index.

Examples:

If the table contains fieldname “username”, the array storage will be either array[0] or array['username'].

If the table contains more than 1 field, like “username” and “password”, the array storage will be mapped as below array style:

array[0] = array['username']
array[1] = array['password']

If you are using integer index for array on data as mentioned as above, please be extra cautious. The Integer index is based on the table field name arrangement in the table when you creates the table. If you are unsure on your field arrangement, you may use the following sql command to check on it:

show fields from tablename;

The field name will be shown in arrangement from top to bottom.

The sample function call are as below:

$dbdata = mysql_fetch_array($dbresults);

If your query returns more than one records, you may consider to use while() loop to query until the function returns FALSE which indicates the end of the records.

mysql_close() function

mysql_close ([ resource $link_identifier ] )

This function is used to close the mysql connection made earlier by mysql_connect() function by using the link_identifier as the reference for the function to know which connection to be closed. This function is recommended to be used together with the mysql_connect to make sure that there is no unused connection is open.

This function returns TRUE if the connection closed successfully or FALSE otherwise.

The sample function call are as below:

mysql_close($connlink);

You should be wondering which function should comes first and which is later. Here is the hints:

mysql_connect() -> mysql_db_query()-> mysql_fetch_array()-> mysql_close()

That will be :

$connlink = mysql_connect(”localhost”,”myusername”,”mypassword”);
$dbresults = mysql_db_query(”mydbname”,”select * from userlogins”,$connlink);
$dbdata = mysql_fetch_array($dbresults);
mysql_close($connlink);

I believe that you are not going to query data once and it will be very long is you keep on pump this 4 lines whenever there is a database query needed. To have a better management, you may consider to create your own custom function to query on the database.

For example:

function myowndbquery($sqlcmd)
{
$connlink = mysql_connect(”localhost”,”myusername”,”mypassword”);
$dbresults = mysql_db_query(”mydbname”,$sqlcmd,$connlink);
mysql_close($connlink);
return $dbresults;
}

Of course this is just a basic idea for custom function. You may need to include error checking with if else statement for better error handling or logging.

I have developed a sample script which may helps you. Click here to download.

MySQL Basic Commands

April 15, 2008

MySQL database server it self supports bunch of common SQL commands which can be utilise for data mining. If you wish to build up a web application which uses MySQL database to store data, you will need to familiarize the following 7 sql commands which I categorize it as “Basic SQL Commands”:

  1. SELECT
  2. UPDATE
  3. INSERT
  4. DELETE

SELECT Query

Select command is used to read data from the database. Before running SELECT query, you need to know which table name and table fieldname (if you wish to display specific field in the table instead of all). MySQL do support on wild card (*) for field name. Wildcard represents a shortcut for to display all field in mentioned table.

Below are the basic SELECT command:

SELECT <field_name>|* FROM <table_name>

Eg:
SELECT username,password from user_details

Explanation:
This SELECT query is trying to read record from the table named “user_details”. This query will display two field which is “username” and “password”.

Update Query

Update command is used to update existing data in the database. Before running UPDATE query, you need to know which table name and table fieldname to be updated. UPDATE query always comes in pair with the WHERE clause to make sure that the correct record is being updated.

Below are the basic UPDATE command:

UPDATE <tablename> SET <fieldname>=<value> WHERE <fieldname>=<value>

Eg:
UPDATE user_details SET password = “1234556″ WHERE username = “vickson”

Explanation:
This UPDATE query is trying to updates all existing record in the database if the record is having field “username”’s value equal to “vickson”. If the WHERE clause is being stripped off, this will apply to all records in the user_details table which ends with all the record’s password field value is “1234556″.

INSERT INTO Query

This INSERT INTO query is used to insert data into the database. There are two ways to write INSERT query that is :

INSERT INTO <tablename> (<fieldname1>,<fieldname2>,..) VALUES (”data1″,”data2″,…)

OR

INSERT INTO <tablename> VALUES (”data1″,”data2″,…)

Eg:
INSERT INTO user_details (username,password) values (”vickson”,”1234556″);

INSERT INTO user_details values (”vickson”,”1234556″);

Explanation:
This INSERT query is trying to insert data into user_details table with “vickson” as username and “1234556″ as password.

Notice that the second INSERT query do not specify the fieldname, the MySQL will match the values provided according field orders during the table creation.

DELETE Query

By the query name it self, you know this query is to delete a record in the table. Similar to UPDATE query, this DELETE query is recommended to be executed with WHERE clause to make sure you deleted the correct record.

Below are the basic DELETE command:

DELETE FROM <table_name> WHERE <fieldname>=<value>

Eg:
DELETE FROM user_details WHERE username = “vickson”

Explanation:
This DELETE query is trying to delete record in the table which is having username field value as “vickson”. Notice that, if the WHERE clause is being stripped off, this will mean that to delete all records in the user_details table.

By understanding these 4 query commands, there is no problem for you to code simple/basic php application with mysql database. However, you may need to use a more complicated sql queries depends on how complicated is your php application.

Security Enhancement via Images

April 13, 2008

To have a better security over your website form, especially on the email forms, you may include security code via Images feature where the user is required to enter the security code shown in the images before they can submit the data.

This will be more secure using image than you just provide security code in string format, users with a little knowledge about programming can easily extract the security codes from the html output.

This security code can be easily coded in PHP scripts using GD Library and PHP Session. To have a better understanding, click here to download the sample script. I have split out my sample script into 3 main files:

1. image.php >> Generate random security codes and output the code in image format

2. index.php >> provide a simple form for user to enter the security code by referring to image.php output

3. process_code >> validate the security codes entered by user.

Selective Hostname Redirections

April 12, 2008

Some of the web hosting do provides domain aliases service such as Exabytes Network. It will be kinda waste if the aliased domain showing the same output as the parent domain.

When having aliased domain sharing the same default page, some work need to be done if you want specific domain to be redirected to other location or path such as :

http://www.oldcoconut.com/ => http://www.yahoo.com/

OR

http://www.oldcoconut.com/ => http://www.oldcoconut.com/any_folder_or_filename

If you are good in php or even with a novice php skill, with some hint from the php manuals, you still can start coding the selective redirection.

Simple selective redirection using php script will involve two component, server variables and header() function. The server variable involved will be SERVER_NAME.

Sample script of selective redirection are as below:

$myHostname = “oldcoconut.com”;
$myHostRedirect = “http://oldcoconut.com/sample“;
if($myHostname==$_SERVER[’SERVER_NAME’])
{
  header(”Location: “.$myHostRedirect);
}

If you do have multiples aliased domain which you wish to have them redirected to other location or folder, you may consider on using arrays to keep the domain and its redirection URL.

If you still want to preserve the domain name on the URI Address, you may consider on using frame to hide the redirected url.

You may refer to the below sample script for further references:

selective_hostname_redirection.zip

PHP Register Globals

April 12, 2008

Well, I do came accross many programmer who is coding their php script using global variables rather than using predefined variables $_POST or $HTTP_POST_VARS to process the data posted from html forms.

Though using global variables is good on code simplification and better understanding while doing the script, it will leads to security threads over their website script if it is not well scripted.

Exploits such as http injection will be the common security threats on users who deals with global variables form processing.

Others than the security threats, this method is a dependent method where it relies on register_globals settings in php.ini which might be disabled by various hosting providers for security purpose.

You may try at your own by setup two different form processing script. One is using global variables and another is using $_POST or $HTTP_POST_VARS for form processing. Try both script at the same time by turning register_globals off and on to see the results.

Of course if you are using Apache server with PHP, you can still enable the register_global for domain wide by include the following string into the .htaccess file:

php_flag register_globals on/off

May be you may have a try the same script using the same test script (without modifiying the content) on IIS. You will end up scratching your heads on the script modification to suit the IIS environment which is having register_globals turn off or develop/search third party tools to provide feature where you can have the register_globals to be turn on.

If you want your life to be easy, start coding your script using $_POST or $HTTP_POST_VARS rather than global variables. You will tell your client/boss “Yes, no problem!” when they plan to switch webserver with register_globals turned off or even plan to turn off the register_globals on the existing webserver.