February 14, 2010

this blog is dead

The title pretty much says it all. After months of writing "i-code-today" a.k.a "daily coding blog", I am closing down shop and shifting to a hosted wordpress blog. My new blog address is http://blog.raysourav.com


(c) Sourav Ray Creative Commons License

January 4, 2010

The PHP Array Project : Lost and Found

Last year January I read an article at http://debuggable.com with title "Donate your PHP arrays!". In that article Felix Geisendörfer has asked all opensource enthusiasts to donate some useful lists of data in php array format. No doubt it's a noble idea, but after almost one year I found it's too difficult to find the project on google search page. Anyway I found it finally because luckily I remember the blog name. No!! I don't want to lost the links again.

Here are the useful links:
The original blog post
The project
Download project




(c) Sourav Ray Creative Commons License

September 14, 2009

Opera 10 rocks the Acid Test 3

Yesterday night I have downloaded the latest version of opera. The browser has great look (I mean the new cool UI), lots of goodies and is as reliable as its preceding versions. I was more inquisit to see how it will perform in Acid Test 3. FireFox 3.5 does really well with an impressive 93/100 score and I expect Opera 10 to perform similarly, but it stunned me with a 100/100 score.
O dear! that's why I Love Opera.


(c) Sourav Ray Creative Commons License

May 28, 2009

FTP but no SCP. WTF!

Today my hosting provider (Yes I am going to start a new blog at http://raysourav.com) told me that he can provide me FTP access but not any SCP access when I have access to the jailed shell.

"Dear hosting service provider , this is really ridiculous .I guess you don't understand what security means!"


(c) Sourav Ray Creative Commons License

March 11, 2009

Calculating Week of the Month from a given date [ PHP ]

Let first understand the problem. In the following fig. we have 2 months calendar of March 2009 to April 2009.

Now 31st March and 1st April, both dates belong to 14th Week of the Year, but in Week of the Month Calculation 31st March will be 5th Week of March and 1st April will be 1st Week of April. There is no such format is available for PHP date() function , so we will calculate the Week of the Month Programmatically.

Test Case: the program should return 1st week of March and 2nd Week of April respectively for given dates (dd/mm/yyyy) 07/03/2009 and 07/04/2009.

The Week of the Month can be determined by following equation










We can implement the equation in a PHP function as bellow

function getWeekOfTheMonth($dateTimestamp)
{
$d = date('j',$ dateTimestamp);
$w = date('w',$ dateTimestamp)+1; //add 1 because date returns value between 0 to 6
$dt= (floor($dayOfMonth % 7)!=0)? floor($dayOfMonth % 7) : 7;
$k = (($w-$dt) < style="">
$W= ceil(($dayOfMonth+$k)/7);
return $W ;
}

Now check the function with Test Cases.
For 07/03/2009 or 7th March 2009:
$dateTimestamp = mktime(0,0,0,3,7,2009);
echo getWeekOfTheMonth($dateTimestamp) ." week of ".date(F,$dateTimestamp);

and the o/p is
1 week of March
For 07/04/2009 or 7th April 2009
$dateTimestamp = mktime(0,0,0,4,7,2009);
echo getWeekOfTheMonth($dateTimestamp) ." week of ".date(F,$dateTimestamp);

and the o/p is
2 week of April


(c) Sourav Ray Creative Commons License

February 20, 2009

Singleton Class, Object Cloning and Object Foreach

After the lunch we (Anand, Avlesh, Jaimin, Ashish, Aakash and yours truly) have a light hearted discussion about object and classes. We were wandering if we can clone a singleton class object? Obviously we all differ with others opinion and finally draw the same conclusion that logically you can clone a singleton class object. This is something disappointing for programmer like me who loves to write singleton class to implement single access point, but thankfully in php generally we are not sharing anything between two processes so the threat is really less.

Returning to my desk I wrote a small script to verify my understanding.

class SimpleClass

{

public $var3 = 1;

public function __toString(){

return strval($this->var3);

}

}

class TestSingletonCloning

{

static $classInstance;

public $var1;

public $var2 = 'value 2';

private function TestSingletonCloning()

{

$this->var1= new SimpleClass();

$this->var2 = 'value 2';

}

public static function init()

{

if(!isset(TestSingletonCloning::$classInstance) || empty(TestSingletonCloning::$classInstance) )

{

TestSingletonCloning::$classInstance = new TestSingletonCloning();

}

$inst = & TestSingletonCloning::$classInstance;

return $inst;

}

}

$obj1 = TestSingletonCloning::init();

$obj2 = TestSingletonCloning::init();

$obj3 = clone $obj1;

$obj3->var1->var3 ++;

$obj3->var2 = 'value 3';

var_dump($obj1);

var_dump($obj2);

var_dump($obj3);

After executing the piece of code I got result like following

object(TestSingletonCloning)#1 (2) {
  ["var1"]=>
  object(SimpleClass)#2 (1) {
    ["var3"]=>
    int(2)
  }
  ["var2"]=>
  string(7) "value 2"
}
object(TestSingletonCloning)#1 (2) {
  ["var1"]=>
  object(SimpleClass)#2 (1) {
    ["var3"]=>
    int(2)
  }
  ["var2"]=>
  string(7) "value 2"
}
object(TestSingletonCloning)#3 (2) {
  ["var1"]=>
  object(SimpleClass)#2 (1) {
    ["var3"]=>
    int(2)
  }
  ["var2"]=>
  string(7) "value 3"
}

