Pages

C3 Health Services

Visit Official Website 9278982994

Expert Healthcare at Your Doorstep

Friday, 4 January 2013

Bad Programming Practices: Never write your application business logic in eventhandlers

Bad Programming Practices: Never write your application business logic in eventhandlers

Writing your application business logic in eventhandlers is a bad programming practice. By doing this, you are mixing your design and logic and making your application more prone to disasters. No doubt your functionality will work fine, but when your senior sits to do your code review, s/he will reject your code. I am trying to explain it by simple delphi example. I will be using 2 methods to implement same functionality.

Method 1:

In the following delphi XE2 example, application logic is written on the click event of OK button. It means when from user interface, user clicks the OK button the application logic will run.

procedure Form1.btnOKClick(Sender: TObject);
begin
  //my application business logic goes here
end;

This application logic can be run by clicking on OK button or just by calling the event handler in your delphi program like following:

btnOK.click; or
btnOKClick(Self.btnOK);

Method 2:

In following delphi XE2 example, same thing is done but in different way. Application logic is written in some delphi function "ApplicationLogic" and is called from the event handler (click of OK button).

procedure TForm1.ApplicationLogic;
begin
 //my application business logic goes here
end;

procedure TForm1.btnOKClick(Sender: TObject);
begin
 ApplicationLogic;
end;

Method 2 is better approach as it encapsulate your actual business logic. by using this approach, you can separate your design logic from application logic and your code will be neat and clear and easy to understand. Your code will be self documented.

Also, directly calling event handlers from program (as in method 1) is quite complex which degrades the performance when your application will grow large.

You can make your code reusable by putting your application logic in some library and then calling the methods of that library from event handlers as well as from other places. Even you can use same methods in some different application by just including that library which contains all your application logic functions. 

Thursday, 3 January 2013

How to Generate Thumbnail Image with Rounded Corners using PHP Script?

How to Generate Thumbnail Image with Rounded Corners using PHP Script?

Thumbnail Images with rounded corners are very common. You might see images with rounded corners on various websites when you browse around the web. If you are a PHP developer, generating Thumbnail Images with Rounded Corners is very easy using PHP script. There are lot of libraries available in PHP which will help you generating thumbnail images with rounded corners.

We are going to use simple PHP script library called phpThumb() to generate thumbnail images with rounded corners. phpThumb() uses the GD library to create thumbnails from images (JPEG, PNG, GIF, BMP, etc) on the fly. The output size is configurable (can be larger or smaller than the source), and the source may be the entire image or only a portion of the original image.

Following is the step by step demonstration on how to generate thumbnail images with rounded corners using PHP script?

Step 1: Download phpThumb() library from Sourceforge:


Extract the file and keep it in your Library Folder or wherever you want in your application folder.

Step 2: Now use the above library in the img tag of your images like this:

<img src="phpThumb.php?src=myImage.jpg&w=200&h=150&fltr[]=ric|20|20&f=png" />

Explanation of above img tag attributes:

1. src is the relative path to image file to phpThumb.php

2. w & h are width and height of the resulting thumbnail

3. fltr is used to tell phpThumb to generate rounded corner thumbnail with first numeric value as horizontal radius of the rounded corner and second as vertical radius in pixels.

4. The last parameter f is used to control the output image format of the thumbnail, namely png, jpg or gif. We are using png as it can render images with transparent corners which can be used on any background.

Thats all you have to do to generate thumbnail images with rounded corners using PHP script.

Wednesday, 2 January 2013

How to Zip and Unzip Files in PHP?

How to Zip and Unzip Files in PHP?

You can easily zip and unzip big files using PHP script. There is a very nice and simple class in PHP which provides Zip and Unzip utility. Using this class, you can zip and unzip files in one go without any hassles.

First of all, before we zip the file using PHP script, will check whether that file already exists or not? If file already exists, then we have to make sure whether to overwrite that zip file or not? Then we will use PHP ZipArchive class to zip the files. We are providing destination parameter to the create_zip function which will contain the full path and name of the final zip file. Overwrite parameter in this function just tells whether to overwrite the existing zip file or not?

Similarly, we can unzip files using PHP ZipArchive class.

How to zip files using PHP script?

/* creates a compressed zip file */

