Friday, 31 May 2013

PHP Interview Questions and Answers for Experienced

PHP Interview Questions and Answers for Experienced

Question: What is Difference between local variable and data members or instance variable?
Answer: 1. A data member belongs to an object of a class whereas local variable belongs to its current scope. 
2. A local variable is declared within the body of a function and can be used only from the point at which it is declared to the immediately following closing brace.
3. Data members are accessible to all member function of the class. Local variable are not accessible in any another function or class.


Question: What are static method? How its different from normal method?
Answer: 1. Static methods are that can be accessed by using the scope resolution operator (i.e ::) and object reference operator ( i.e.-> ).

For example HelloClass::mystatic(); $helloClass->mystatic();
class MyClass{             
    static function mystatic() {                           
        echo "this was declared static!\n";  
    }  
}              
 
$obj = new MyClass();                                                                                 

MyClass::mystatic();
$obj->mystatic();

2. The only rule is that static methods or properties are out of object context.
3. Public function of class can be access by scope resolution operator (i.e ::) and Object Reference Operator (i.e ->) but public data member can't be access through scope resolution operator.




Question: When and Why we use static variable/ functions?
Answer: 1. You use static when you want to use a method / variable that is not tied to an instance.
2. When you want to persistent value throughout multiple call of function.
3. For singleton pattern, we use static method/variable.
4. it is very usefull for caching if a method will be called very often and do just the same thing. For example see below
protected function is_logged_in() {
    static $logged_in = null;
    if($logged_in != null) {
        return $logged_in;
    }

    //Check shibboleth headers
    if (!empty($_SERVER['HTTP_SHIB_IDENTITY_PROVIDER']) || !empty($_SERVER['Shib-Identity-Provider'])) {
        if (!empty($_SERVER[$this->core->dbconfig("shib_auth", self::SHIB_AUTH_CONFIG_UID)])) {
            $logged_in = true;
            return true;
        }
    }
    $logged_in = false;
    return false;
}


Question: What is Persistent Database Connections?
Answer: Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link.
Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably.



Question:Server Start/Stop/Restart unix command
Restart Apache web server over the SSH
/etc/init.d/apache2 restart

Stop Apache web server over the SSH
/etc/init.d/apache2 stop

Start Apache web server over the SSH
/etc/init.d/apache2 start

httpd Server restart command
service httpd restart

httpd Server Stop command
service httpd stop

httpd Server Stop command
service httpd start


Question: What is ORM?
Answer: Full form of ORM is Object Relation Mapper.
 ORM is programming technique for converting data between incompatible type systems in object-oriented programming languages.


Data management tasks in object-oriented programming(OOP) are typically implemented by manipulating objects that are almost always non-scalar values.
For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a "Person object" with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain "PhoneNumber objects" and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance)

Question: What is Exception Handling in PHP?
Answer: Exception Handling is used to handle the error. It can handle all types of error like Warning, Notice, User defined Error message etc but unfortunately it can not handle fatal error. read more...



Question: What is dispatcher in Zend?
Answer: Dispatching is the process of taking the request object,  Zend_Controller_Request_Abstract, extracting the module, controller, action name, and optional parameters contained in it, and then instantiating a controller and calling an action of that controller. If any of the module name, controller name, or action are not found, it will use default values for them.
Zend_Controller_Dispatcher_Standard specifies index for each of the controller and action defaults and default for the module default value, but allows the developer to change the default values for each using the setDefaultController(), setDefaultAction(), and setDefaultModule() methods, respectively.


Question: What is Bootstrap in Zend?
Answer: In Zend Framework, bootstrapping is the process that loads your application. This includes, but is not limited to the Session. Any resources needed by your application to process the request (the dispatch) to the application is bootstrapped/loaded/initialized before the request is fulfilled, e.g. before the controller delegates any input to the model and creates a response that is send back to the client.


Question: What are the advantages and disadvantages of Store procedure.
Answer: Following are the advantage / disadvantage of SP.
Advantage
You do not need to deploy to make a change.
Faster
Easier to expand a system

Disadvantages
Refactoring is harder. Renaming or changing where the store proc is might produce a bad effect.
Unit testing stored proc require code assistance outside the DB



Question : What is difference between array_combine and array_merge?
Answer: array_merge merges the elements of one or more arrays. array_combine  Creates an array by using one array as its keys and another for its values.


