Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Thursday, July 24, 2014

Simple, best and standard way to make Thumbnail Images in PHP using Imagick

There is lot of way and plugins available to make thumbnail images in PHP. But that was the problem, because we are confused about which was the best one. After I research on these, I found using Imagick is the best one(Its only on my point of view.).

Imagick
Its an PHP extension to create or modify images. Imagick = Image + Magick. In old periods peoples wrote Magic as Magick. To install these run following command on your linux terminal.

pecl install imagick

After installing Imagick using above command, add “extension=imagick.so“ at the end on php.ini file which is located on /etc/php5/apache2/php.ini and restart the apache.

Example
<?php
$img_old_path = 'images/sun.jpg';     // Input image.
$img_new_path = 'images/thumbnail/sun.jpg';      // Output thumbnail image.

$img = new Imagick($img_old_path);

// Orientation operation start.
// If you remove this orientation block, there will no issue on generating thumbnail. But image may rotated if it has high difference in height and width.
$orientation = $img->getImageOrientation();
switch($orientation) {
    case imagick::ORIENTATION_BOTTOMRIGHT: 
        $img->rotateimage("#000", 180); // rotate 180 degrees.
    break;

    case imagick::ORIENTATION_RIGHTTOP:
        $img->rotateimage("#000", 90); // rotate 90 degrees CW.
    break;

    case imagick::ORIENTATION_LEFTBOTTOM: 
        $img->rotateimage("#000", -90); // rotate 90 degrees CCW.
    break;
}
$img->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
// Orientation operation end.

$img->thumbnailImage(200 , 200, TRUE);
/* Max width and max height with best fit. Will return boolean;
This is the best method to make thumbnail. Action behind the scene is...
1. If given image width is larger than heigh then make thumbnail width as 200(here) and fix height according to that.

2. Else if image hight is larger than width then make thumbnail height as 200 and fix width according to that.*/

$img->writeImage($img_new_path); // Write the generated thumbnail. Will return boolean.
?>

References

Friday, July 18, 2014

Abstract class in PHP

Concept
Abstract class cannot be instantiated, that is we can not create a object. Any class which has at-least one abstract function should be  declared as abstract. These abstract functions are only can declare, can not define here. But these are must be defined in classes which are inherited this abstract class. We can declare this abstract function as any type(public, protected or private) in abstract class, but it should be same or less restricted type in inherited class(For example declared as protected may had public in derived class). And number of arguments also should be same(May had additional optional argument in derived class.).

Clear Example
<?php
abstract class A                          // Abstract class.
{
abstract protected function fun1();   // Declaring abstract function as protected.
abstract public function fun2($i);  // Declaring abstract function as public with one argument.
abstract public function fun3($i,$j); // Declaring abstract function as public with two arguments.

public function fun4()  // Declaring and defining a normal function in abstract class.
{
echo 'fun4 definition from class A(abstract class).<br />';
}
}

class B extends A
{
public function fun1()  // Definiion for a abstract function.
{
echo 'fun1 definition from class B.<br />';
}

public function fun2($i)  // Definiion for a abstract function with exact no.of arugument.
{
echo 'fun2 definition from class B.<br />';
}

public function fun3($i,$j,$k=30)  // Definiion for a abstract function with optional arugument.
{
echo 'fun3 definition from class B.<br />';
}
}

$b=new B();
echo $b->fun1();
echo $b->fun2(10);
echo $b->fun3(10,20);
echo $b->fun4();
?>

Abstract vs Interface
1. Abstract is a class but interface not. So memory allocation for abstract is high.
2. Abstract class can had normal functions and variables. But interface cannot.
3. Functions on interface must be public but in abstract class may had anything.
4. A class can inherit only one abstract class but can inherit more than one interface.

Thursday, July 17, 2014

Interface in PHP

Basic Concept
Interface is declared as same as class, except interface having only function declarations without any definition. A class which implementing a interface must be defined all functions which are declared in interface. We can implement a interface using the keyword implements.

Example 1: Simple Interface Concept.
<?php
interface BasicAction
{
        public function grow();
}

class Man implements BasicAction
{
        public function speak()
        {
               echo 'Will Speak';        
        }

        public function grow()
        {
               echo 'Will Grow';        
        }
}

$obj=new Man();
$obj->speak();
$obj->grow();
?>