It is a desired result that I got. Hurrah!!! We have successfully cloned the object of the singleton class. As object Cloning bypasses the constructor call by replicating the object map ( or what ever lies beneath your object)

In PHP the cloning is a shallow copying by default like most of OO languages. So the cloned object points to the same object referred by $val1.Any modification in $var1 of clone Object will affect the object referred by $var1 of the original Object. If desire to change this behavior implement deep copying logic in the magic method __clone of the singleton class. That definitely not solves the problem of having multiple object versions of a singleton class. If you like to stop developer to clone your singleton class, you can throw an exception within __clone function .

Now going by the definition of PHP foreach the last solution, suppose to fail you if you try to iterate over the singleton object using a foreach outside of the class. But it will not, because your object which is supposed to be cloned before iteration, is actual shallow copied via an implementation other than Cloning. So the copying process never calls the __clone method of you singleton class . Try this out before dumping all…

foreach($obj1 as $key => $value) {

if($key=='var1')

$obj1->var1->var3 ++;

echo "$key => $value
";

}

Finally some relief for my soul.



(c) Sourav Ray Creative Commons License

February 17, 2009

Favicon for I-Code Today


As this blog is gaining popularity (average 240 unique users per day form 11th Feb ), I thought now it should have an unique Favicon .
I tried to keep the color pallet inline with the blog color.

Dear Readers... do I have to say .. "I am looking for your feedback!". Thank you guys.. for visiting this blog :)


(c) Sourav Ray Creative Commons License

February 11, 2009

PHP array, foreach loop with references and no block-scope – a killer recipe

Today morning I was browsing through my collection ridiculous php bugs ( I have 20+ such code snippet now) and my eyes got stuck to this problem. I cannot remember from where I got this one but surely it’s a jewel in my collection.

Let give a look to the original code
<?php

   $arr = array('A', 'B', 'C', 'D', 'E');
   foreach ($arr as &$val) {}
   foreach ($arr as $val) {}
   var_dump($arr);

?>

The problem is that the var_dump gives a result

array(5) {
  [0]=>
  &string(1) "A"
  [1]=>
  &string(1) "B"
  [2]=>
  &string(1) "C"
  [3]=>
  &string(1) "D"
  [4]=>
  &string(1) "D"
}

Shocked! Aaha… who screwed up your array? Apparently it’s your references
and variable scopes. You get it right but you will be biased if you don’t
criticize the lack of block-scope in php.
In the first foreach block we are assigning reference of the each element
to $val. Thus at the end of the first foreach loop $val actually a reference
to the final index of array $arr.
Now as there is no concept of block-scope in php, the $val will retain the
reference to the final index $arr at the start of the second loop (pathetic!).
 We can simply represent the situation as bellow

<?php

   $arr = array('A', 'B', 'C', 'D', 'E');
   $val = &$arr[4] ;
   foreach ($arr as $val) {}
   var_dump($arr);

?>

Now doing a var_dump of $arr inside the second foreach loop gives us the
following result.
array (
  0 => 'A',
  1 => 'B',
  2 => 'C',
  3 => 'D',
  4 => 'A',
)

array (
  0 => 'A',
  1 => 'B',
  2 => 'C',
  3 => 'D',
  4 => 'B',
)