Question: How to import database from desktop to server with use of command line?
1) Make a zip of sql dump file and upload the zip file to server through FTP.
2) Login to Putty/Console
3) Go the directory with use of cd command, the location where you have upload the zip file.
4) unizip that zip file, with following command
unzip zipfilename.zip
3)Import the sql dump file with use of following command.
mysql -u username -p databasename < sqlfilename.sql 

(It will for prompt password)


Question: How to copy file from one server to another?
1) Login to Putty/Console
2) Go to the directory where your file exist (suppose file name is file.zip)
3) Use the following command to copy the file frome current server to another server
scp file.zip username@hostname:/foldername
(It will prompt password)
(username, hostname is another server)


Question: How to export database to sql file with use of command line?
1) Login to Putty/Console
2) Execute following commands to export the sql dump into server.
mysqldump –u username –p databasename tablename > sqlfilename.sql
(It will prompt password)


Question: Import database from sql file to mysql
mysql –u username –p databasename tablename < sqlfilename.sql
(It will prompt for password)


Question: What is Responsive web design? 
Responsive web design (RWD) is a web design approach aimed at crafting sites to provide an optimal viewing experience, easy navigation and reading with a minimum of scrolling, resizing and  panning. across a wide range of devices (all mobiles, desktop, laptop, ipad etc).


Question:  What is www1?
World Wide Web
The number(eg 1,2,3,4,5....) that follows the "WWW" indicates that the data being retrieved by the Web browser is gathering the information from a different Web server than the one that serves the typical "WWW" address.
Web sites, especially dynamic Web sites, that handle large amounts of traffic often need more than one server to accommodate the many requests they receive as one server often cannot handle the multitude of requests.
Examples
https://www1.pearsonvue.com/
https://www2.pearsonvue.com/
https://www3.pearsonvue.com/
https://www4.pearsonvue.com/
https://www5.pearsonvue.com/
https://www6.pearsonvue.com/

Here all above websites have same data.


Question: Create a php script that output following.

Answer:
$totalRows =5;
$totalStar=1;
for($rows=1; $rows<=$totalRows; $rows++){
if($rows!=1){
$totalStar+=2;
}
$cols=$totalStar;
$space = $space1 = $totalRows-$rows; 
 
 /** create first space **/ 
  while($space>0){
       echo ' ';
      $space--;
  }
  /** create star **/
    while($cols>0){
       echo "* ";
   $cols--;
  }
  /** create second space **/ 
    while($space1>0){
       echo ' ';
      $space1--;
  }
  
   echo "";

}

Question: What is New Relic. What is benefits of this software?
Answer: New Relic is software as a service (SaaS) that monitors your Website and mobile applications(Android, iOS) in real-time that run in different environments like cloud, on-premise and hybrid. 

Following are few benefits of New Relic
1. Monitoring your website regularly.
2. Downtime Notification by email.
3. Custom Error recording and then report you in email & also can view in newrelic website.
4. Key Transaction tracking: 
You will be able to see where your application is spending most of its time (e.g. in the controller, model OR database).
5. External Service Call Recording (Webservices)



Question: What is Apdex?
Answer: Apdex means Application Performance Index.
It is standard method for reporting & comparing the performance of software.

Purpose:  Analyse the performance, user satisfaction & expectation then Convert into percentage.

Formula
Apdex = (Satisfied + Tolerating / 2) / Total 
Satisfied: Response time is less than or equal to T.
Tolerated: Response time is more than T and (Less than OR Equal to 4T);
Frustrated: Response time is greater than 4T.
T: It is threshold time define by  application owner.

Example: https://docs.newrelic.com/docs/assets/apdex.pdf


Question: Execute a php script using command line in wampserver server in window7.
Answer: Follow  simple steps
1. login to command prompt (CMD)
2. Go to path where "php.exe" exist in wamp folder.
"C:\wamp\bin\php\phpx.x.x";
2. Execute the file with php, for example
php c:/wamp/www/arun/test.php


Question: What is meant by urlencode and urldocode?
Answer: URL coding converts special characters into % signs followed by two hex digits.
For example, urlencode("10.00%") will return "10%2E00%25?
urldocode is just opposite to urlencode


Question: What is difference between unlink and unset?
Answer: unlink: It unlink(remove) the file.
unset: It unlink(remove) the variable from scope.


Question: How to get the image type, size,width and height
Answer: 
type: exif_imagetype()
size: use getimagesize()
width: use imagesx()
height: use imagesy()