Example 2: Extend a interface on another interface.

interface BasicAction
{
        public function grow();
}

interface Animal extends BasicAction
{
        public function walk();
}

class Deer implements Animal
{
        public function walk()
        {
               echo 'Will Walk';        
        }

        public function grow()
        {
               echo 'Will Grow';        
        }
}

Example 3: Multiple inheritance of interfaces on a class

interface A
{
        public function fun1();
}

interface B
{
        public function fun2();
}

class Test implements A, B
{
        public function fun1()
        {
               echo 'Fun 1 Definition';
        }

        public function fun2()
        {
               echo 'Fun 1 Definition';
        }
}

Interface Characters
1. All functions on interface must be public.
2. All functions on interface must be defined in classes which are implements interface.
3. We can inherit more than one interface on a class using comma(,) separator.
4. We can extend a interface on other interface.
5. We can declare constants inside a interface. Which will work as constants under class, except we cannot overwrite constants on other class or interface which implements or extends this interface.
6. Prior to PHP 5.3.9, a class could not implement two interfaces that specified a method with the same name, since it would cause ambiguity. More recent versions of PHP allow this as long as the duplicate methods have the same signature.

Wednesday, July 16, 2014

Final keyword in PHP

If we declare a function inside a class as final, we cannot use that function name in its derived classes. That is final keyword avoid method overriding. You can see more about method overriding here.

Example 1:
<?php
class A
{
     final function test()                // Declare function as final.
     {
          echo 'From base class';
     }
}

class B extends A
{
      function test()                      // Will throw an error.
      {
            echo 'This never run.';
      }
}
?>

And we can also avoid extending a class by declaring a class as final.

Example 2:
final class A                               // Declare class as final.
{
     function fun()
     {
     }
}

class B extends A                      // Will throw an error.
{
}

And note we can only declare function and class as final, cannot declare variable as final.

Constant variables in PHP

Basic Concept
By declaring a variable as constant, it will available all over the program and only we can access it, cannot modify it.

In PHP we can declare a constant variable in two ways. That are using define() function and const keywords.

Before going to see deep difference between these, first look a simple program using these two methods.

Example 1:
<?php
define('PIE',3.143);
const SHAPE='Circle';

function fun()
{
       echo PIE.'<br />';
       echo SHAPE;
}

fun();
?>

Output:
3.143
Circle
?>

On above example there no difference between using define() and const. But it has following notable differences.

1. const execute on compile time and define() execute on run time. That is we cannot declare const under a function or and conditional statement like "if".

2. We cannot declare define() in class, but can declare const.

See the below complex example which is using define() and const in all possible manners.

Example 2:
<?php
define('REGISTER_NO',90323540126);  // Declaring a constant using define keyword in global.
const NAME = 'Ramasamy Kasi';          // Declaring a constant using const keyword in global.
const ROLL_NO = 35;

function fun()
{
define('DEPARTMENT','Computer Science'); // Declaring a constant using define inside a funtion.
// const TOTAL = 450;    // Try to declare a constant using const inside a funtion. ITS WRONG.

echo REGISTER_NO.'<br />'; // Accessing consatants inside a function.
echo NAME.'<br />';
}

class Test
{
// define('AVERAGE',90) // Try to declare a constant using define inside a class. ITS WRONG.
const SEMESTER = 1;          // Declaring a constant using const inside a class.

function sample()
{
echo self::SEMESTER.'<br />';          // WAY 1: Accessing class constant.
}
}

fun(); // Calling function.
echo ROLL_NO.'<br />'; // Accessing constant, which is created in side a function.
echo DEPARTMENT.'<br />'; // Accessing constant, which is created on global.
$obj=new Test();
$obj->sample(); // Calling class function.
echo TEST::SEMESTER; // WAY 2: Accessing class constant.
?>

Output:
90323540126
Ramasamy Kasi
35
Computer Science
1
1

Static variables in PHP

Declaring a variable with a value inside function as static, is will not re-declare or reassign the value when every time that function will called. That is, the last assigned value will remains on that variable.

<?php
function test()
{
    static $a = 1;
    echo $a;
    if ($a <= 10) {
        ++$a;
        test();
    }
}

test(); // Will print: 1234567891011
test(); // Will print: 11
?>