array (
  0 => 'A',
  1 => 'B',
  2 => 'C',
  3 => 'D',
  4 => 'C',
)

array (
  0 => 'A',
  1 => 'B',
  2 => 'C',
  3 => 'D',
  4 => 'D',
)

array (
  0 => 'A',
  1 => 'B',
  2 => 'C',
  3 => 'D',
  4 => 'D',
) 
So it is clear now the second foreach loop actually assigns value of
each index one by one to the index referred by $val (final index).
 Now try out this solution 

<?php

   $arr = array('A', 'B', 'C', 'D', 'E');
   foreach ($arr as &$val) {}
   unset($val);
   foreach ($arr as $val) {}
   var_dump($arr);

?>

IT WORKS :)

(c) Sourav Ray Creative Commons License

January 30, 2009

Sending mail Attachment(s) with PHP mail function (PART - II) : The Code

In my previous post we saw the thumb rules for emailing using php mail function. Now we will implement those rules in code.

I have written a function sendMail, which receives mail subject, message, senders email id and destination id. I also accept three optional parameters, namely cc, bcc and attachment file list. The function prepares appropriate mail headers and call mail function to send mail via SMTP server. The function returns true for mailing success and otherwise it will return false.


function
sendMail( $subject, $message, $from, $to, $cc=null, $bcc=null, $attachment=null)

{

$headers = 'From: '.$from."\r\n";

if(!is_null($cc)){

$headers .= 'Cc: '.$cc ."\r\n";

}

if(!is_null($bcc)){

$headers .= 'Bcc: '.$bcc ."\r\n";

}

$headers .= 'MIME-Version: 1.0'."\r\n";

if(is_array($attachment) && count($attachment)>0){

$headers .= mailAttachmentHeader ($attachment, $message);

} else {

$headers .= 'Content-type: text/html; charset=iso-8859-1'."\r\n";

}

if(is_array($attachment) && count($attachment)>0){

$message = '';

}

$mailStatus = mail($to,$subject,$message,$headers);

echo "\nNew Mailer\n";

if($mailStatus){

return true;

}else{

return false;

}

}


In mail function "Form ", "Cc " , "Bcc", "'MIME-Version" set without checking if attachment is present or not – Rule 1.

Next we check is if attachments are present.
In case of no attachment we set 'Content-type: text/html; charset=iso-8859-1'."\r\n" Rule 2.a. Otherwise we call the mailAttachmentHeader function to prepare the attachment header

The massage is set to blank Rule 3.b.

function mailAttachmentHeader($attachment, $message )

{

$mime_boundary = md5(time());

$xMessage = "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"\r\n\r\n";

$xMessage .= "--".$mime_boundary."\r\n\r\n";

$xMessage .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";

$xMessage .= "Content-Transfer-Encoding: 7bit\r\n";

$xMessage .= $message."\r\n\r\n";

foreach($attachment as $file)

{

$xMessage .= "--".$mime_boundary."\r\n";

$xMessage .= "Content-Type: application/octet-stream; name=\"".basename($file)."\"\r\n";

$xMessage .= "Content-Transfer-Encoding: base64\r\n";

$xMessage .= "Content-Disposition: attachment; filename=\"".basename($file)."\"\r\n";

$content = file_get_contents($file);

$xMessage.= chunk_split(base64_encode($content));

$xMessage .= "\r\n\r\n";

}

$xMessage .= "--".$mime_boundary."--\r\n\r\n";

return $xMessage;

}


Parameters passed to mailAttachmentHeader function are list of attachments and the functions returns headers string.

In mailAttachmentHeader function we set "Content-Type: multipart/mixed; bundary=\"".$mime_boundary."\"\r\n\r\n"; where value of $mime_boundary is the MD5 of current timestamp. Rule 2.b.

To denote starting of message and each attachment following code is added
$xMessage .= "--".$mime_boundary."\r\n\r\n"; Rule 3.b.

We add Content-type “text/html” for message and “application/octet-stream” for attachments – Rule 4

For each attachment we add "Content-Transfer-Encoding: base64\r\n"; Rule 5 and "Content-Disposition: attachment; filename=\"".basename($file)."\"\r\n"; Rule 6

At the end of the function we add "--".$mime_boundary."--\r\n\r\n"; to denote the end of attachment mail header Rule 7

Now you can use the send mail function to send mail with or without any attachment. Cheers!!