function create_zip($files = array(),$destination = '',$overwrite = false) {
 //if the zip file already exists and overwrite is false, return false
 if(file_exists($destination) && !$overwrite) { return false; }
 //vars
 $valid_files = array();
 //if files were passed in...
 if(is_array($files)) {
  //cycle through each file
  foreach($files as $file) {
   //make sure the file exists
   if(file_exists($file)) {
    $valid_files[] = $file;
   }
  }
 }
 //if we have good files...
 if(count($valid_files)) {
  //create the archive
  $zip = new ZipArchive();
  if($zip->open($destination,$overwrite?ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
   return false;
  }
  //add the files
  foreach($valid_files as $file) {
   $zip->addFile($file,$file);
  }
  //debug
  //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
 
  //close the zip -- done!
  $zip->close();
 
  //check to make sure the file exists
  return file_exists($destination);
 }
 else
 {
  return false;
 }
}
 
/***** Example Usage ***/

$files=array('file1.jpg', 'file2.jpg', 'file3.gif');
create_zip($files, 'myzipfile.zip', true);

How to unzip files using PHP script?

function unzip_file($file, $destination){
 // create object
 $zip = new ZipArchive() ;
 // open archive
 if ($zip->open($file) !== TRUE) {
  die (Could not open archiveĆ¢€™);
 }
 // extract contents to destination directory
 $zip->extractTo($destination);
 // close archive
 $zip->close();
 echo 'Archive extracted to directory';
}

Tuesday, 1 January 2013

PHP JSON and XML Parser: How to Parse JSON and XML using PHP Script?

PHP JSON and XML Parser: How to Parse JSON and XML using PHP Script?

Parsing XML and JSON is very common application requirement as all the webservices provide data in the form of JSON and XML. PHP has very simple ways to parse XML and JSON. To parse JSON with PHP script, you have to use "json_decode" PHP function. We have given below the PHP JSON Parser code which is very simple. Similarly, using PHP script you can easily create PHP XML Parser. Using simplexml_load_string function, you can easily parse XML in PHP.

Below is the PHP code to parse JSON and XML:

PHP JSON Parser: How to Parse JSON using PHP Script?

$json_string='{"id":101,"name":"Harry","email":"harry@example.com","interest":["wordpress","php"]} ';
$obj=json_decode($json_string);
echo $obj->name; //prints Harry
echo $obj->interest[1]; //prints php

PHP XML Parser: How to Parse XML using PHP Script?

//xml string
$xml_string="<?xml version='1.0'?>
<users>
   <user id='101'>
      <name>Harry</name>
      <email>harry@example.com</name>
   </user>
   <user id='102'>
      <name>Harry2</name>
      <email>harry2@example.com</name>
   </user>
</users>";

//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);

//loop through the each node
foreach ($xml->user as $user)
{
   //access attribute
   echo $user['id'], '  ';
   //subnodes are accessed by -> operator
   echo $user->name, '  ';
   echo $user->email, '<br />';
}

How to Validate, Encode and Send Email using PHP Script?

How to Validate, Encode and Send Email using PHP Script?

Sending email from PHP script is very easy. You can send email using PHP script in many ways. Just create an HTML Form and run the PHP script to send email to various recipient. PHP script uses mail() function to send the email. But before sending the email using PHP script, you must validate the email address to which you are going to send the email. You can impose an extra check to encode the email address to which you are going to send the email using PHP script. Validating and Encoding the email address with PHP script is very easy. So, I will show here step by step how can you validate, encode and send email using PHP script.

Step 1: How to Validate Email Address using PHP Script?

Following is the PHP code to validate email address:

function IsValidEmailAddress($email, $test_mx = false)
{
 if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email))
  if($test_mx)
  {
   list($username, $domain) = split("@", $email);
   return getmxrr($domain, $mxrecords);
  }
  else
   return true;
 else
  return false;
}

Above function to validate the email address uses regular expressions to check whether email address is valid or not. If email address is valid, it returns true otherwise false.

Step 2: How to Encode Email Address using PHP Script?

Following is the PHP code to encode email address:

function EncodeEmailAddress($email='info@domain.com', $linkText='Contact Us', $attrs ='class="emailencoder"' )
{
 $email = str_replace(
'@', '&#64;', $email);
 $email = str_replace('.', '&#46;', $email);
 $email = str_split($email, 5);
 $linkText = str_replace('@', '&#64;', $linkText);
 $linkText = str_replace('.', '&#46;', $linkText);
 $linkText = str_split($linkText, 5);

 $part1 = '<a href="ma';
 $part2 = 'ilto&#58;';
 $part3 = '" '. $attrs .' >';
 $part4 = '</a>';
 $encoded = '<script type="text/javascript">';
 $encoded .= "document.write('$part1');";
 $encoded .= "document.write('$part2');";
 foreach($email as $e)
 {
   $encoded .= "document.write('$e');";
 }
 $encoded .= "document.write('$part3');";
 foreach($linkText as $l)
 {
   $encoded .= "document.write('$l');";
 }
 $encoded .= "document.write('$part4');";
 $encoded .= '</script>';
 return $encoded;
}

Step 3: How to Send Email using PHP Script?

Following is the PHP code to send email to recipient. PHP uses mail() function to send the email. PHP mail() function takes "TO", "SUBJECT" and "BODY" as arguments.

<?php
 $to = "
recipient@example.com";
 $subject = "Hello 2013";
 $body = "GoodBye 2012, Welcome 2013";
 if (mail($to, $subject, $body)) {
   echo("<p>Message successfully sent!</p>");
  } else {
   echo("<p>Message delivery failed...</p>");

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.