Note:
1. We can not use any expression on declaring of static variables. Ex: static $a=5+6;  // Is wrong.
2. Declaring a variable as static on outside of function not make sense. Because it will not going to re-call in future, except in some cases like using goto statements.

Tuesday, July 15, 2014

Global variables in PHP

Basic Concept
By declaring a variable as Global(Common), we can access it any where of the program.

In C or C++
Here they don't use any special keyword to denote the variable as global. Say for example you defined  or declared a variable with a name in top of the program, now if you use the same name in any where of your program even inside a function, it will denote that as global variable.

Example 1:
#include<stdio.h>
// Global variables
int A=5;
int B=7;

int Add()
{
return A + B;
}

void main()
{
int answer; // Local variable
answer = Add();
printf("%d\n",answer);   // Output: 12
}

In PHP
Here to use global variable inside a function, first we have to declare it as "global".

Example 2:
<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;
    $b = $a + $b;
}

Sum();
echo $b;   // Output: 3
?>

And one more way is we can use a super global valiable called $GLOBALS, intead of the keyword global.

Example 3:
<?php
$a = 1;
$b = 2;

function Sum()
{
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

Sum();
echo $b;   // Output: 3
?>

We could not directly declare a class property as global variable. But we can get global variable under a function inside a class. So it can done by assigning global variable value on a property inside the constructor function.

Example 4:
<?php
$a=5;
class A
{
// private global $a; This is wrong statement. It will not going work.
        privare $a;

function __construct()
{
global $a;
$this->a=$a;
}

 function fun1()
{
global $a;
echo 'value of "a" inside class A is: '.$a;
}
}

$obj=new A();
$obj->fun1();
?>

References:
http://php.net/manual/en/language.variables.scope.php
http://www.codingunit.com/c-tutorial-functions-and-global-local-variables

Monday, July 14, 2014

Class inheritance in PHP

Definition
Creating a new class by inheriting(combining) exist class is called inheritance. By doing this newly created class can access existing classes functions and variables. Here newly created class will be called as sub class or derived class and the class from where it inherited is called as base class or super class.

Example
Books.php:
<?php
class Books // Class name.
{
var $title='5'; // Class variables.
var $price=45;

function __construct() // Constructor.
{
$this->price=100; // Define books's default price is 100.
}

function setTitle($title) // Set title for book.
{
$this->title=$title;
}
function getTitle() // Get tiitle of book.
{
return $this->title;
}

function setPrice($price) // Set price for book.
{
$this->price=$price;
}

function getPrice() // Get price of book.
{
return $this->price;
}

public function name() // A public function.
{
return '<br />Ramasamy Kasi : Public funtion from Books(base) class.';
}

protected function mobileNumber() // A protected function.
{
return '<br />+91 95684575000 : Protected funtion from Books(base) class.';
}

private function password() // A private function.
{
return '<br />bossword : Private funtion from Books(base) class.';
}

protected function getPassword() // Call private function from the same class(Books).
{
return $this->password();
}

function __destruct() // Destructor.
{
echo '<br />Destructor for "'.$this->title.'" Called.'; // Will be called when, there is no further action exist for a object.
}
}
?>

EBooks.php:
<?php
class EBooks extends Books         // Creating new class by combining existing class.
{
var $link;

function setLink($link) // Set link for book.
{
$this->link=$link;
}

function getLink() // Get link for book.
{
return $this->link;
}

function mobileNumber() // Getting mobile number by directly calling base classes protected function 'mobileNumber'.
{
$mob_from_base=Books::mobileNumber();
return $mob_from_base.' - Through EBooks(Sub) Class.';
}

function password() // Getting password by calling one base classes public function 'getPassword'.
{
$pass_from_base=$this->getPassword();
return $pass_from_base.' - Through EBooks(Sub) Class.';
}
}
?>

index.php:
<?php
include 'Books.php'; // Include Books class file.
include 'EBooks.php'; // Include EBooks class file.

$tamil=new Books(); // Creating object.
$tamil->setTitle('Tamil Text Book'); // Set tittle.
$tamil->setPrice(150); // Set price.

$english=new Books();
$english->setTitle('Spoken English');
$english->setPrice(180);

$environment=new Books();
$environment->setTitle('Environmental Science');

$python=new EBooks();
$python->setTitle('Python for Beginners');
$python->setLink('http://python.books/python_begin.html'); // Set link.
$python->setPrice(85);

echo $tamil->getTitle() . ' : ' . $tamil->getPrice().'<br />'; // Display saved title and price.
echo $english->getTitle() . ' : ' . $english->getPrice().'<br />';
echo $environment->getTitle() . ' : ' . $environment->getPrice().'<br />';
echo $python->getTitle() . ' : ' . $python->getPrice() . ' : ' . $python->getLink() . '<br />';

echo Books::name(); // Calling a public function of base class(Books).
echo EBooks::mobileNumber(); // Calling a protected function of base class(Books) by calling public function of sub class(EBooks).
echo $python->password().'<br />'; // Calling a private function of base class(Books) by calling public function of sub class(EBooks).
?>

Output
Tamil Text Book : 150
Spoken English : 180
Environmental Science : 100
Python for Beginners : 85 : http://python.books/python_begin.html

Ramasamy Kasi : Public funtion from Books(base) class.
+91 95684575000 : Protected funtion from Books(base) class. - Through EBooks(Sub) Class.
bossword : Private funtion from Books(base) class. - Through EBooks(Sub) Class.

Destructor for "Python for Beginners" Called.
Destructor for "Environmental Science" Called.
Destructor for "Spoken English" Called.
Destructor for "Tamil Text Book" Called.

Function overloading in PHP with example

General Definition
Defining more than one function with a same name, but different number of parameters or different types of parameters.

In PHP
PHP does not support function overloading directly. That is we cannot create more than one function with a same name under a class, even it has different number of arguments or different data types. But we can do this using a PHP magic method called __call().

__call()
This PHP magic method will be triggered when class object trying to call undefined function(Note: This will not work when we trying to call a undefined function using class name.).
This has two parameters, first one is function name(Undefined function's name which we are trying to call.) and second one is parameters(Undefined function's parameters which we are trying to input.).

Example
<?php
class A
{
function __call($function,$parameters)  // Magic method
{
//echo $function;
//print_r($parameters);
if($function=='test')
{
switch (count($parameters)) {
case "1":
echo 'Test function with one parameters.<br />';
break;

case "2":
echo 'Test function with two parameters.<br />';
break;
case "3":
echo 'Test function with three parameters.<br />';
break;
default:
echo 'Critical Error.<br />';
break;
}
}
else
{
echo $function.' function not exist.<br />';
}
}
}

$a=new A();
$a->test('hi');
$a->test('par1','par2');
$a->test(1,2,3);
$a->sample();
?>

Output
Test function with one parameters.
Test function with two parameters.
Test function with three parameters.
sample function not exist.

Function overriding in PHP with example

Definition
Rewrite the action of function in sub or derived class, which is already in base or super class.

Example
<?php
class Fruits
{
public function taste()
{
return 'Sweet';
}

public function color()
{
return 'Reddish orange';
}
}

class Greaps extends Fruits
{
public function color()  // Overriding color function.
{
return 'Black';
}
}

$greap=new Greaps();
echo 'Taste: '.$greap->taste().'<br />';
echo 'Color: '.$greap->color();
?>

Output:
Taste: Sweet
Color: Black

Notes:
We can avoid method overriding by declaring a function as final.

Thursday, July 10, 2014

Simple OOPs example program using PHP

Class Page: Books.php
<?php
class Books // Class name.
{
var $title='5'; // Class variables.
var $price=45;

function __construct() // Constructor.
{
$this->price=100; // Define books's default price is 100.
}

function setTitle($title) // Set title for book.
{
$this->title=$title;
}
function getTitle() // Get tiitle of book.
{
return $this->title;
}

function setPrice($price) // Set price for book.
{
$this->price=$price;
}
function getPrice() // Get price of book.
{
return $this->price;
}
}
?>

Main Page: index.php
<?php
include 'Books.php'; // Include class file.

$tamil=new Books(); // Creating object.
$tamil->setTitle('Tamil Text Book'); // Set tittle.
$tamil->setPrice(150); // Set price.

$english=new Books();
$english->setTitle('Spoken English');
$english->setPrice(180);

$environment=new Books();
$environment->setTitle('Environmental Science');

echo $tamil->getTitle() . ' : ' . $tamil->getPrice().'<br />'; // Display save title and price.
echo $english->getTitle() . ' : ' . $english->getPrice().'<br />';
echo $environment->getTitle() . ' : ' . $environment->getPrice().'<br />';
?>

Output:
Tamil Text Book : 150
Spoken English : 180
Environmental Science : 100

Monday, January 20, 2014

Timezone in PHP

By default PHP get the timezone from the "php.ini" file.

Get Current Timezone:
echo date_default_timezone_get(); // Will return current timezone used by PHP.

Set Timezone:
date_default_timezone_set('Asia/Kolkata'); // Will set PHP timezone to specified.

Thursday, August 29, 2013

Strange and Interesting facts about PHP

Comparison:
In PHP the boolean values TRUE and FALSE are case in-sensitive.

Example:
$a=TrUe;
if($a)
 echo 'Entered';     //will come
if($a==TRUE)
 echo 'Entered';    //will come
if($a===TRUE)
 echo 'Entered';   //will come

And TRUE = Something other than FALSE or 0 or '0'.

Example:
$a='test';
$b='0';
if($a==TRUE)
    echo 'Entered';   //will come
if($b==TRUE)
    echo 'Entered';   //will not come

Increment Operator:
If we use an increment operator along with a string, it will increment last letter of the string(When the last letter of the string is alpha numeric, that is other than special characters).

Example:
$a='apple3';
$b='apple';
$c='apple?';

echo ++$a;    // output: apple4
echo ++$b;   // output: applf
echo ++$c;   // output: apple?

Case Sensitive:
In PHP variables are case sensitive but functions are not.

Example:
$test='red';
echo $tesT;   // will not work
sample();      // will work

function Sample()
{
echo 'inside function';
}


Please go throw the following links for more details:
http://www.sitepoint.com/3-strange-php-facts-you-may-not-know/
http://php.net/manual/en/types.comparisons.php

Wednesday, July 24, 2013

Apply Even and Odd classes for elements on, "while" or "for" loop

When we display list of elements using any looping, we need to add some two classes for differentiate one row from another. On this case we need use one extra variable, and increment it throw loop, then we can get '0' or '1' by mod(%) this value. So now we can have two different classes repeatedly like 'r0','r1'. And now write style for these two classes.

Example:
<style type="text/css">
Output
.list0{
background-color: #00B2C1;
}
.list1{
background-color: #50D4FF;
}
</style>
<html>
<title>Even and Odd classes for loopig elements</title>
<body>
<table cellspacing="0">
<tr>
<td>NO</td>
<td>Name</td>
</tr>
<?php $i=0; while($i<=10) { ++$i; ?>
<tr class="list<?php echo (++$x%2); ?>">
<td><?php echo $i; ?></td>
<td>Name <?php echo $i; ?></td>
</tr>
<?php } ?>
</body>
</html>


Note: Here we can use '$i' to mod. But most of cases we don't has this option, and more over here we wrote single line(++$x%2) to get mod value.

Monday, July 22, 2013

Regular Expression validation for frontend(JS) and backend(PHP)

Start with one example:

For validate Name Field: Alphabets, numbers and space(' ') no special characters min 3 and max 20 characters.

var ck_name = /^[A-Za-z0-9 ]{3,20}$/; 
if (!ck_name.test(name))
{
        alert('Enter valid Name.');
        return false;
}


Note: The above code for front end using JavaScript. If you are using PHP use key word preg_match instead of test.

Some important conditions:
[abc] Find any character between the brackets
[^abc] Find any character not between the brackets
[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z
{3,10} Check for the string length in between give boundary.


Important Links:


Friday, May 31, 2013

Save output as CSV file and ask for download using PHP

<?php
header("Content-Type: text/csv");
header("Cache-Control: no-store, no-cache");
header('Content-Disposition: attachment; Filename="Selected_Resumes.csv"');

$outstream = fopen("php://output",'w');  //Directly ask for download with out saving
//$outstream = fopen('bath/list.csv', 'w'); // Save file on sever then ask for download

fputcsv($outstream, $titles);

foreach ($result as $data) {
    fputcsv($outstream, $data);
}
fclose($outstream);

//unlink('bath/list.csv');  // Use this to delete file, if you are using save file on server.
?>

Note: Better we can directly ask for download output as CSV, with out saving them in server.

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS...