Showing posts with label PHP Interviews Questions. Show all posts
Showing posts with label PHP Interviews Questions. Show all posts

Thursday 7 January 2016

OOP Interview Questions and Answers

OOP Interview Questions and Answers


What is Object Oriented Programming?
Object-oriented programming (OOP) is a programming language model organized around objects rather than actions;
Objects are instances of classes, are used to interact with one another.

Following are few examples of object-oriented programming languages
PHP, C++, Objective-C, Smalltalk, C#, Perl, Python, Ruby.

The goals of object-oriented programming are:
  1. Increased understanding.
  2. Ease of maintenance.
  3. Ease of evolution.


What is data modeling?
In class, we create multiple get/set function to get and set the data through the protected functions known as Data Modeling.
class dataModel {    
    public function __set( $key, $value ) {
        $this->$key = $value;
    } 
}
Following are the benefits of Data Modeling
  1. It is very fast.
  2. Smart way to  manipulation on data
  3. No extra layer of logic 
  4. Really flexible to be modeled per need 
  5. Setters can explicitly define what data can be loaded into the object


What is difference between class and interface?
1) Interfaces do not contain business logic
2)You must extend interface to use.
3) You can't create object of interface.



How Session - cookie works in PHP?
When a website open in new client machine(Browser), new sessionId is created and stored in php server and in client machine (In cookie).
All data is store in PHP Server and cookie only have sessionId. When client send sessionId with request to the server, then server fetch the data corresponsing to that sessionId and retun to the browser.



What are some of the big changes PHP has gone through in the past few years?
5.1 added PDO
5.3 - added namespace support



What is Polymorphism?
It is simply "One thing, can use in different forms"
For example, One car (class) can extend two classes (hond & Alta)



How to load classes in PHP.
We can load a class with the use of "autoload" class.
If we want to change from default function autoload to testautload function.
we can do this with "spl_autoload_register"
spl_autoload_register('kumar');



How to call parent constructor?
parent::__construct()



Are Parent constructors called implicitly when create an object of class?
No, Parent constructors are not called implicitly It must call this explicitly. But If Child constructors is missing then parent constructor called implicitly.



What happen, If constructor is defined as private OR protected.
If constructor declared as private, PHP through the following fatal error when create object. Fatal error: Call to private BaseClass::__construct() from invalid context in. If constructor declared as private, PHP through the following fatal error when create object. Fatal error: Call to protected BaseClass::__construct() from invalid context in



What happen, If New-Style constructor & old-style constructor are defined. Which one will be called.
New-Style constructor will called. But if New-Style constructor is missing, old style constructor will called.


What are different visibility of method/property?
There are 3 types of visibility of method & property and are following
Public: Can be accessed from same class method, child class and from outside of class.
Protected : Can be accessed from same class method, child class.
Private: Can be accessed from same class method only.
class TestClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printValue()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new TestClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal error: Cannot access protected property TestClass::$protected in
echo $obj->private; // Fatal error: Cannot access private property TestClass::$private in C:\wamp\www\arun\class\class.php on line 20
$obj->printValue(); // Shows Public, Protected and Private 


What is Scope Resolution Operator?
The Scope Resolution Operator (also called Paamayim Nekudotayim) is double colon that allows access to static, constant, and overridden properties or methods of a class. Following are different uses Access to static
Acess the constant
Access the overridden properties of parent class
Access the overridden methods of a parent class



What is Static Keyword in PHP?
  • If we declare a Method or Class Property as static, then we can access that without use of instantiation of the class.
  • Static Method are faster than Normal method.
  • $this is not available within Static Method.
  • Static properties cannot be accessed through the object(i.e arrow operator)
  • Calling non-static methods with Scope Resolution operator, generates an E_STRICT level warning.
  • Static properties may only be initialized using a literal or constant value.
  • Static properties/Normal properties Can't be initialized using expressions value.

class StaticClass
{
    public static $staticValue = 'foo';

    public function staticValue() {
        return self::$my_static;
    }
}
echo StaticClass::$staticValue;




What is Abstraction in PHP?
  • Abstraction are defined using the keyword abstract .
  • PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated (create object).
  • To extend the Abstract class, extends operator is used.
  • You can inherit only one abstract class at one time extending.
  • Any class that contains one abstract method must also be declare as abstract. Methods defined as abstract simply declare the method's signature, they can't define the implementation.
  • All methods marked as abstract in the parent's class, declaration must be defined by the child.
  • additionally, these methods must be defined with the same (or a less restricted) visibility (Public,Protected & private).
  • Type hint & number of parameter must be match between parent & child class.