Question: What are formating functions in PHP?     
Answer: 
Function                     Description
printf()    :                 Displays a formatted string
sprintf()   :                 Saves a formatted string in a variable
fprintf()   :                 Prints a formatted string to a file
number_format()  :   Formats numbers as strings


Question: How to import Text File in database?
LOAD DATA LOCAL INFILE 'C:/Users/Vijay/Desktop/SQL/image.txt' INTO TABLE images FIELDS TERMINATED BY '|' LINES TERMINATED BY '\n';



Question: How to include a file to a php page?
We can include a file using include() or require() function with file path as its parameter. For Example
include "myfile.php";
require "myfile.php";//use this OR ABOVE



Question: How to detecting request type in PHP (GET, POST, PUT)?
echo $_SERVER['REQUEST_METHOD']; //get/post/put/delete



Question: How to get the full path of php.ini?
You can check php.ini path in phpinfo();
Search with Loaded Configuration File .



Wednesday, 29 May 2013

MySQL Indexing

MySQL Indexing

Indexing

It is a data structure that improves the speed of search in database. We add the indexing on columns of table. We can one or more indexing on table.

Advantage of Indexing
It improve the speed of search. If we add indexing on any column, It will search faster.

Disdvantage of Indexing

INSERT and UPDATE statements take little more time on tables.


Following are different types of MySQL indexes

Column Index: In this type, we add indexing on single column
ALTER TABLE table_name ADD INDEX (field_name);

Concatenated Index: In this type, we add indexing on two OR more columns.
ALTER TABLE table_name ADD INDEX (field_name1, field_name2);

Use only when you are using query in below way
SELECT * FROM table_name  WHERE field_name1='text1' AND field_name2='text2';


Partial Index : In this type, we add indexing on single columan and on few number of character like first 10 character.
ALTER TABLE table_name ADD INDEX (field_name(10));

Following are some examples of indexing

create a table cities 
CREATE TABLE IF NOT EXISTS `cities` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Add Indexing
alter table `cities` add index name (name)

List all the Indexing in cities table
show index from `cities`

Drop Indexing
alter table `cities` drop index name


Tuesday, 28 May 2013

Difference between Abstract class and Interface in PHP

Difference between Abstract class and Interface in PHP

S.No
Abstract Class
Interface
1
For abstract class, a method must be declared as abstract. In class, at-least one method must be declared as abstract.


Variable can not be declared
For Interface, class must be declared as Interface.

In interface, all methods by default all are abstract methods.


Variable can not be declared
2
The Abstract methods can declare with Access modifiers like public, private, protected.

When implementing in subclass these methods must be defined with the same visibility (Like public, protected).
All methods are public in interface.
3
Abstract class can contain variables, concrete methods and constants.Interfaces cannot contain variables and concrete methods except constants.
4
A class can Inherit only one Abstract class
and
Multiple inheritance is not possible for Abstract class.
A class can implement many interfaces
and
Multiple interface inheritance is possible.


   



Similarity between abstract and interface classes

1) We can not create object of abstract and interfaces.

2) Abstract method must be there in abstract and interface

3) We have to defined all the methods which are abstract in base class.



Example of Interface
//Interface
interface car {

    public function audio();

    public function video();
}

//how to implements interface
class mycar implements car {

    public $owner = 'Arun';

    public function audio(){
        return 'Audio functionality.';
    }

    public function video(){
        return 'Video functionality.';
    }

    public function owner() {
        return $this->owner;
    }

}

$mycarObj = new mycar();
echo $mycarObj->audio(); //Audio functionality
echo $mycarObj->video(); //video functionality
echo $mycarObj->owner(); //Arun



Example of Abstract
//Abstract class
abstract class car {
    //Abstract method
    abstract public function audio();

    public function video() {
        return 'video functionality.';
    }

}

class mycar extends car {
    public $owner='Arun';
    public function audio() {
        return 'Audio functionality.';
    }
    public function owner() {
        return $this->owner;
    }    

}

$mycarObj = new mycar();
echo $mycarObj->audio(); //Audio functionality
echo $mycarObj->video(); //video functionality
echo $mycarObj->owner(); //Arun



Mysql Update Statement with Join

Mysql Update Statement with Join

Yes, You can use update statement with mysql join also.

See Below Example

1) Create users Table
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `address` text,
  PRIMARY KEY (`id`)
);