(c) Sourav Ray Creative Commons License

January 28, 2009

Sending mail Attachment(s) with PHP mail function (PART -I) : Rules Of Thumb

A few days ago I was writing a script that would send email with (or without) any number of attachments. I started googling for help and ended up with some code snippets that didn’t work. After spending few more frustrating hours debugging those scripts, I finally reached the solution (“Tank you! Anand, Kunal and Avlesh… for your suggestions”). The problem with those scripts was that they were missing some crucial pieces of mail header and it was really a daunting task to fix those bugs, because “trial 'n error” was the only option left. That’s why in this post I tried to formulate a set of rules to send mail using mail() function with or without any attachment.

The Rules:

  1. In the mail header few header elements (like "Form ", "Cc " , "Bcc", "'MIME-Version" ) will remain as it is, irrespective of the fact that the mail has any attachment or not.
  1. a. If a mail doesn't contain any attachment, then Content-type will be "text/html" (for html formatted mail) or "text/plain" ( for plain text mail) . Content-type should have an additional attribute "charset" to define character encoding of the message.

b. In case when mail consists of one or more attachments, Content-type will be "multipart/mixed". Content-type will also have an attribute called "boundary". The "boundary" attribute contains a unique signature which is use to denote the starting point of each message/attachment of the mail as well as the end of mail.

  1. a. In case of mail without attachment the message string should be passed to mail function as message parameter.

b. If mail contains one or more attachments, then the message and the attachment file contents will be attached to the header string, separated by a boundary notation

-- [boundary value]

the start message will also have similar boundary notation to denote the start of message and A blank string or null value should be passed to the message parameter of mail function.

  1. In multipart mail each message/attachment will have their own Content-type . For a multipart mail header the message will have Content-type "text/html" (for html formatted mail) or "text/plain" (for plain text mail). And attachment will have Content-type depending upon the type of content. If you are not sure about content use Content-type "application/octet-stream". For attachment content type Additional Attribute name can be use to denote the base name of the attachment file.
  1. Each attachment block also contain header "Content-Transfer-Encoding" to specify the content encoding
  1. Each attachment block will have Content-Disposition as "attachment" and attribute filename will denote the name of the downloaded file.
  1. After the end of all attachments there will be end of mail notation

--[boundary value]--



Note : To be on the safe side it is better to encode the attachment content to some standard encoding and set the Content-Transfer-Encoding as per the implemented encoding.

In the next Post we will see how to implement these Rules in actual code

(c) Sourav Ray Creative Commons License

January 22, 2009

PHP! Taking arguments from Command Line

Setting up Command Line Interface SAPI for php
In *nix environment:
Since PHP 4.3.0 the both --enable-cli and --enable-cgi are enabled by default. If a module SAPI is chosen during configure, such as apxs, or the --disable-cgi option is used, the CLI is copied to {PREFIX}/bin/php during make install otherwise the CGI is placed there. If you want to override the installation of the CGI binary, use make install-cli after make install. Alternatively you can specify --disable-cgi in your configure line.
In windows:
PHP 5, the CLI is distributed in the main folder, named php.exe. The CGI version is distributed as php-cgi.exe.


Now consider this CLI hello world programme
File: cli-hello-world.co
<?php
fwrite(STDOUT,"CLI hello world \n");
?>

To call this script from command line (we assume that php bin path is set in OS environment variable )

>_ php cli-hello-world.com

CLI hello world


To passing an argument to php script from command line is similar to C or Java. There are two global variables $argc and $argv, that hold an integer value of number of arguments passed and an array of sting value of the arguments respectively.
Note: if no additional parameter is passed then the arg variables only will contain the file name and the value of $argc will be 1

For example
File : cli-arg.php
<?php
if($argc > 1)
{
foreach ($argv as $argumentVariable)
fwrite(STDOUT, $argumentVariable. "/n");
}
?>

Now we can call this script like
>_ php cli-arg.php "Hello World"
cli-arg.php
Hello World

In PHP 5, the CLI version will always populate the global $argv and $argc variables regardless of any php.ini directive setting. Even having register_argc_argv set to off will have no affect in CLI.



(c) Sourav Ray Creative Commons License

" हेल्लो World "

Finally I have stared a blog that will keep an account to all my coding tricks. This was a long pending task since my previous blog was closed. My official blog is yet to be online, it is coming soon...


(c) Sourav Ray Creative Commons License