What is Interface in PHP?
  • Interfaces are defined using the interface keyword.
  • All methods declared in an interface must be public. Classes defined as Interface may not be instantiated(create object).
  • To extend the interface class, implements operator is used.
  • You can inherit number of interface class at the time of extending and number of abstract class separated by comma.
  • All methods in the interface must be implemented within a child class; failure to do so will result in a fatal error.
  • Interfaces can be extended like classes using the extends operator.
  • The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.
  • Type hint & number of parameter must be match.



What is Traits in PHP?
  1. Traits are a mechanism for code reuse in single inheritance.
  2. A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. 
  3. It is not possible to instantiate a Trait but addition to traditional inheritance. It is intended to reduce some limitations of single inheritance to reuse sets of methods freely in several independent classes living in different class hierarchies.
  4. Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas(,).
  5. If two Traits insert a method with the same name, a fatal error is produced.

    Example of Traits
class BaseClass{
    function getReturnType() {
        return 'BaseClass';
    }
}
trait traitSample {
    function getReturnType() {
        echo "TraitSample:";
        parent::getReturnType();
    }    
}

class Class1 extends BaseClass {
    use traitSample;   
}

$obj1 = new Class1();
$obj1->getReturnType();//TraitSample:BaseClass



What is Overloading?
It is dynamically create method / properties and performed by magic methods. Overloading method / properties are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope, Means we you are calling a function which is not exist. None of the arguments of these magic methods can be passed by reference.
In PHP, Overloading is possible http://200-530.blogspot.in/2013/04/oop-magic-methods.html



What is Object Iteration?
PHP provides a way for objects to be iterate through a list of items, for this we can use foreach. Only visible properties will be listed.
class TestClass{
    public $public='PublicVal';
    protected $protected='ProtectedVal';
    private $private='PrivateVal';
    
    function myfunc() {
        return 'func';
    }
    
    function iterateVisible(){
        foreach($this as $key => $value) {
           print "$key => $value\n";
       }
    }
}

$obj=new TestClass();
$obj->iterateVisible(); 



What is Final Keyword in PHP?
PHP introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final.
If the class itself is being defined final then it cannot be extended. If the function itself is being defined final then it cannot be extended.



What is Serialize function in php?
It return string containing a byte-stream representation of any value that can be stored in PHP.



Comparing Objects?
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.
When using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class



What is UML?
UML stands for Unified Modeling Language.
You can do following things with UML
  • Manage project complexity.
  • create database schema.
  • Produce reports.


What are Properties of Object Oriented Systems?
  • Inheritance
  • Encapsulation of data
  • Extensibility of existing data types and classes
  • Support for complex data types
  • Aggregation
  • Association 


Question: What is serialization?
serialization: returns a string containing a byte-stream representation of any value that can be stored in PHP.
Before starting your serialization process, PHP will execute the __sleep function automatically.

What can you Serialize?
  1. Variables
  2. Arrays
  3. Objects


For example
   
$str_array = array( "I", "Love", "PHP" );
$serialized_str = serialize($str_array);
echo $serialized_str;
Output
a:3:{i:0;s:1:"I";i:1;s:4:"Love";i:2;s:3:"PHP";}




Question: What is un-serialization?
unserialize: can use this string to recreate the original variable values.
Before starting your unserialization process, PHP will execute the __wakeup function automatically.

What can you  un-Serialize?
Resource-type

   
$unserialized = unserialize('a:3:{i:0;s:1:"I";i:1;s:4:"Love";i:2;s:3:"PHP";}');
print_r($unserialized);

Output
Array ( [0] => I [1] => Love [2] => PHP )



Sunday 15 November 2015

Top 10 PHP Interview Questions and Answers


Top 10 PHP Interview Questions and Answers


Question 1: How to redirect a page to another?
You can use header function to recirect.
header('location: http://www.web-technology-experts-notes.in"); //Redirect to home page of another website

header('location: http://www.web-technology-experts-notes.in/2015/11/php-questions-and-answers-for-experienced.html"); //Redirect to another page and another website

header('location: php-questions-and-answers-for-experienced.html"); //Redirect to another page of same website

header('location: php-questions-and-answers-for-experienced.html?topic=php");  //Redirect to another page of same website with parameter

header('Location: http://www.web-technology-experts-notes.in/2015/11/php-questions-and-answers-for-experienced.html', true, 301); //Permanent Redirect

Following are different use of header functions.
  1. Redirect from one page to another page. Also can redirect to another website.
  2. Help to download the file like (csv download, pdf download etc).
  3. Browser Authentication to the web page.
  4. Set the header of any page at the top of page.



Question 2: Is it secure to store a password in a session?
No,
If you still need then please stored in encrypted form with different name (not password).


Question 3: How to set/get PHP array in cookie?
//Set an array in cookie
$arrayData=json_encode(array(1,2,3,4,5,6));
setcookie('no_array', $arrayData);

//Get an array from cookie
$cookie = $_COOKIE['no_array'];
$arrayData = json_decode($cookie);
print_r($arrayData);



Question 4: What is the difference between bindParam and bindValue?
$string='this is ';
if (strlen($string) != strlen(utf8_decode($string)))
{
    echo 'is unicode';
}else{
  echo 'It is Not unicode.';
}



Question 5: How to add 30 mins to a date?
$date = date("Y-m-d H:i:s");
date("Y/m/d h:i:s", strtotime("+30 minutes", $date));



Question 6: How to get Path From URL?
$url = "http://www.web-technology-experts-notes.in/2013/09/amazon-s3-introduction.html";
$path = parse_url($url);
print_r($path);
/**Array
(
    [scheme] => http
    [host] => www.web-technology-experts-notes.in
    [path] => /2013/09/amazon-s3-introduction.html
)*/



Question 7: How to get array elements which present in two different array?
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
/**Array ( [a] => green [0] => red )*/



Question 8: How to replace array elements with another another?
$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
print_r($input);

/*Array ( [0] => red [1] => green [2] => blue [3] => black [4] => maroon )*/



Question 9: Count number of elements in an array?
$foodArray = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));

echo count($foodArray); // output 2
// recursive count
echo count($foodArray, COUNT_RECURSIVE); // output 8



Question 10: How to exchanges all keys with their associated values in an array?
$input = array("oranges", "apples","mango", "pears");
$flippedArray = array_flip($input);

print_r($flippedArray);
/*Array ( [oranges] => 0 [apples] => 1 [mango] => 2 [pears] => 3 )*/



Saturday 14 November 2015

PHP Questions and Answers for experienced

PHP Questions and Answers for experienced



Question: Difference between array_map, array_walk and array_filter?
array_map: This function applies the callback to the elements of the given arrays.
$arrayData= array_map('strtolower', array('One','Two','three'));
print_r($arrayData); //array ( [0] => one [1] => two [2] => three )

array_walk: This function apply a user supplied function to every member of an array
function my_function(&$item, $key){
  $item=$item.($key+1);
}
$arrayData=array('One','Two','three');
array_walk($arrayData, 'my_function');
print_r($arrayData); //Array ( [0] => One1 [1] => Two2 [2] => three3 )

array_filter: This function filters elements of an array using a callback function.
function odd_number($item){
  if($item%2==0){
    return false;
    }else{
    return true;
    }
}
$arrayData=array(1,2,3,4,5,6);
$arrayData=array_filter($arrayData, 'odd_number');
print_r($arrayData); //Array ( [0] => 1 [2] => 3 [4] => 5 )



Question: How to convert date to timestamp in PHP??
echo strtotime('2015-09-15'); //1442275200



Question: Give an easy way to encrypt/decrypt the password?
define('SALT', 'X4DSF464ADS6SC5C5D55D5'); 
function encrypt_string($text) 
{ 
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 
} 

function decrypt_string($text) 
{ 
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 
} 

echo $msg = encrypt_string("your message"); //q2s33vKz5sNPPQFzZygm4nqtjuPljaI+9q1mtcwRZ3U=
echo decrypt_string($msg);//your message


Question: How to get the last character of a string in PHP?
echo substr("web tehnology", -1); // y



Question: How to store array in constants??
$arrayData=array(1,2,3,4,5,6);
define ("FRUITS", serialize($arrayData));
print_r(unserialize (FRUITS));



Question: What is the difference between bindParam and bindValue?
bindParam the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called. PDOStatement::bindValue() is not work in this way.


Question: What is use of PHP_EOL?
PHP_EOL is used to find the newline character in a cross-platform-compatible way so it handles DOS/Mac/Unix issues.


Question: How to get accurate Ip Address of client Machine?
function ip_address(){
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(',', $_SERVER[$key]) as $ip){
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                    return $ip;
                }
            }
        }
    }
}
echo ip_address();//101.60.216.68 



Question: How to get extension of file??
$path ='/web-tech/myimage.png';
print_r(pathinfo($path, PATHINFO_EXTENSION));



Question: How to Check if PHP session has already started?
if(session_id() == '') {
    echo "session not started";
}else{
 echo "session started";
}



Question: NOW() equivalent function in PHP?
echo date("Y-m-d H:i:s"); //2015-11-14 9:52:32



Question: How to get all php functions?
print_r(get_defined_functions());



Friday 13 November 2015

PHP Difficult Interview Questions and Answers

PHP Difficult Interview Questions and Answers


Question: How to check a variable is NULL OR empty string?
var_dump($variableName);

Also for compare you can use === to compare data type.


Question: How can I execute an anonymous function?
call_user_func(function() { echo 'anonymous function called.'; });



Question: How can I measure the speed of code written in PHP?
$startTime= microtime(true);
/** Write here you code to check **/
/** Write here you code to check **/
$endTime= microtime(true);
echo 'Time Taken to executre the code:'.$endTime-$startTime;



Question: Which PHP Extension help to debug the code?
Xdebug


Question: How to get Yesterday date?
date("F j, Y", strtotime( '-1 days' ) ); //November 11, 2015



Question: How to set HTTP header to UTF-8 using?
Add following at the top of page.
header('Content-Type: text/html; charset=utf-8');



Question: How to get first 20 characters from string?
echo substr('Web Technology Experts Notes',0,20);



Question: How to get last date of month of given date?
$date = "2015-11-23";
echo date("Y-m-t", strtotime($date));



Question: How do I check with PHP if file exists?
$filename = "/folder/filename.php";
if (file_exists($filename)) {    
    echo "The file $filename exists.";    
} else {
    echo "The file $filename does not exists.";
}



Question: How to remove non-alphanumeric characters ?
echo preg_replace("/[^A-Za-z0-9 ]/", '', 'web technology experts notes @2015 '); //web technology experts notes 2015



Question: How do I replace all line breaks (\n\r) in a string with
tags?