2) Add records in users table.
INSERT INTO `users` (`id`, `name`, `address`) VALUES
(1, 'name 1', 'address 1'),
(2, 'name 2', 'address 2'),
(3, 'name 3', 'address 3'),
(4, 'name 4', 'address 4'),
(5, 'name 5', 'address 5'),
(6, 'name 6', 'address 6'),
(7, 'name 7', 'address 7'),
(8, 'name 8', 'address 8'),
(9, 'name 9', 'address 9'),
(10, 'name 10', 'address 10'),
(11, 'name 11', 'address 11'),
(12, 'name 12', 'address 12'),
(13, 'name 13', 'address 13'),
(14, 'name 14', 'address 14'),
(15, 'name 15', 'address 15');

3) Create salary Table
CREATE TABLE IF NOT EXISTS `salary` (
  `id` int(11) NOT NULL DEFAULT '0',
  `user_id` int(11) NOT NULL,
  `salary` float(10,2) NOT NULL,
  PRIMARY KEY (`id`)
);

4) Add Record in salary Table
INSERT INTO `salary` (`id`, `user_id`, `salary`) VALUES
(1, 9, 5000.00),
(2, 6, 3500.00);

Requirement : update the user record whose salary is 5000.

Solution with Inner join
update users As u INNER JOIN salary As s on s.user_id=u.id set u.name='my salary is 5000'  where s.salary=5000

Solution with LEFT join
update users As u LEFT JOIN salary As s on s.user_id=u.id set u.name='my salary is 5000'  where s.salary=5000

Solution with Right join
update users As u RIGHT JOIN salary As s on s.user_id=u.id set u.name='my salary is 5000'  where s.salary=5000


Monday, 27 May 2013

Ajax Methods in JQuery

Ajax Methods in JQuery

jQuery Load Method
load(): Load a piece of html into a container DOM.
$('#result').load('ajax/test.html');

jQuery GET Method
$.get(): Use this if you want to make a GET call and play extensively with the response.
$.get('ajax/test.html', function(data) {
  $('.result').html(data);
  alert('Load was performed.');
});

jQuery POST Method
$.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
$.post('ajax/test.html', function(data) {
  $('.result').html(data);
});

jQuery AJAX Method
$.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.
$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});




jQuery getJSON Method
Return the Response in JSON Format
$.getJSON("/ajax/json_response", function(result){
    console.log(result)
        
    });



Wednesday, 22 May 2013

Spoofed Forms - Stop Spoofed Form Submissions

Spoofed Forms - Stop Spoofed Form Submissions

It is method in which attacker create a copy of html form of another website, fill the data whatever he want to sent and submit the form.

There are various ways to spoof forms, the easiest of which is to simply copy a target form and
execute it from a different location. Spoofing a form makes it possible for an attacker
to remove all client-side validations/restrictions imposed upon the form in order to submit the form.


Street:
City:
State:
Zip:


See in above form, here form's action is of another website.


How to Protect your website from spoofed forms

  • Add client side and server side validation
  • Use token system
  • Use captcha

Defination of SOLID DRY KISS UX

Defination of SOLID DRY KISS UX

SOLID Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion
Create a system that is easy to maintain and extend over a time to time.


DRY : Don't Repeat Yourself
Develop a functionalities that need not to change but can be extend the functionalists. 


KISS : Keep It Simple Stupid
Coding standard must be maintain and approach do simple, so that every developer must be able to understand at one glance.

UX : User Experience


Friday, 17 May 2013

Concurrent Connections of Apache Server

First of all you should understand below

  • ServerLimit: 16
  • StartServers: 2
  • MaxClients: 200
  • MinSpareThreads: 25
  • MaxSpareThreads: 75
  • ThreadsPerChild: 25



First of all, whenever an apache is started, it will start 2 child processes which is determined by StartServers parameter.
Then each process will start 25 threads determined by ThreadsPerChild parameter so this means 2 process can service only 50 concurrent connections/clients i.e. 25x2=50.

Now if more concurrent users comes, then another child process will start, that can service another 25 users. But how many child processes can be started is controlled by ServerLimit parameter, this means that in the configuration above, I can have 16 child processes in total, with each child process can handle 25 thread, in total handling 16x25=400 concurrent users. 


But if number defined in MaxClients is less which is 200 here, then this means that after 8 child processes, no extra process will start since we have defined an upper cap of MaxClients

This also means that if I set MaxClients to 1000, after 16 child processes and 400 connections, no extra process will start and we cannot service more than 400 concurrent clients even if we have increase the MaxClient parameter. 

In this case, we need to also increase ServerLimit to 1000/25 i.e. MaxClients/ThreadsPerChild=40 So this is the optmized configuration to server 1000 clients


    ServerLimit          40
    StartServers          2
    MaxClients          1000
    MinSpareThreads      25
    MaxSpareThreads      75 
    ThreadsPerChild      25
    MaxRequestsPerChild   0


File Location: C:/wamp/bin/apache/Apache2.2.17/conf/extra/httpd-mpm.conf

Mysql FullText Search Examples

Mysql FullText Search Examples

Full-text indexes can be used with MyISAM tables and InnoDB tables (in MySQL 5.6+ only), and can be created only for varchar, char and text columns only.

A FULLTEXT index definition can be given in the CREATE TABLE statement when a table is created, or added later using ALTER TABLE or CREATE INDEX.

/** create table **/
CREATE TABLE products (
 id INT UNSIGNED NOT NULL AUTO_INCREMENT,
 name VARCHAR(75) NOT NULL,
 sku  VARCHAR(75) NOT NULL, 
 description MEDIUMTEXT NOT NULL, 
 PRIMARY KEY(id)
)ENGINE=MyISAM;
/** add full text indexes **/
CREATE FULLTEXT INDEX ft_index_name ON products (name, description); 


Full-text searching is performed using MATCH() and AGAINST syntax.

MATCH() takes a comma-separated list that names the columns in which to be searched.

AGAINST takes a string to search for, and an optional modifier that indicates what type of search to perform. The search string must be a string value that is constant during query evaluation. This rules out, for example, a table column because that can differ for each row.

INSERT INTO `abc`.`products` (`id`, `name`, `sku`, `description`) VALUES (NULL, 'watch', 'w2658', 'test watch'), (NULL, 'MOBILE', 'M25744', 'Test mobile')
INSERT INTO `abc`.`products` (`id`, `name`, `sku`, `description`) VALUES (NULL, 'watch1', 'w26581', 'test watch'), (NULL, 'MOBILE1', 'M257441', 'Test mobile');



There are three types of full-text searches:

1. A boolean search interprets the search string using the rules of a special query language. The string contains the words to search for. It can also contain operators that specify requirements such that a word must be present or absent in matching rows, or that it should be weighted higher or lower than usual. Common words such as “some” or “then” are stopwords and do not match if present in the search string. The IN BOOLEAN MODE modifier specifies a Boolean search.

2. A natural language search interprets the search string as a phrase in natural human language (a phrase in free text). There are no special operators. The stopword list applies. In addition, words that are present in 50% or more of the rows are considered common and do not match. Full-text searches are natural language searches if no modifier is given.

3. A query expansion search is a modification of a natural language search. The search string is used to perform a natural language search. Then words from the most relevant rows returned by the search are added to the search string and the search is done again. The query returns the rows from the second search. The WITH QUERY EXPANSION modifier specifies a query expansion search. For more information, see Section 12.9.3, “Full-Text Searches with Query Expansion”.
Example
SELECT * 
FROM products WHERE MATCH (name,description) AGAINST ('mobile') 
SELECT * 
FROM products WHERE MATCH (name,description) AGAINST ('mobile' in boolean mode) 
select * from products WHERE MATCH(name,description)  AGAINST ('+mobile -computer' IN BOOLEAN MODE);




See following for searching....
'mobile computer'
search mobile or computer

'+mobile +computer'
search for both mobile and computer

'+mobile -computer'
search for mobile without computer

'+mobile +computer'
search for both mobile and computer

‘+mobile ~computer’
Find rows that contain the word “mobile”, but if the row also contains the word “computer”, rate it lower than if row does not.

‘+mobile +(>computer <television)’
Find rows that contain the words “mobile” and “computer”, or “mobile” and “television” (in any order), but rank “mobile computer” higher than “mobile television”.


OperatorDescription
+Include, word must be present.
-Exclude, word must not be present.
>Include, and increase ranking value.
<Include, and decrease ranking value.
()Group words into sub expressions 
~Negate a word’s ranking value.
*Wildcard at end of word.
“”Defines a phrase (as opposed to a list of individual words, the entire phrase is matched for inclusion or exclusion).