echo str_replace(array('\r','\n','\r\n'),'
','Hello \n Web technology');



Question: How do I format a number to a dollar amount in PHP? Give Example?
Use money_format
echo money_format('$%i', 6.6); // echos '$3.40' //echos $6.60



Question: How to prevent Browser cache for php site?
Add following code at the top of web page.
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");



Question: How do i get the current script file name?
echo __FILE__; //htdocs/project/index.php



Question: How to add key/value in existing array?
$arrayname['keyname'] = 'new value';



Monday 7 September 2015

How to Detect Request type in PHP

How to Detect Request type (GET OR Post ) in PHP

Question:How to Detect Request type (Get OR Post) in PHP?
$method = $_SERVER['REQUEST_METHOD'];
try {
    switch ($method) {
        case 'GET':
            /** Add your code here **/
            
            /** Add your code here **/
            break;
        case 'POST':
            /** Add your code here **/
            
            /** Add your code here **/
            break;
        case 'PUT':
            /** Add your code here **/
            
            /** Add your code here **/
            break;
        case 'HEAD':
            /** Add your code here **/
            
            /** Add your code here **/
            break;
        case 'DELETE':
            /** Add your code here **/
            
            /** Add your code here **/
            break;
        case 'OPTIONS':
            /** Add your code here **/
            
            /** Add your code here **/
            break;
        default:
            echo "$method method not defined";
            break;
    }
} catch (Exception $e) {
    echo $e->getMessage();
}



Question: How to get all post data in PHP?
$postData = array();
if(!empty($_POST)){
    $postData = $_POST;
}
print_r($postData );



Question: How to get all GET data in PHP?
$getData = array();
if(!empty($_GET)){
    $getData = $_GET;
}
print_r($getData );



Question: How to get Document root path in PHP?
echo $_SERVER['DOCUMENT_ROOT'];



Question: How to get Client Ip-Address in PHP?
echo $_SERVER['REMOTE_ADDR'];



Tuesday 30 June 2015

PHP Basic questions and answers for fresher and experienced

Top 25 PHP-Interview Questions and Answers


Question: How JSON.parse Works? Give few examples?
JSON.parse is method which is used parses a string as JSON. How to parse the string as JSON
JSON.parse('{}');              // {}
JSON.parse('null');            // null
JSON.parse('true');            // true
JSON.parse('"string"');           // "string"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]



Question: How to get the Data of any Public URL(HTML Contents)? Get the data of public URL is known as scrapping. You can use following method to get the data of public URL
  1. use file_get_contents function
  2. use CURL


Question: What is use of nl2br?
nl2br is used to insert the line break.


Question: What is .htaccess?
htaccess is configuration file for Apache Server which helps us to configure at base level configuration as well as directory level.


Question: How to get the URL of Referrer page?
echo $_SERVER['HTTP_REFERER'];


Question: How to extract seconds, minutes and hour from date?
$dateTime = strtotime("2015-06-30 12:25:60");
echo date('s',$dateTime); //seconds
echo date('i',$dateTime); //Minutes
echo date('h',$dateTime); //hour in 0-12 format
echo date('H',$dateTime); //hour in 0-24 format


Question: How to get current date and time?
echo date('Y-m-d H:i:s');



Question: How to change the timezone using PHP?
echo date_default_timezone_get(); //Default time zone

date_default_timezone_set('America/Los_Angeles'); //Chnage timezone to Los_Angeles



Question: Difference between unset and unlink?
unset is used to remove the variable from scope.
unlink is used to remove the file from server.


Question: How to increase max execution time?
Following are different ways to increase the execution time?
Change dynamically with PHPv
ini_set('max_execution_time', 300);

With htaccess
php_value max_execution_time 300

Change in php.ini (NEED server restart)
max_execution_time = 120


Question: How to check a variable have number OR String value?
$testvariable ='10';
if(is_number($testvariable)){
    echo "This is Number";
}else{
    echo "This is string";
}


Question: What is PEAR in php?
Full form of PEAR is PHP Extension and Application Repository. It is a framework and repository for reusable PHP components.


Question: What is MIME?
Full form of MIME is Multi-purpose Internet Mail Extensions.
It is standard way to get the file type of an file.


Question: Can we change the value of constant variable?
No, we can't do this.


Question: How do we destroy a session?
session_destroy();



Question: What is a PDO classes?
PDO is an PHP extension which provides an interface to connect the database like mysql, mysqli, SQL etc.


Question: What is full form of Ajax? What is Ajax?
Full form of AJAX is Asynchronous JavaScript and XML.
Ajax is technique which is used to update the website contents without refreshing the page. Ajax get the contents from server.


Question: How to set and destroy the cookie?
setcookie("cookieName", "cookie value", time()+3600);  //Set the cookie
setcookie("cookieName", "cookie value", time()-3600);  //distroy the cookie


Question: Does PHP support multiple inheritances in PHP?
No, PHP Support only single level of inheritance.


Question: Can we achieve multiple inheritance in PHP?
PHP Does not support multiple inheritance but we can achieve multilevel inheritance in directly.
See Example below:
class a{}
class b extends a{}
class c extends b{}
class d extends c{}
class e extends d{}
class f extends e{}

As PHP Does not support multi level inheritance but we can extend mulitple classes one by one (As in Above).



Wednesday 3 June 2015

PHP Mysql Interview Questions and Answers for fresher and experienced

PHP Mysql Interview Questions and Answers for fresher and experienced


Question: How many ways we can retrieve the data in the result set of MySQL using PHP?
Following are different ways
$sqlQuery = mysql_query("SELECT id, name FROM users");
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
    //$row have results
}

$sqlQuery = mysql_query("SELECT id, name FROM users");
while ($row = mysql_fetch_assoc($sqlQuery)) {
    //$row have results
}

$sqlQuery = mysql_query("SELECT id, name FROM users");
while ($row = mysql_fetch_object($sqlQuery)) {
   //$row have results
}



Question: How can we create a database using PHP and MySQL?
mysql_create_db('db_name');



Question: How can we repair a MySQL table?
Use any of below as per requirement:
REPAIR tablename; 
REPAIR tablename quick;
REPAIR tablename extended;



Question: How can we find the number of rows in a result set using PHP?
$sqlQuery = mysql_query("SELECT id, name FROM users");
$num = mysql_num_rows($sqlQuery);



Question: How to update auto increment value for 100000?
ALTER TABLE table_name AUTO_INCREMENT = 100000;



Question: How to get the current version number of MYSQL?
SELECT VERSION();



Question: What is difference between between NOW() and CURRENT_DATE()?
Now gives the current date, hour and minutes
select NOW()
//2015-06-03 19:17:23  



CURRENT_DATE gives the current date only.
select CURRENT_DATE()
//2015-06-03

Question: List all databases?
SHOW DATABASES



Question: What is mysql query to show the first 100 records?
SELECT * FROM user LIMIT 0,100


Question: How many TRIGGERS allows per table in mysql?
Following are 6 triggers in mysql for table.
1. BEFORE INSERT,
2. AFTER INSERT,
3. BEFORE UPDATE,
4. AFTER UPDATE,
5. BEFORE DELETE
6. AFTER DELETE



Question: What is difference between COMMIT and ROLLBACK?
COMMIT: Mostly it is used in transaction and commit means all process are completed successfully. Once commit done you can not revert.
ROLLBACK: Mostly it is used in transaction and ROLLBACK means all process are NOT completed successfully. So revert the db changes automatically.


Question: What is SAVEPOINT?
The SAVEPOINT statement is used to set a savepoint with a name in transaction. used for roll back the transaction to the named savepoint specified instead of all the changes.


Question: How to find the number of days between two dates?
$now = time(); // or your date as well
$newDate = strtotime("2010-01-01");
$datediff = $now - $$newDate;
echo floor($datediff/(60*60*24));


Question: How to find the number of hours between two dates?
$now = time(); // or your date as well
$newDate = strtotime("2010-01-01");
$datediff = $now - $$newDate;
echo floor($datediff/(60*60));


Question: How to find the number of minutes between two dates?

$now = time(); // or your date as well
$newDate = strtotime("2010-01-01");
$datediff = $now - $$newDate;
echo floor($datediff/(60));


Question: How do I get random item from an array?

$array = array('','s','d');
echo $array[array_rand($array)];


Question: How to update the max_allowed_packet mysql variable?
You can check the value of max_allowed_packet with following query.
SHOW VARIABLES LIKE 'max_allowed_packet'; 

For Update, You have to change in configuration mysql.
File Location in My Wamp Server: D:\wamp\bin\mysql\mysql5.6.17\my.ini
Now search with max_allowed_packet and update, as per requirement.


Question: List all the tables whose engine is InnoDB?
SELECT table_name FROM INFORMATION_SCHEMA.TABLES  WHERE ENGINE = 'InnoDB'




Question: How to update the column where NULL value set?
update `users` set phone='000000000' where  phone is NULL





Friday 22 May 2015

PHP interview questions and answers for 5 year experienced

PHP interview questions and answers for 5 year experienced


Question: How array_walk function works in PHP?
Purpose: It is used to update the elements/index of original array.
How: in array_walk, two parameter are required.
1st: original array
2nd: An callback function, with use of we update the array.



Question: Difference Between Zend framework 2 VS Zend framework 1?
http://www.web-technology-experts-notes.in/2014/03/zend-framework-2-vs-zend-framework-1.html


Question: How to achieve Multilevel inheritance in PHP?
//base class
class grandParent{}

//parent class extend the base class
class parent extends grandParent{}

//chid class extend the parent class
class child extends parent{}



Question: What is Routing? How it works in Zend?
Routing is the process of taking a URI endpoint and decomposing it into parameters to determine which module, controller and action to that controller should receive the request.
This values of the module, controller, action and parameters are packaged into a Zend_Controller_Request_Http object which is then processed by Zend_Controller_Dispatcher_Standard.




Question: What is Zend_Controller_Front?
Front Controller is design pattern.
Zend framework use the Zend_Controller_Front which is based on Front controller design pattern. Zend_Controller_Front purpose is to initialize the request environment, route the incoming request and then dispatch any discovered actions.
It aggregates any responses and returns them when the process is complete.


Question: What is difference between TDD and BDD?
TDD is Test-driven development
BDD is Behaviour-driven development



Question: What is Zend_Translate? Where it is used?
It is component of Zend Framework. Responsible for converting the text data from one language to another languages.
It is used in multilingual website where we are showing content display in multilingual.


Question: What are different Adapter of zend_translate?
Following are main Adapter of zend translator
Zend_Translate_Adapter_Array
Zend_Translate_Adapter_Csv
Zend_Translate_Adapter_Gettext
Zend_Translate_Adapter_Ini
Zend_Translate_Adapter_Tbx
Zend_Translate_Adapter_Tmx
Zend_Translate_Adapter_Qt
Zend_Translate_Adapter_Xliff
Zend_Translate_Adapter_XmlTm


Question: How to get 2nd highest salary of employee, if two employee may have same salary?
select salary from employee group by salary order by salary limit 1,1



Question:How to find duplicate email records in users table?
SELECT u1.first_name, u1.last_name, u1.email FROM users as u1
INNER JOIN (
    SELECT email FROM users GROUP BY email HAVING count(id) > 1
    ) u2 ON u1.email = u2.email;



Question: How to pass data in header while using CURL?
$url='http://www.web-technology-experts-notes.in';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'headerKey: HeaderValue ',
  'Content-Type: application/json',
  "HTTP_X_FORWARDED_FOR: xxx.xxx.x.xx"
));
echo curl_exec($ch);
curl_close($ch);



Question: How to pass JSON Data in CURL?
$url='http://www.web-technology-experts-notes.in';
$jsonData='{"name":"Web Technology Experts","email":"contact@web-technology-experts-notes.in"}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_close($ch);



Question: What is Final Keyword in PHP?
PHP introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final keyword.


Question: What are Properties of Object Oriented Systems?
Inheritance
Encapsulation of data
Extensibility of existing data types and classes
Support for complex data types
Aggregation
Association



Question: How can we prevent SQL-injection in PHP? Sanitize the user data before Storing in database.
While displaying the data in browser Convert all applicable characters to HTML entities using htmlentities functions.



Question: How to redirect https to http URL and vice versa in .htaccess?
Redirect https to http
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Redirect http to https
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]



Question: What are benefits of htaccess?
We can do following benefits stuff with htaccess.
Routing the URL
Mange Error Pages for Better SEO
Redirection pages
Detect OS (like Mobile/Laptop/Ios/Android etc)
Set PHP Config variable
Set Environment variable
Allow/Deny visitors by IP Address
Password protection for File/Directory
Optimize Performance of website
Improve Site Security

Question: What is Reference Transaction in Paypal?
In Reference transaction,
With use of first transaction done by customer, we can do mutiple transaction without need another approvel.
In this, we store the transaction_id(First transaction), and use this transaction_id as reference_id for net payments.

It has two methods.
1) DoDirect payment. (Accept the credit card by website)
2) Express Checkout. (website doesn't accept credit card in own website, customer pay on paypal.com)
Click to Know More



Question: What is the validate a credit card format in PHP?
MASTERCARD Prefix=51-55, Length=16
VISA Prefix=4, Length=13 or 16
AMEX Prefix=34 or 37, Length=15
Diners Club/Carte Prefix=300-305, 36 or 38, Length=14
Discover Prefix=6011,622126-622925,644-649,65, Length=16

PHP Function to validate
function validateCreditCardFormat($number) {
    //Only number will accept 
    $number = preg_replace('/\D/', '', $number);

    // Set the string length and parity
    $number_length = strlen($number);
    $parity = $number_length % 2;

    // Loop through each digit and do the maths
    $total = 0;
    for ($i = 0; $i < $number_length; $i++) {
        $digit = $number[$i];        
        if ($i % 2 == $parity) {
            $digit*=2;            
            if ($digit > 9) {
                $digit-=9;
            }
        }
        
        $total+=$digit;
    }
    if($total%10==0){
        return true;
    }else{
        return false;
    }    
}
var_dump(validateCreditCardFormat('5105105105105100')); //true
var_dump(validateCreditCardFormat('4111111111111111'));//true
var_dump(validateCreditCardFormat('4012888888881881'));//true
var_dump(validateCreditCardFormat('40128888'));//false



Question: Difference between Apache and Nginx?
Nginx is based on event-driven architecture.
Apache is based on process-driven architecture.

Nginx development started only in 2002.
Apache initial release was in 1995.

Nginx doesn't create a new process for a new request.
Apache creates a new process for each request.

In Nginx, memory consumption is very low for serving static pages.
Apache’s nature of creating new process for each request, that's why it  increases the memory consumption.

Nginx is extremely fast for serving static pages as compare to Apache.

In complex configurations apache can be configured easily as compare to Nginx.

Apache has excellent documentation as compare to Nginx.

Nginx does not support Operating Systems like OpenVMS and IBMi where as Apache supports much wider range of Operating Systems.

The performance and scalability of Nginx is not completely dependent on hardware resources.
The Performance and scalability of the Apache is dependent on underlying hardware resources like memory and CPU.


Question: When to use self over $this?
Use $this to refer to the current object.
Use self to refer to the current class.

Example of use of $this
class MyClass1 {
    private $nonStaticMember = 'nonStaticMember  member Called.';        
    
    public function funcName() {
        return $this->nonStaticMember;
    }
}

$classObj = new MyClass1();
echo $classObj->funcName();//nonStaticMember  member Called.


Example of use of self
class MyClass2 {
    private static $staticMember = 'staticMember  member Called.';        
    
    public function funcName() {
        return $this::$staticMember;
    }
}

$classObj = new MyClass2();
echo $classObj->funcName(); //staticMember  member Called.





Monday 11 May 2015

PHP Frequently asked Questions and Answer 2015

PHP Frequently asked Auestions and Answer 2015



Question: What is PHP?
PHP is a server-side scripting language which is used to create the dynamic web pages.


Question: Who is fater of PHP?
Rasmus Lerdorf


Question: Which language is used to Implementation?
C/C++


Question: What is offical website of PHP?
http://php.net/


Question: What is current statable version of PHP?
Version: 7.0.6 Dated April 29, 2016.


Question: What is extensions of PHP File?
.php, .phtml, .php4, .php3, .php5, .phps


Question: Describe how PHP Works with Browser?
Works in following Flow
1. Open website http://www.web-technology-experts-notes.in/
2. Request send to server of http://www.web-technology-experts-notes.in/
3. Call PHP Files.
4. PHP Scripts are loaded into memory and compiled into Zend opcode.
5. These opcodes are executed and the HTML generated.
6. Same HTML is send back to Browser.

Know more: http://www.web-technology-experts-notes.in/2012/07/what-is-zend-engine-in-php.html


Question: What are important things about php functions?
PHP function start with "function function-name()".
PHP Function name must be start with character and it accept alphanumeric and _.
In build functions are case in-sensitive.
User build functions are case sensitive.
We can pass upto 64 parameter as argument.
Anonymous function are user defined function which have "no-name" and also called closures.
PHP support variable functions. Means when you can call a function using variable.
In same file OR under same class, same function name can't be created.


Question: What is role of htmlentities?
htmlentities is used to convert all applicable characters to HTML entities.
It is used to stop the user from running malicious code in HTML.
With use of htmlentities, user can't run the html tags like h2, p, script etc. It helps to prevent you from XSS attack.
echo htmlentities($userData);



Question: How to use email with PHP?
Email functionality is inbuilt with PHP.
PHP provide mail() with use of this, we can sen an email to user or subscriber.
We can send html/text email.
We can send attachment with email.
We can also use option like cc, bc and bcc.
We can also set the values in header.
We can also use third party API like (gmail, yahoo etc) to send email.


Question: How session and cookie works together?
Create an session in PHP.
Session data is stored in Server.
Session data have unique name.
Session unique key with domain name is stored in browser cookie.
Now, Browser keep the login with use of unique key(in cookie) and session data (stored in server side).


Question: What is the difference between the functions unlink and unset?
unlink: delete the files from Server.
unset: delete the variable name and data from memory.


Question: How to create subdomain?
With use virtual host and htaccess, you can create sub domain.


Question: What are the various methods to pass data from one web page to another web page?
Session
Cookie
Database
URL parameters



Question: What are super global variables?
$_COOKIE – Stored information in Cookie.
$_GET – Send data in URL as paramter.
$_POST – Send data to server OR Page as POST Method.
$_REQUEST – Its combined array containing values from the $_GET, $_POST and $_COOKIES.
$_ENV – Get/Set varaible in environment.
$_FILES – Used to upload the file, image and videos etc.
$_SERVER – It have all server information.
$GLOBALS – Contains all the global variables associated with the current script.


Question: How to get a user's IP address of client.
echo $_SESSION['REMOTE_ADDR'];


Question: What type of inheritance supported by PHP?
Single inheritance.
Multiple Level inheritance.


Question: What is CMS?
CMS means Content Management System. It is web software who provide the website full fledged content management where owner can add/update/delete the html/files/images/videos etc. Today's CMS do much more as compare to its name.
For example. Joomla/Wordpress is CMS but you can create E-commererce website and can accpet all types of payment.
In Today's CMS, you can create many different types of website like Ecommerce website, Personal blogging and Forum etc.


Question: How to create unique random password?
echo md5(uniqid(rand(), true));


Question: What is the difference between echo and print?
echo constructor which is used to display the value in browser.
print is function which is used to display and return the value.


Question: What is the difference between characters \023 and \x23?
\023 is octal 23.
\x23 is hex 23.