Skip to main content

Interview PHP

>> Why do you want to work at our company?
Sir, It is a great privilege for anyone to work in a reputed company like yours. When I read about your company I found that my skills are matching your requirements.  Where I can showcase my technical skills to contribute to the company growth.
>> What are your strengths?
I am very much hard working and optimistic.
Hard Working: Work with dedication and determination.
Optimistic: work with positive attitude.

I am a team player. I am also very hardworking, and will do what it takes to get the job done.
>> What are your weaknesses?
Gets nervous when talk to strangers
I am a bit lazy about which I am not interested

I tend to trust people too easily. I am working on it.
>> Why should I hire you?
With reference to my work experience, I satisfy all the requirement for this job. I am sincere with my work and would never let you down in anyway. I promise you will never regret for the decision to appoint me in your organization.

I can prove to be a great asset to your company because I feel I possess the right qualities and skills required for this job.

>> Tell me what you know about this company?
It is one of the best fastest growing company in india. Work environment of the company is very good. People feel proud to be part of the company as company provides full support to their employees.

>> What is your greatest accomplishment?

Being a part of the leading software firm has been my greatest accomplishment.

>> Why are you looking for a job change?
I am thankful to my previous organization because I have learnt a lot of thing from there. According to me changes are necessary for everyone to enhance your skills, knowledge and for professional growth and financial growth. Your organization is the good platform where I can learn more.

In order to enhance my skill set, I am looking for better opportunities.
>> What are your salary requirements?
As per the company standard I am expecting.

Salary is my second priority. I want to enhance my knowledge and build on my skills.
>> What are your career goals or Where do you see yourself in 5 years?
My short term goal is to get a job in reputed company where I can utilize my skills and improve my career path. My long term goal is to be in respectable position in that organization.
>>  Do you have any questions to ask me?
Thank you for giving this opportunity. Sir I would like to know about the job timing.
Can you explain the roles and responsibilities in greater detail?
What are the growth opportunities for me in this company?

What are the next steps of the interviewing process?

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

English Learning Tips

  • Conversation - Convert speech in mind directly in English not first in native language.
  • Translation - Note down words add to sticky note which are in daily use and you not known. 
  • Story telling - Try to speak whatever story in your mind to yourself/some/group. 
  • Repeat Learning - language unless you repeat does not get learned.

 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Agile Methodology & Scrum

>> Who will work on Product backlog?
Product owner will manage and assigns priority.

>> What is sprint planning?
Sprint planning is done by scrum master and development team. Work and Estimation of stories will be done here.

>> What is sprint backlog?
Sprint backlog is bunch of stories to be complete in current sprint.

>> who will be work on sprint backlog?
Developers will be work on sprint backlog.

>> Role of scrum master?
Role of scrum master is to check gloal is achivable.
Scrum master will check is daily meeting is done and not exceed above 15min.
Discuss on roadblocks and resolve with product owner.

>> What is sprint retrospective?
Sprint retrospective will be done by scrum master with team on what will be Good, Bad and improvement in sprint.

>> What is sprint review?

>> What is Agile Methodology
Agile Methodology is Better way to developing a software:
Values of Agile Methodology
 - Individuals and Interactions: Self organised and motivation
 - Working Software: Demo working software is better consider comminuction with client rather than depending upon only documents
 - Customer Collabration: Requirement can not be gathered completely in begining of project, so continuous customer interaction is important.
 - Responding to change: Focused on quick responses to change and continuous development.

Techniques:
Customer satisfaction
Changing requrements
Countinuous delivery
Work together
Build Projects
Face to face communication
Measure Progress
Maintain Pace

Scrum : Main goal is work efficiently and effectively.

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Design patterns

>> What are Design Patterns? (Solutions To General Problems)
Design patterns are solutions to general problems that software developers faced during software development.

>> What is Gang of Four (GOF)?
In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book titled Design Patterns - Elements of Reusable Object-Oriented Software which initiated the concept of Design Pattern in Software development. These authors are collectively known as Gang of Four (GOF).

>> Singleton pattern?
class has only one instance and provides a global point of access to it.

>> Factory Design Pattern?
let the subclasses decide which class to instantiate.

>> Observer Design pattern?
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

>> Stratergy design pattern  (also known as the policy pattern)?
software design pattern that enables selecting an algorithm at runtime.

>> adapter design pattern ((also known as Wrapper)?
allows the interface of an existing class to be used as another interface.

>> Other points in design pattern.
The term “design pattern” was originally coined in the field of architecture.
Design patterns are a template for how to organize your code so you can take advantage of a tried-and-true design.
A pattern is a useful technique to solve a given problem. A design pattern isn’t a library—code
to be included and used directly in your project—but rather a template for how your code can be
structured. Indeed, a code library and a design pattern are applied much differently.
e.g.
For example, a shirt you buy off the rack at a department store is a code library. Its color, style,
and size were determined by the designer and manufacturer, but it meets your needs. However, if nothing in the store suits you, you can create your own shirt—designing its form, choosing a fabric, and stitching it together. But unless you are a tailor, you may find it easier to sim-ply find and follow an appropriate pattern. Using a pattern, you get an expertly-designed shirt in far
less time.
One last thought: like a sewing pattern, a design is of little use on its own. After all, you can’t wear
a pattern—it’s just a patchwork of thin paper. Similarly, a software design pattern is just a guide. It
must still be tailored specifically to a programming language and your application’s features and
requirements.

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
>> Latest Versions of things you used:- (up to dec 2017)

  • PHP 7.0
  • Apache 2.4.29
  • Mysql stable 5.7 and next 8.0
  • Laravel 5.5
  • Symfony 3.3  and now 4
  • AngularJs 4.4
  • CodeIgniter 3.1.6 and next 4 
  • jQuery 3.2.1
  • Jquery UI 1.7+
  • ReactJs 16.0,
  • Dojo Js framework 1.13.0
  • EmberJS framework 2.17
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

>> How PHP Executes from source code to render?
PHP interpreter goes through four stages when executing code,

Lexing - 
Lexing or tokenizing is the process of turning a string (PHP source code, in this case) into a sequence of tokens. A token is simply a named identifier for the value it has matched. PHP uses re2c to generate its lexer from the "zend_language_scanner.l" definition file.

Parsing -
PHP uses a LALR(1) (look ahead, left-to-right) context-free grammar. The left-to-right part means that it parses the token stream from left-to-right. The generated parser stage takes the token stream from the lexer as input and has two jobs. It firstly verifies the validity of the token order by attempting to match them against any one of the grammar rules defined in its BNF grammar file. The second job of the parser is to generate the abstract syntax tree (AST) – a tree view of the source code that will be used during the next stage (compilation). We can view a form of the AST produced by the parser using the php-ast extension.

Compilation - 
The compilation stage consumes the AST, where it emits opcodes by recursively traversing the tree. This stage also performs a few optimizations. These include resolving some function calls with literal arguments (such as strlen("abc") to int(3)) and folding constant mathematical expressions (such as 60 * 60 * 24 to int(86400)). We can inspect the opcode output at this stage in a number of ways, including with OPcache, VLD, and PHPDBG.

Interpretation - 
The final stage is the interpretation of the opcodes. This is where the opcodes are run on the Zend Engine (ZE) VM.

Note that while some of the extensions used should already be a part of your PHP installation (such as tokenizer and OPcache), others will need to be manually installed and enabled (such as php-ast and VLD). This has involved using various extensions (including tokenizer, php-ast, OPcache, and VLD) to manipulate and view the output of each stage.

>> Abstract syntax tree AST?
  • Is tree representation of the abstract syntactic structure of source code written in a programming language. each node of the tree denotes a construct occuring in the source code.
  • The syntax is abstract and not representing every details occuring in real syntax.
  • Is like parse trees but ignore some details.
e.g.
1. Consider the grammar
    E -> int | (E) | E + E
2. Add the string
    5+(2+3)
3. After lexical analysis (a list of tokens)
    int5 '+' '('int2 '+' int3 ')'
4. During the parsing we build a parse tree
    E -> E int5 + E -> (E) -> E+E -> E int2 + E int3
  • parentheses very important in parsing as it shows the association.
  • traces the operation of the parser
  • captures nesting structure
  • but it has too much information (parentheses, single-succesor nodes)

5. Abstract syntax tree
    PLUS -> 5 -> PLUS -> 2 3
  • Captures the nesting structure.
  • But abstract from concrete syntax (more compact and easier to use)
  • An important data structure in a compiler.

>> Difference between compiler and interpreter?
Compiler -
It takes hole source code and Translates high level languages to machine code at once.
Compiler translates high level language as source progamme it takes hole source code and translates to machine level and then executes.
e.g. Compiled languages C++, JAVA, C#, C etc. these use compiler. Java uses both compiler translator and Interpreter translator.

Interpreter - 
It takes each line and translate it to machine code and then again next line and translates it to machine code.
Interpreter is translator which takes high level language as source programme line by line and convertes to machine language line by line and executes till end of programme.
e.g. Interpreted languages are BASIC, PYTHON etc. these use interpreter.

>> What is assembler? (system software)
Assemble is a system software translates assembly language(low level language) into machine language.
Input to an assembler is source programme and translated programme is called object programme.
Assembly language programmes are machine dependent.

>> What are type of software?
Software -> System (translator(assembler, interpreter, compiler), operating(like windows)), applicationutility.

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Optimization Server side & PHP code
Session by SM --->>

Optimization 
PHP/Mysql Internal 
PWA/AMP 
pull/push protocol
Design patterns

Currenclty for optimization we follow the "monolithics" aproach but there is another aproach in market called "microservices" which is followed by many huge sites.

>>>> Optimization Server side

>> Use nginx server
Use nginx server as it used event loop in background to handle the requests and not block for each request. Low cost high performance.
In Apache it blocks the other all request until previous request completes.
e.g.
ngix
request
     event loop (background) free
next request
     event loop (background) free
>> http2 protocol latest in market over https using that it the performance increased 5x times.
>> Use/Enable gzip compression

gzip compression compresses the data and browser unzip the compressed file at browser end.
using this the browser response time gets increased.
Browser know the gzip enabled at server end using header send to browser for each url.
While gzip compression server allocates unique address for each element/text for similar things and compress the data according to that.
E.g. Server allocates unique addres for same "div" elements
<div> ADDRESS
    <div>
        <div>
e.g. we can see the gzip is enabled or not using F12 in browser response Headers
Response Headers
Content-Encoding:gzip
Accept-Ranges:bytes
Cache-Control:max-age=604800
Connection:keep-alive
Content-Length:29918
Content-Type:application/javascript
Date:Mon, 13 Nov 2017 06:03:23 GMT
Expires:Mon, 20 Nov 2017 06:03:23 GMT
Last-Modified:Thu, 09 Nov 2017 05:46:21 GMT
Server:Apache
Vary:Accept-Encoding

>> keep alive
tell browser to cache data for particular time
e.g.
Response Headers
Connection:keep-alive
Content-Length:29918

>> etag (We can use etag OR keep alive the purpose is same)
hash purpose
this is same as keep alive but insted to time it useses hash value

>> load balancer
We can use the load balancer server to handle the huges requestes.
e.g.
ngix (useses Round Robin rule to distrubute work amongs each server)

>>>> Optimization in php code side

>> Divide and Rule (less no of iteration)
Code tructure should follow the divide and rule logic for large code/if statments
e.g. for bellow code we can use devide and rule like
if(x==1)
if(x==2)
if(x==3)
if(x==4)
...
if(x==10)

//divide and rule
if(x==1 or x==2 or x==3) {
 if(x==1)
 if(x==3)
 else
}
if(x==8 or 9 10) {

}

>> Concatening variables is faster than just putting them in a double-quotation mark string.
e.g
$var = 'Hello ' . $world; // is faster than bellow
$var = "Hello $world";

>> When using a loop, if your condition uses a constant, put it before the loop. ( Never Use Count or Any Other methods in The Condition Section of a Loop)
e.g. in bellow example count($my_array) need to assign to variable then use in for loop.
for ($i = 0; $i < count($my_array); $i++) // this is wrong practice
for ($i = 0, $count = count($my_array); $i < $count; $i++) // this is good practice

>> Do not put querries in a loop (insted you can use inner joins)
e.g. bellow example is bad practice avoid such a things
$query = mysql_query("SELECT id FROM your_table");
while ($row = mysql_fetch_assoc($query)) {
    $query2 = mysql_query("SELECT * FROM your_other_table WHERE id = {$row['id']}");
    // etc
}

>> Unnecessary testing count array to zero instead you can use "!" operator in if
e.g.
if (count($array) === 0) return; // this is bad practice
if (! $array) return; // this is good practice (this will cause PHP Notice of Undefined variable), so use bellow
if (!empty($array)) return; // this is also good

>> Using single quotes ( ‘ ‘ ) is faster than using double quotes( ” ” )

>> Use “= = =” instead of “= =”.
The equality operator == typecasts, or converts the data type temporarily to see if it’s equal to the other operand whereas === ( identity operator ) doesn’t need to do any converting whatsoever and thus, it does lesser work, making it comparatively fast.
>> Using a switch/case or if/elseif is almost the same. Note that the test is unsing === (is exactly equal to) and is slightly faster then using == (is equal to).
>> Avoid the @ operator it suppresses warnings 
>> Absolute paths for requires and includes.
>> Releasing all Resources (Unsetting large arrays, closing a file handler, closing a database connection or a curl request to any other server.)
>> Avoid Unnecessary Use of Global Variables (Accessing a global variable is twice as costly as accessing a local variable)
>> Use strpos, str_replace etc. instead of regular expressions whenever possible.
>> Use isset Use isset( ) where ever possible instead of using count( ), strlen( ), sizeof( ) to check whether the value returned is greater than 0.
>> isSet() and empty() are identical. So always check if val is set at all before using type-checking. E.g. if (isSet($foo) AND is_array($foo)).
>> Using more of Static Methods/Properties.
Static methods/ properties are generally faster than non-static ones. However, if an object is pre-initialized and then a non-static method/property is called repeatedly on the same object, non-static is faster.
>> foreach > for > while
According to our benchmarks, the foreach loop is much faster than the for loop and for loop is faster than the while loop.
>> Pre and Post Increments (so best practice to use pre-increment)
Post-incrementation in PHP has been documented as storing a temporary variable which attributes to this 10% overhead vs. pre-incrementation.
e.g.
++$i is pre-incrementation, $i is incremented and the new value is returned
$i++ is post-incrementation, the value of $i copied to an internal temporary variable, $i is incremented and the internal copy of the old value of $i is returned.
The difference measured by us is not much, so it’s being recommended in this case to use it according to the need without worrying about the microscopic difference.
>> Echo, print, comma, printf, and sprintf (Echo is a language construct whereas print is a function.)
echo is faster than print.
e.g.
echo $a, $b, $c; //is faster than echo $a . $b . $c;, but echo $a . $b . $c; is faster than print $a . $b . $c.
we have printf and sprintf functions, which are least used in PHP scripts.
Using sprintf is 10 times faster than using variables within double quotes in string formatting. There is a little difference between sprintf and printf. printf outputs the string, whereas sprintf stores the string in a variable.
e.g.
$query = sprintf( “SELECT * FROM users WHERE username=’%s’ AND password=’%s'”, $_user, $_password );

>>>> Use PHP 7 instead of lesser version
PHP 7.0 is released on (3 December 2015), It has following features like
  • speed 10x greater
  • It supports type casting to variables and funbction to easy job of compiler.
  • Internal support for php caching (php cache opcache, apc, memcached)
  • Improved performance
  • Significantly reduced memory usage
  • Abstract Syntax Tree
  • Consistent 64-bit support
  • Improved Exception hierarchy
  • Many fatal errors converted to Exceptions
  • Secure random number generator
  • Removed old and unsupported SAPIs and extensions
  • The null coalescing operator (??)
  • Return and Scalar Type Declarations
  • Anonymous Classes
  • Zero cost asserts

>>>> js/css/images Optimization
 - compression, js ,css and html
 - use sprint images
 - image compress
 - use cdn for (images,js,css)

browser based host channel or threads
hosts 4 channel safari 2
rc.com 4 channel
use subdomains to gain more channels to load contents in browser.
static.rc.com 4 channel images 4
js/css
e.g. Facebook uses many subdomains to load contents/images/js/css files.
gfdhfgdjds.static.fb.com
dhsdjshgdasj.static.gdggjs

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Oops notes:-

>> Advantages of Oops - re-usability, Easy to Maintain

>> Encapsulation - Binding property and function in single unit/class. Encapsulation can be done using access specifiers.
Binding of data members and members functions under one single unit(class) is called encapsulation.

>> Abstraction - Hide something is called abstraction. Abstraction is defined as showing only the relevant data to the user. (eg. Mobile Phone Design, Car steering)
Any representation of data in which the implementation details are hidden. Show needed details only instead of showing all information which is not necessary.
Abstraction is defined using abstact keyword. Methods and classes can be abstact. Abstract class can not be instantiate.
All methods declared as abstract in parent class must be defined in child class.

>> Inheritance - Code re-usability (Inheritance is a feature by which a class acquires attributes of another class.) (e.g Car (wheel, steering, gear))
Inheritance is used to code reusability. We derived child class from base class through which we used properties (variables, methods/procedures/function) of base/parent class in derived/child class
Or
In inheritance, we have a parent class with its own methods and properties, and a child class (or classes) that can use the code from the parent class.

Type of Inheritance -

  • Single - From one base class one derived class. possible in PHP, Class A => Class B
  • Multilevel  - From one base class derived class is created and that derived class considering as base another derived class is created. possible in PHP, Class A => Class B => Class C
  • Multiple  - Number of base classes to one derived class. not possible in PHP but we can achieve using interface or traits. Class C is extends Class A and Class B 
  • Hierarchical  - From one base class number of derived classes is created. not possible in PHP, One Father and n number of children from him
  • Hybrid   - Combination of above. not possible in PHP, Class D is extends from Class B and Class C
link:- http://technotip.com/2683/multiple-and-hybrid-inheritance-php-oop/

>> Why multiple inheritance not supported in PHP
One problem occurs when two parent classes have data members or methods of the same name. It is difficult to resolve which is being referenced by the sub-class.

>> Polymorphism - 
One name many forms.
It is simply one thing can use in many forms.
One function behaves multiple way depending on parameter/type pass to it.  (eg:- Humanbeing(men, women, superhuman), Shapes(circle, triangle, square, rectangle), )

>> Interfaces - 
  • Is collection of method declaration. 
  • We can not declare variable/property in interface.
  • Does not contain any logic (methods would not actually contain any logic only declaration)
  • We can not create object of Interface.
  • Only public methods defined. 
  • Defined to provide a common function names to the implementors.
  • Interfaces are defined to provide a common function names to the implementers. Interfaces is defined using interface keyword. We can not create instace of interface. To extend interface, implements operator is used. 
  • All declared method in interface must be define in child class. All methods in interfaces are public.
>> Traits
Traits are mechanism to code reuse in inheritance. Traits is similar to class and only intended to group functionality in consistent way.
Traits can not be instantiate. Multiple traits can be inserted into class by use statement and separated by comma. If inserting two traits with same name, fatal error produced.

>> Constants - (const) -
  • To access const variable out side class we need to use access specifier (ClassName::variablename), We can not call const variable using object ->
  • Once you declare a constant, it does not change. 
  • Note that the constant's name does not have a leading $. (e.g. const requiredMargin = 1.7;)

>> Abstract Classes - 
  • We can not create object of abstract class. 
  • An abstract class is one that cannot be instantiated, only inherited. 
  • all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibility. (e.g. abstract class MyAbstractClass)
>> Overriding
We can can re-declare Member functions from parent class in child class is called Overriding.

>> Overloading
2 methods with same name but with different paramters in class is called as overloading. PHP does not support 2 methods with same name in class. To achieve overloading we can use magic method.

Ex.

class Test {
    public function __construct(){
    }

    public function __call($method_name, $parameter) {
     if($method_name == 'functionOverloaded') {
    $count = count($parameter);
    switch($count)
case 1:
    echo "$method_name with $count argument";
break;
case 2:
    echo "$method_name with $count argument";
break;
}
    }
}

$obj = new Test();
$obj->functionOverloaded('Akshay');
$obj->functionOverloaded('Name','Akshay');


Ex.
Class Father {
function __constructor();
private $abc;
  public function name() {
}
}

Class Son extends Father {
parent::name(); // We can access parent class function when its overridden
public function name() {
}

Overloading means same function name having different numbers of arguments and different return type.
public function name($xyz) {
}
PHP does not support overloading because we can not create same name function more than 1 time in php class
}

$obj = new Father(); //Object instantiation or creation

>> Static Keyword - 

  • We can not mark class as Static.
  • class members or methods as static makes them accessible without needing an instantiation of the class.  
  • A member declared as static can not be accessed with an instantiated class object (though a static method can). (e.g. for class A public static $my_static = 'foo';  A::$my_static;)

>> Difference between const and static?
const can not modify, once define then we can not change value

>> Final Keyword - 
  • final modifier is allowed only for methods and classes not for variable in class.
  • class or method cannot be extended. 
  • If class is final class then it can not extendable by any child class. 
  • If method in parent class as final method then that method Cannot override in child class. (e.g. final public myMethod(){})

>> Association - When we associate classes or objects, each one keeps a reference to the ones it is associated with.

>> Aggregation - Aggregation implies encapsulation (hidding) of the parts of the composition. We can aggregate classes by using a (static) inner class (PHP does not yet support inner classes), in this case the aggregated class definition is not accessible, except through the class that contains it.

>> Multiple inheritance - A sub class can have characteristics from multiple parents and still can have its own characteristics.

>> Friend function - PHP doesn't support any friend-like declarations. (Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions.)

>> Message passing (interfacing) - Object sends data to another object or requests other object to invoke method.

>> Composition - simplify a complex problem into an easier problem. It makes different classes and objects to interact with each other thus making the problem to be solved automatically.

>> Method chaining - call more than one method or function of the class in single instruction.(e.g. $a = new Order(); $a->CreateOrder()->sendOrderEmail()->createShipment();)

>> Implement overloading in PHP - __call() is magic method used to implement overloading in PHP.

>> What are the differences between procedure-oriented (PO) languages and object-oriented (OO) languages?

POP more focus on functions and OOP focus on data and deals with objects created on the basis of classes
Procedure oriented language data has not security and in object oriented languange data has secured.
POP Gives importance to algorithm rather than data. OOP gives importance to data rather than algorithm
POP is Top Down approach. It starts execution from top to bottom. OOP is Bottom Up approach. It starts execution from bottom to top.

>> What are object oriented programming key concepts.
Data Abstraction, Encapsulation, Polymorphism, Dynamic Binding, Message passing, Re-usability, Delegation.

===========
===========

>> What are different Phases in Design Pattern? (Analysis, Design, Implementation)

  1. Analysis - Critical requirements needs to be identified.
  2. Design - Documenting understanding of the system. Design generates the blue print of the system. 
  3. Implementation - Programming is done as per the requirements gathered during the analysis and design phases.

>> Name the different Creational patterns in OO design?
  1. Factory pattern
  2. Single ton pattern
  3. Prototype pattern
  4. Abstract factory pattern
  5. Builder pattern

>> Explain about object oriented databases?

  1. Object oriented databases are very popular such as relational database management systems.
  2. Object oriented databases systems use specific structure through which they extract data and they combine the data for a specific output.
  3. These DBMS use object oriented languages to make the process easier.

>> What is abstract class?
  1. Basic use of abstract classes is to create templates for future classes. 
  2. Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. 
  3. Methods defined as abstract simply declare the method's signature - they cannot define the implementation.

>> What are Properties of Object Oriented Systems?
  1. Inheritance
  2. Encapsulation of data
  3. Extensibility of existing data types and classes
  4. Support for complex data types
  5. Aggregation
  6. Association 

>> What is UML? (Unified Modeling Language)
Is regarded to implement complete specifications and features of object oriented language.
We can do following things with UML,

  1. Manage project complexity.
  2. create database schema.
  3. Produce reports.
Types of UML Diagrams: 
  1. Class Diagrams
  2. Package Diagrams
  3. Object Diagrams
  4. Use Case Diagrams
  5. Sequence Diagrams
  6. Collaboration Diagrams
  7. State chart Diagrams
  8. Activity Diagrams
  9. Component Diagrams
  10. Deployment Diagrams

>> 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.

>> 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 throw the following fatal error when create object. Fatal error: Call to private BaseClass::__construct() from invalid context in.

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

>> 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.

>> What are the differences between procedure-oriented (PO) languages and object-oriented (OO) languages?

  • POP more focus on functions and OOP focus on data and deals with objects created on the basis of classes Procedure oriented language data has not security and in object oriented language data has secured. POP Gives importance to algorithm rather than data. 
  • OOP gives importance to data rather than algorithm POP is Top Down approach, It starts execution from top to bottom. 
  • OOP is Bottom Up approach. It starts execution from bottom to top.
Traditional programming has the following characteristics:
  1. Functions are written sequentially, so that a change in programming can affect any code that follows it.
  2. If a function(peace of code) is used multiple times in a system.
  3. Multiple sets of code can access and modify one set of data. 
  4. One set of code may rely on data in multiple places. 
  5. Multiple sets of code and data are required to work together.
  6. Changes made to any of the code sets and data sets can cause problems through out the system.
Object-Oriented programming takes a radically different approach:
  1. Code and data are merged into one indivisible item – an object.
  2. The object would contain all information/multiple-functions and functionality for that thing.
  3. A system is composed of multiple objects.
  4. features such as “class”, “instance”, “inheritance”, and “polymorphism” that increase the power and flexibility of an object.

    >> Types of Constructors?
    1. Default Constructor
    2. Parameterized Constructor
    3. Copy Constructor
    4. Static Constructor
    5. Private Constructor

      >> Data Hiding?
    Also known as information hiding or data encapsulation.

    >> Autoloading in php?
    Every time you want to use a new class in your PHP project, first you need to include this class (using include or require language construct, that’s right this are not functions). However if you have __autoload function defined, inclusion will handle itself.

    >> When to use Abstract class and when to use Interface?
    • Abstract class for partial implementation.
    • Interface use for full implementation.

    Abstract class example:-

    abstract Class Bank {

        public function deposit() {
           echo "Common deposit method";
        }
        public function withdraw() {
           echo "Common withdraw method";
        }
        abstract function calculateInterest();
    }

    Class Hdfc extends Bank {
       public function calculateInterest() {
         echo "Hdfc bank calculates interests rates";
       }
    }

    Interface example:- provide a contract to Bank that it must use all methods

    interface BankInterface {
        public function deposit() ;
        public function withdraw() ;
        public function calculateInterest() ;
    }

    >> Disadvantage of Inheritance?
    Time consuming, it take program to jump through all level of classes.
    Two Classes are get tightly couple, dependent of each other.

    >> How can we count number of times a PHP class is created ? 
    P class is created ?
    1- For single page we can put echo in class constructor and check same. 
    2- For multiple page we can search in document for class name.

    OR
    Add counter in class

    <?php 
    class BaseClass { 
      public static $counter = 0; 
      function __construct() { 
        self::$counter++; 
      } 

    new BaseClass(); 
    new BaseClass(); 
    new BaseClass(); 
    echo BaseClass::$counter; 
    ?>

    >> Overloading example? We can achieve method overloading using __call function. 
    2 methods with same name but with different paramters in class is called as overloading. PHP does not support 2 methods with same name in class. To implement overloading we can use magic method. 
    e.g. 
    class Test { 
        public function __construct(){ } 
        public function __call($method_name, $parameter) { 
            if($method_name == 'functionOverloaded') { 
            $count = count($parameter); 
            switch($count) 
            case 1: 
                //medhod with single parameter, you can write method body here
                echo "$method_name with $count argument"; 
                break; 
            case 2: 
                //medhod with two parameter, you can write method body here
                echo "$method_name with $count argument"; 
                break; 
            } 
        } 


    $obj = new Test(); 
    $obj->functionOverloaded('Akshay'); 
    $obj->functionOverloaded('Name','Akshay');


    ===========
    ===========
    Popular Example of Oops:- Humanbeing
    -- Session by SM

    /*
    Always program to INTERFACE
    */

    /*
    OPEN for extension, CLOSE for modification.
    */

    // TRAIT
    trait Human {
        public function work() {
        }
    }

    // INTERFACE
    interface HumanBeing { //interface
        public function eat();
        public function walk();
        public function body();
    }

    // INTERFACE
    interface HumanBeing2 { //interface
        public function eat();
        public function walk();
        public function body();
    }

    // ABSTRACT CLASS and ABSTRACT METHOD
    abstract class commanBehaviou { //abstract c
        public function eat() { // Abstract clas
       
        }
        abstract function sleep(); // For abstar
    }

    class Men extends commanBehaviou implements

        use Human; //multiple inhertance using T

        public function __construct() {
            echo "I am a men <br/><br/>";
        }
        public function walk() {}
        public function body(){
            $this->work(); // Use function defin
        }
        public function sleep(){
        }
    }

    class  Woman extends commanBehaviou implemen
        public function __construct() {
            echo "I am a woman <br/><br/>";
        }
        public function eat() {} //overridding
        public function walk() {}
        public function body(){}
        public function sleep(){
        }
    }

    class SuperHuman implements HumanBeing {
        public function __construct() {
            echo "I am a superhuman <br/><br/>";
        }
        public function eat() {}
        public function walk() {}
        public function body(){}
        public function sleep(){
        }
    }

    //Polymorphism
    class Factroy {
        public static function CreateHuman($type
            if($type === 'men') {
                return new Men();
            } else if($type === 'women') {
                return new Woman();
            } else if($type === 'superhuman') {
                return new SuperHuman();
            }
        }
    }

    //abstraction
    $men = Factroy::CreateHuman('men');
    $women = Factroy::CreateHuman('women');
    $women = Factroy::CreateHuman('superhuman');

    =======
    =======
    Abstract class example:-

    abstract Class Bank {

        public function deposit() {
           echo "Common deposit method";
        }
        public function withdraw() {
           echo "Common withdraw method";
        }
        abstract function calculateInterest();
    }

    Class Hdfc extends Bank {
       public function calculateInterest() {
         echo "Hdfc bank calculates interests rates";
       }
    }
    -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

    Clustering In PHP and Databases.

    Clustering In PHP

    >> What Is Clustering?

    • Having multiple computers working together for a single goal.
    • having multiple servers providing a website or service.
    • Load balancing is the first step in setting up a clustered environment for a web application.
    • For a cluster to work, not only do we need to load balance, but we also need to share the user sessions across all nodes.

    >> Clustering major advantage?
    Fault tolerance.
    Load balancing.

    >> Load Balancing?

    • load balancing consists of having a master node that accepts web requests, and funnels them to a farm of web servers to actually process the request.
    • each server has its own session to keep track of which server the user hit first, and keep redirecting them back to that same server on subsequent requests.
    • If Server 1 goes offline, the load balancer will transfer those users to the remaining nodes, but their sessions will not follow them--effectively logging out every user on Server 1.
    • bellow setup only gives you load balancing, not fault tolerance.

    e.g.
                                    | -> Server 1, Session 1
    Request -->> Load Balancer -->> | -> Server 2, Session 2
                                    | -> Server 3, Session 3
                                  
    >> Sharing Sessions (Fault tolerence).
    For a cluster to work, not only do we need to load balance, but we also need to share the user sessions across all nodes.
    To get proper PHP session sharing, every node essentially needs access to the other node's filesystem.


    >> NFS (Network File System), A Simple Solution to share sessions.
    we can get proper session sharing in our cluster is to set up a NFS (Network File System) share on a central location, and have all of the PHP servers use it for session storage.
    In bellow example we have set up a NFS share on the load balancer, using it as the central session storage location. On each node, we need to mount the NFS share and change the PHP session storage location to be in this mount point (symlinks are fine here).

    e.g.
                                               | <- NFS (symlink) -> Server 1, Session 1
    Request -->> Load Balancer, NFS share -->> | <- NFS (symlink) -> Server 2, Session 2
                                               | <- NFS (symlink) -> Server 3, Session 3
                                  

    Clustering In Mysql

    >> What does Clustering mean?

    • ability of several servers or instances to connect to a single database.
    • An instance is the collection of memory and processes that interacts with a database, which is the set of physical files that actually store data.
    e.g.
    shared-disk architecture - In which all data is stored centrally and then accessed via instances stored on different servers or nodes.

    e.g.
    Grid computing or Distributed caching - In this setup, data is still centrally managed but controlled by a powerful “virtual server” that is comprised of many servers that work together as one.

    >> Clustering advantages in high-volume database environments.

    • Fault tolerance: Because there is more than one server or instance for users to connect to, clustering offers an alternative, in the event of individual server failure.
    • Load balancing: The clustering feature is usually set up to allow users to be automatically allocated to the server with the least load.

    -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

    Database Related Notes:-
    -- Session by SM

    Engine behavior and stages - 

    Stage 1: cache - Check whether result already in cache, If in cache then it will return from cache
    e.g.

    1. caching is case sensitive so it will cache bellow data 2 queries in two different files
    • SELECT t fROM 
    • select t from 
    1. setting to be done bellow file to enable/disable database cache in mysql
    • mycnf.cnf 

    Stage 2: AST(Abstract Syntax Tree) - Here it perform "word wise" tokenisation of query parts(t1 t2 t3..)
    e.g.
    t1    t2 t3   t4    t5    t6
    select t from table where y=1;

    Stage 3: Parser - Syntax checking and sequence check/decide)

    Stage 4: query plan - [explain extended //use to get which query plan has decided by search engine]

    1. In query plan  it will decide which algorithm to be use for run queries, (micro seconds working)minimum time execute query will take
    2. to avoid engines query plans we can use "straight" keyword in joins

    e.g.
    select t1 from table1
    straight left join on table2
    straight right join on table3

    Stage 5: Get Records - [explain filesort ///debug purpose is filesort is used in your query]

    1. limit 0, 10 //is ok from zeroth record but
    2. limit 20000,10 - pagination like this should be avoid, because engine will take all records and flush first 20000 records and then get remaining
    3. where id > 10 limit 10 //micros seconds, this is best practice than above using limit

    Stage 6: Returns - Returns final records

    Different type of Engines in Mysql
    1. myisam - table lock, noforegin,fulltextsearch
    2. innodb - row lock(rows matched in where clause/search criteria),  foreign, transaction safe, [thread-safe],fulltextsearch - introduced in latest Innodb version
    3. csv,
    4. backhole,
    5. heap


    Engine similar to MYASAM, INNODB server/fast in speed

    1. spnix (http://sphinxsearch.com/)
    2. apache lucene

    Engine for fast indexing

    1. tokudb

    We can debug the performance using slow query log
    1. slow query log
    2. Percona Tools for MySQL - https://tools.percona.com/sign-in

    Databases type advanced optimization, this will explain all query behavior
    1. perconadb
    2. mariadb
    Indexing in mysql
    simple indexing - indexing on one column
    composit indexing - is best practice(depend on situation) to use indexing but developer need to maintain the sequence of composit colums in where clause.
    e.g. composit index on 2 columns(firstname,lastname)
    firstname,lastname -> combine to in one index

    slecte *  from t where firstname = 'y ' and last name='y'; //this will work
    slecte *  from t where firstname = 'y'; // this will also work
    slecte *  from t where lastname='y'// this will not work as we have not maintained sequence of column from 'firstname'

    e.g. composit index on 3 columns(firstname,lastname,dep)
    firstname,lastname,dep

    slecte *  from t where firstname = 'y ' and last name='y' and dep =''//this will work
    slecte *  from t where firstname = 'y'  and last name='y'; //this will also work
    slecte *  from t where last name='y' and dep =''; //this will not work

    Indexing is uses bellow searching techniques, while creating index we can define this

    1. binary search
    2. b+
    3. btree
    Full-text indexing - 
    Full-text indexes can be used with MyISAM tables and InnoDB tables (in MySQL 5.6+ only).
    Can be created only for varchar, char and text columns only.
    e.g. 
    CREATE FULLTEXT INDEX ft_index_name ON products (name, description);

    Master slave configuration
    on traditional db server all the queries will get fire on same server
    e.g. one db
    insert,select,update,delete

    On master and slave servers we can configure specific query to be executed on specific server and after than the sync will happen with in miscro second and changes gets relfected to all the server
    e.g. divide in 2 db
    insert
    select

    Replica(parallel servers) -

    Cluster(master and slave) -

    =======
    =======

    >> What is procedure and how to use it in my sql?

    • instead of writing code in php we can write stored procedure/functions as those are stored in compiled format those executes faster that php codes.
    • A stored procedure are compiled, verified and stored in the server database.
    • A stored procedure is typically treated like other database objects and controlled through server security mechanism.

    e.g. // create stored procedure
    DELIMITER $$ //we can use any syntax to delimiter
    CREATE PROCEDURE employee_pro (IN paramempemail VARCHAR(50), IN paramempname VARCHAR(50)) //number of parameter to procedure
    BEGIN
        SELECT employee_id, name, email_address FROM employee WHERE email_address = paramempemail and name = paramempname;
    END
    $$ DELIMITER ; //end of create store procedure

    e.g. // call procedure
    CALL `employee_pro`('myemail@mydomain.com');

    e.g. // this is delete procedure
    DROP PROCEDURE employee_pro;

    >> difference between char and varchar?

    • CHAR is fixed length.
    • VARCHAR is variable-length.

    If your content is a fixed size, you'll get better performance with CHAR.
    "your content is a fixed size" it means the rows of your table must contain all fixed size fields. You get no performance improvement if you use CHAR against VARCHAR in one field, but the table contains other fields that are VARCHAR (in order to have a performance increase the whole row has to be fixed-width.).
    >> CHAR

    • Used to store character string value of fixed length.
    • The maximum no. of characters the data type can hold is 255 characters.
    • It's 50% faster than VARCHAR.
    • Uses static memory allocation.

    >> VARCHAR
    • Used to store variable length alphanumeric data.
    • The maximum this data type can hold is up to
    • Pre-MySQL 5.0.3: 255 characters.
    • In MySQL 5.0.3+: 65,535 characters shared for the row.
    • It's slower than CHAR.
    • Uses dynamic memory allocation*.

    e.g. To use storage space efficiently must use VARCHAR Instead CHAR if variable length is variable
    Create table temp (City CHAR(10), Street VARCHAR(10));
    Insert into temp values('Pune','Oxford');
    select length(city), length(street) from temp;
    //output will be
    length(City)          Length(street)
    10                    6
    //final conclusion
    A CHAR(x) column can only have exactly x characters.
    A VARCHAR(x) column can have up to x characters.
    e.g.
    Value    CHAR(4)       Length
    ''               '    '              4 bytes
    'ab'          'ab  '             4 bytes
    'abcd'      'abcd'           4 bytes

    Value    VARCHAR(4)    Length
    ''                 ''                     1 byte
    'ab'             'ab'          3 bytes
    'abcd'         'abcd'        5 bytes


    >> Why do we need to use CHAR?

    • Char fields are stored inside the register.
    • This makes searching and indexing faster. 
    • VARCHAR have to be stored elsewhere and reference tables have to be used to find the content.

    >> How Many Groups of Data Types?
    MySQL support 3 groups of data types as listed below,

    • String Data Types - CHAR, NCHAR, VARCHAR, NVARCHAR, BINARY, VARBINARY, TINYBLOB, TINYTEXT, BLOB, TEXT, MEDIUMBLOB, MEDIUMTEXT, LONGBLOB, LONGTEXT, ENUM, SET
    • Numeric Data Types - BIT, TINYINT, BOOLEAN, SMALLINT, MEDIUMINT, 
    • Date and Time Data Types - DATE, DATETIME, TIMESTAMP, TIME, YEAR.

    >> What Are NULL Values?
    • NULL is a special value that represents no value. Here are basic rules about NULL values:
    • NULL presents no value.
    • NULL is not the same as an empty string ''.
    • NULL is not the same as a zero value 0.
    • NULL can be used as any data type.
    • NULL should not be used in any comparison options.
    • NULL has its own equality operator "IS".
    • NULL has its own not-equality operator "IS NOT".

    >> What Happens If NULL Values Are Involved in Expressions?

    • If NULL values are used in expressions, the resulting values will be NULL values. In other words:
    • Arithmetic expressions with NULL values result NULL values.
    • Comparison expressions with NULL values result NULL values.
    • Logical expressions with NULL values result NULL values.

    >> How To Calculate Expressions with SELECT Statements?
    There is no special SQL statements to calculate expressions. But you can use the "SELECT expression FROM DUAL" statement return the calculated value of an expression. "DUAL" is a dummy table in the server.
    e.g.
    SELECT (1+2)*3/4 FROM DUAL;//2.2500
    SELECT TRUE FROM DUAL; // 1
    SELECT TRUE AND FALSE FROM DUAL; // 0
    SELECT TIME(SYSDATE()) FROM DUAL;// 21:30:26

    >> How To Include Comments in SQL Statements?
    If you want to include comments in a SQL statement, you can first enter "--", then enter your comment until the end of the line.
    e.g.
    INSERT INTO links VALUES ('example.com'); -- Top rated!

    >> How To Escape Special Characters in SQL statements?

    • The escape character (\) needs to be escaped as (\\).
    • The single quote (') needs to be escaped as (\') or ('') in single-quote quoted strings.
    • The double quote (") needs to be escaped as (\") or ("") in double-quote quoted strings.
    • The wild card character for a single character (_) needs to be escaped as (\_).
    • The wild card character for multiple characters (%) needs to be escaped as (\%).
    • The tab character needs to be escaped as (\t).
    • The new line character needs to be escaped as (\n).
    • The carriage return character needs to be escaped as (\r).

    >> How To Concatenate Two Character Strings in mysql?
    If you want concatenate multiple character strings into one, you need to use the CONCAT() function,
    e.g.
    SELECT CONCAT('exam','ple','.com') FROM DUAL; // example.com

    >> How To Enter Characters or Enter Numeric Values as HEX Numbers?
    If you want to enter characters as HEX numbers, you can quote HEX numbers with single quotes and a prefix of (X), or just prefix HEX numbers with (0x).
    e.g. 
    SELECT 0x414243 FROM DUAL; // ABC
    SELECT 0x1000 + 0 FROM DUAL; // 4096

    >> How To Enter Binary Numbers in SQL Statements?
    Quote binary numbers with single quotes and a prefix of (B), or just prefix binary numbers with (0b)
    e.g.
    SELECT 0b1000 + 0 FROM DUAL; // 8

    >> How To Convert Numeric Values to Character Strings or Convert Character Strings to Numeric?
    using the CAST(value AS CHAR),  CAST(value AS DECIMAL) function.
    e.g.
    SELECT CAST(4123.45700 AS CHAR) FROM DUAL; // 4123.45700
    SELECT CAST('4123.45700' AS DECIMAL) FROM DUAL;

    >> How To Use IN Conditions?
    An IN condition is single value again a list of values. It returns TRUE, if the specified value is in the list. Otherwise, it returns FALSE.
    e.g.
    SELECT 3 IN (1,2,3,4,5) FROM DUAL; // 1
    SELECT 3 NOT IN (1,2,3,4,5) FROM DUAL; // 0

    >> How To Use LIKE Conditions?
    • '_' is used in the pattern to match any one character.
    • '%' is used in the pattern to match any zero or more characters.
    • ESCAPE clause is used to provide the escape character in the pattern.

    e.g.
    SELECT 'FIcenter.com' LIKE '%CENTER_com' FROM DUAL; // 1
    SELECT 'FIcenter.com' LIKE '%CENTER%' FROM DUAL; // 1

    >> How To Use Regular Expression in Pattern Match Conditions?
    Regular expression pattern condition: REGEXP
    e.g.
    SELECT 'FYICenter.com' REGEXP '.*fyi.*' FROM DUAL; // 1

    >> How To Use CASE Expression?
    e.g.
    SELECT CASE 'Sun' WHEN 'Mon' THEN 'Open'
       WHEN "Fri" THEN "Open" ELSE 'Closed' END FROM DUAL; // Closed

    >> SELECT All Records From Today Using PHP?
    e.g.
    $pdo = new PDO("mysql:host=localhost;dbname=test", 'root', '');
    $date = date("Y-m-d");
    $sql = "SELECT * FROM posts WHERE DATE(date_posted) = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array($date));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    var_dump($rows);

    >> What Is mSQL?
    Mini SQL (mSQL) is a light weight relational database management system capable of providing rapid access to your data with very little overhead. mSQL is developed by Hughes Technologies Pty Ltd.

    >> What Is SQL?
    SQL, SEQUEL (Structured English Query Language), is a language for RDBMS (Relational Database Management Systems). SQL was developed by IBM Corporation.

    >> What Is Table?
    A table is a data storage structure with rows and columns.

    >> What Is Column?
    A column defines one piece of data stored in all rows of the table.

    >> What Is Row?
    A row is a unit of data with related data items stored as one item in one column in a table.

    >> What Is Primary Key?
    A primary key is a single column or multiple columns defined to have unique values that can be used as row identifications.

    >> What Is Foreign Key?
    A foreign key is a single column or multiple columns defined to have values that can be mapped to a primary key in another table.

    >> What Is Index?
    An index is a single column or multiple columns defined to have values pre-sorted to speed up data retrieval speed.

    >> What Is View?
    A view is a logical table defined by a query statement.

    >> What Is Join?
    Join is data retrieval operation that combines rows from multiple tables under certain matching conditions to form a single row.

    >> What Is Union?
    Join is data retrieval operation that combines multiple query outputs of the same structure into a single output.

    >> What Is ISAM?
    ISAM (Indexed Sequential Access Method) was developed by IBM to store and retrieve data on secondary storage systems like tapes.

    >> What Is MyISAM?
    MyISAM is a storage engine used as the default storage engine for MySQL database. MyISAM is based on the ISAM (Indexed Sequential Access Method) concept and offers fast data storage and retrieval. But it is not transaction safe.

    >> What Is InnoDB?
    InnoDB is a transaction safe storage engine developed by Innobase Oy (an Oracle company now).

    >> What Is BDB (BerkeleyDB)?
    BDB (BerkeleyDB) is transaction safe storage engine originally developed at U.C. Berkeley. It is now developed by Sleepycat Software, Inc. (an Oracle company now).

    >> What Is CSV?
    CSV (Comma Separated Values) is a file format used to store database table contents, where one table row is stored as one line in the file, and each data field is separated with comma.

    >> What Is Transaction?
    A transaction is a logical unit of work requested by a user to be applied to the database objects. MySQL server introduces the transaction concept to allow users to group one or more SQL statements into a single transaction, so that the effects of all the SQL statements in a transaction can be either all committed (applied to the database) or all rolled back (undone from the database).
    e.g.
    START TRANSACTION; // BEGIN start a new transaction.
           INSERT INTO customer VALUES (10, 'Heikki'); // insert data
    COMMIT; // commits the current transaction, making its changes permanent.
    SET autocommit=0; //disables(0) or enables(1) the default autocommit mode for the current session.
    I      NSERT INTO customer VALUES (15, 'John');
    ROLLBACK; // rolls back the current transaction, canceling its changes.


    >> What Is Commit?
    Commit is a way to terminate a transaction with all database changes to be saved permanently to the database server.

    >> What Tools Available for Managing MySQL Server?
    • mysqld - MySQL server daemon. You can use "mysqld" to start your MySQL server. "mysqld" is MySQL server daemon program which runs quietly in background on your computer system. Invoking "mysqld" will start the MySQL server on your system. Terminating "mysqld" will shutdown the MySQL server.
    • mysqladmin - A command-line interface for administrators to perform server administration tasks.
    • mysql - A command-line interface for end users to manage user data objects.
    • mysqlcheck - A command-line interface for administrators to check and repair tables.
    • mysqlshow - A command-line interface for end users to see information on tables and columns.
    • mysqldump - A command-line interface for administrators or end users to export data from the server to files.
    • mysqlimport - A command-line interface for administrators or end users to load data files into tables program tool to load data into tables.

    >> What Are the "mysql" Command Line Options?

    • "-?" - Displays a help message on how to use "mysql" and terminates the program.
    • "-u userName" - Specifies a user name for the server to authenticate when connecting to the server.
    • "-p[password]" - Specifies a password for the server to authenticate when connecting to the server.
    • "-h hostName" - Specifies a host name where the MySQL server is running. The default host name "localhost".
    • "-P portNumber" - Specifies a port number where the MySQL server is listening for connections. The default port number is 3306.
    • "-e command" - Executes the specified command and terminates the program.
    • "-t" - Specifies that the query output is displayed in text table format. This is the default display format for interactive mode.
    • "-H" - Specifies that the query output is displayed in HTML table format.
    • "-X" - Specifies that the query output is displayed in XML element format.

    >> How Many SQL DDL Commands Are Supported by "mysql"?
    4 SQL Data Definition Language (DDL) i.e. CREATE, RENAME, ALTER, DROP

    >> How Many SQL DML Commands Are Supported by "mysql"?
    4 SQL Data Manipulation Language (DML)  i.e. INSERT, DELETE, UPDATE, SELECT

    >> What Are the Non-Standard SQL Commands Supported by "mysql"?

    • "SHOW infoName" - Shows basic information of based on the specified information name.
    • "SET ..." - Sets new values to server or connection session variables.
    • "GRANT ..." - Grants access privileges to users.
    • "REVOKE ..." - Revokes access privileges from users.
    • "CHECK TABLE tableName" - Checks the specified table for errors.
    • "ANALYZE TABLE tableName" - Analyzes the specified table.
    • "REPAIR TABLE tableName" - Repairs the specified table.
    • "BACKUP TABLE tableName" - Backs up the specified table.
    • "RESTORE TABLE tableName" - Restores the specified table.
    • "USE databaseName" - Uses the specified database as the current database.
    • "HELP topicName" - Returns help information on the specified topic.

    >> Redirect Page After Five Seconds Using PHP, JavaScript Or META Tags.
    //using meta tag
    <meta http-equiv="refresh" content="5;url=http://example.com/detecting-ajax-requests-with-php/">

    //using php
    header( "refresh:5;url=http://example.com/php-forcing-https-over-http/" );

    //or using php
    sleep(5);
    header('Location: http://example.com/php-forcing-https-over-http/');

    //using javascript
    <script>setTimeout(function () { window.location.href= 'http://example.com/php-forcing-https-over-http/';}, 5000);</script>

    >> php Setting CURL Timeout Options.?
    CURLOPT_CONNECTTIMEOUT // attempting to connect to a given URL
    CURLOPT_TIMEOUT //maximum amount of time that the request should take
    e.g.
    $url = 'http://localhost/tester/log.php';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    //Tell cURL to return the response output as a string.
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    if(curl_errno($ch)){
        throw new Exception(curl_error($ch));
    }

    >> Send A PUT Request With PHP.
    We can use 'CURLOPT_PUT' of curl
    curl_setopt($ch, CURLOPT_PUT, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array("id" => 1)));

    >> Remove Duplicate Elements From An Array.
    we can remove duplicate elements of array using array_unique function.
    $example = array_unique(array('dog', 'cat', 'horse', 'cat', 'dog'));
    var_dump($example); // array('dog', 'cat', 'horse')

    >> How To Convert Character Strings to Dates?
    can use the STR_TO_DATE(string, format) function.
    e.g.
    SELECT STR_TO_DATE('Friday, January 31, 1997', '%W, %M %e, %Y') FROM DUAL; // 1997-01-31

    >> How To Increment Dates by 1?
    can use the DATE_ADD(date, INTERVAL 1 DAY) function
    e.g.
    SELECT DATE_ADD(DATE('1997-01-31'), INTERVAL 1 DAY) FROM DUAL; // 1997-02-01

    >> How To Decrement Dates by 1?
    you can use the DATE_SUB(date, INTERVAL 1 DAY) function
    e.g.
    SELECT DATE_SUB(DATE('1997-03-01'), INTERVAL 1 DAY) FROM DUAL; // 1997-02-28

    >> How To Calculate the Difference between Two Dates?
    can use the DATEDIFF(date1, date2) functio
    e.g.
    SELECT DATEDIFF(DATE('1997-02-28'), DATE('1997-03-01')) FROM DUAL; // -1

    >> How To Calculate the Difference between Two Time Values?
    can use the TIMEDIFF(time1, time2) function.
    e.g.
    SELECT TIMEDIFF(TIME('19:26:50'), TIME('09:26:50')) FROM DUAL; // 10:00:00

    >> How To Present a Past Time in Hours, Minutes and Seconds?
    can use the TIMEDIFF(NOW(), pastTime) function
    e.g.
    SELECT TIMEDIFF(NOW(), '2006-07-01 04:09:49') FROM DUAL; // 06:42:58
    SELECT TIME_FORMAT(TIMEDIFF(NOW(), '2006-06-30 04:09:49'), %H hours, %i minutes and %s seconds ago.') FROM DUAL; //30 hours, 45 minutes and 22 seconds ago.

    >> How To Extract a Unit Value from a Date and Time?
     can use the EXTRACT(unit FROM expression) function
    e.g.
    SELECT EXTRACT(DAY FROM NOW()) FROM DUAL; // 28
    SELECT EXTRACT(HOUR FROM NOW()) FROM DUAL; // 23
    SELECT EXTRACT(SECOND FROM NOW()) FROM DUAL; // 36

    >> What Are Date and Time Functions?

    • ADDDATE(date, INTERVAL expr unit) - Adding days to a date. Same as DATE_ADD().
    • ADDTIME(time1, time2) - Adding two time values together.
    • CURDATE() - Returning the current date. Same as CURRENT_DATE().
    • CURTIME() - Returning the current time. Same as CURRENT_TIME().
    • DATE(expression) - Returning the date from the expression.
    • DATEDIFF(date1, date2) - Returning dates difference in days.
    • DATE_ADD(date, INTERVAL expr unit) - Adding days to a date.
    • DATE_SUB(date, INTERVAL expr unit) - Subtracting days from a date.
    • DATE_FORMAT(date, format) - Returning a character string representing a date.
    • DAY(date) - Returning an integer representing the day of the month. Same as DAYOFMONTH()
    • DAYNAME(date) - Returning the name of week day.
    • DAYOFMONTH(date) - Returning an integer representing the day of the month.
    • DAYOFWEEK(date) - Returning an integer representing the day of the week.
    • DAYOFYEAR(date) - Returning an integer representing the day of the year.
    • EXTRACT(unit FROM date) - Returning a unit value of a date and time.
    • HOUR(time) - Returning the hour value of a time
    • LAST_DAY(date) - Returning a date representing the last day of the month based on the given date.
    • LOCALTIME() - Returning the current date and time. Same as NOW().
    • MAKETIME(hour,minute,second) - Returning a date based on the given time unit values.
    • MICROSECOND(time) - Returning the microsecond unit value of the given time.
    • MINUTE(time) - Returning the minute unit value of the given time.
    • MONTH(date) - Returning the month unit value of the given date.
    • MONTHNAME(date) - Returning the month name of the given date.
    • NOW() - Returning the current date and time.
    • SECOND(time) - Returning the second unit value of the given time.
    • SEC_TO_TIME(seconds) - Converting a second value to a time
    • STR_TO_DATE(str,format) - Converting a character string to a date.
    • SUBDATE(date,INTERVAL expr unit) - Subtracting days from a date.
    • SUBTIME(expr1,expr2) - Subtracting a time from another time.
    • SYSDATE() - Returning current date and time.
    • TIME(expr) - Returning a time from the given date and time.
    • TIMEDIFF(expr1,expr2) - Returning the difference between two times.
    • TIME_TO_SEC(time) - Converting a time to a second value.
    • WEEKDAY(date) - Returning the weekday unit value of a given date.
    • YEAR(date) - Returning the year unit value of a given date.


    >> How Many Ways to Get the Current Time?

    • SELECT NOW() FROM DUAL; // 2006-07-01 10:02:41 
    • SELECT CURRENT_TIME() FROM DUAL; // 10:02:58
    • SELECT SYSDATE() FROM DUAL; // 2006-07-01 10:03:21 
    • SELECT CURRENT_TIMESTAMP() FROM DUAL; // 2006-07-01 10:04:03 
    • SELECT LOCALTIME() FROM DUAL; // 2006-07-01 10:07:37 
    • SELECT UTC_TIME() FROM DUAL; // 14:09:22 
    • SELECT UTC_TIMESTAMP() FROM DUAL; // 2006-07-01 14:09:49 

    >> How To Get a List of Columns in an Existing Table?
    use the "SHOW COLUMNS FROM tableName" command
    e.g.
    SHOW COLUMNS FROM tableName;

    >> How To See the CREATE TABLE Statement of an Existing Table?
    use the "SHOW CREATE TABLE tableName" command
    e.g.
    SHOW CREATE TABLE tableName;

    >> How To Create a New Table by Selecting Rows from Another Table?
    use the "CREATE TABLE ... SELECT" statement
    e.g.
    CREATE TABLE newTableName SELECT * FROM existingTableName;

    >> How To Add a New Column to an Existing Table?
    use the "ALTER TABLE ... ADD COLUMN" statement.
    e.g.
    ALTER TABLE tip ADD COLUMN author VARCHAR(40);

    >> How To Rename an Existing Table?
    use the "ALTER TABLE ... RENAME TO" statement.
    e.g.
    ALTER TABLE tableName RENAME TO newTableName;

    >> How To Create an Index for a Given Table?
    use the "CREATE INDEX" statement
    e.g.
    CREATE INDEX tableName_columName ON tableName(columName);

    >> How To Get a List of Indexes of a Given Table?
    use the "SHOW INDEX FROM tableName" command to get a list of all indexes.
    e.g.
    SHOW INDEX FROM tableName;

    >> How To Create a New View?
    by using the "CREATE VIEW viewName AS selectStatement" statement.
    e.g.
    CREATE VIEW faqComment AS SELECT f.id, f.title, f.description, c.message FROM faq f, comment c WHERE f.id = c.faqID;

    >> What Happens If the UPDATE Subquery Returns No Rows?
    MySQL will provide a NULL value to the SET clause.

    >> How To Delete All Rows in a Table?
    Use the DELETE statement with no WHERE clause.
    Use the TRUNCATE TABLE statement.

    >> How To Filter Out Duplications in Returning Rows?
    use the keyword DISTINCT in the SELECT clause.
    e.g.
    SELECT DISTINCT * FROM tableName;

    >> What Are Group Functions?
    Group functions are functions applied to a group of rows. like COUNT(*), MIN(exp), MAX(exp), AVG(exp).

    >> Can Group Functions Be Mixed with Non-group Selection Fields?
    Non-group fields can not be mixed with group fields in the SELECT clause.
    e.g.
    SELECT COUNT(*), url FROM fyi_links; // will give error
    SELECT tag, COUNT(*), MIN(created), AVG(counts) FROM fyi_links GROUP BY tag; // this is correct
    SELECT tag, YEAR(created), COUNT(*) FROM fyi_links GROUP BY tag, YEAR(created) // we can use multiple columns in group by
      
    >> How To Apply Filtering Criteria at Group Level?
    at the group level by using the HAVING clause inside the GROUP BY clause. Note group functions can also be used in HAVING conditions.
    e.g.
    SELECT tag, COUNT(*), MIN(created), AVG(counts) FROM fyi_links GROUP BY tag HAVING AVG(counts) > 3.8;
    SELECT tag, COUNT(*), MIN(created), AVG(counts) FROM fyi_links GROUP BY tag HAVING COUNT(*) > 2;

    >> How To Count Duplicated Values in a Column?
    use the GROUP BY ... HAVING clause
    e.g.
    SELECT first_name, COUNT(*) FROM fyi_team GROUP BY first_name HAVING COUNT(*) > 1;

    >> Can Group Functions Be Used in the ORDER BY Clause?
    We can sort the groups by using group functions in the ORDER BY clause.
    e.g.
    SELECT tag, YEAR(created), COUNT(*) FROM fyi_links GROUP BY tag, YEAR(created) ORDER BY COUNT(*) DESC;

    >> How To Join Two Tables in a Single Query?

    • Inner Join: Returns only rows from both tables that satisfy the join condition.
    • Left Outer Join: Returns rows from both tables that satisfy the join condition, and the rest of rows from the first (left) table.
    • Right Outer Join: Returns rows from both tables that satisfy the join condition, and the rest of rows from the second (right) table.
    • Full Outer Join: Returns rows from both tables that satisfy the join condition, the rest of rows from the first (left) table, and the rest of rows from the second (right) table.

    >> What Is a Subquery?
    A subquery is a SELECT statement used as part of the selection criteria of the main SELECT statement.
    //subqueries are used in the following Boolean operations:
    "expression IN (subquery)"
    "expression NOT IN (subquery)"
    "EXISTS (subquery)"
    "NOT EXISTS (subquery)"
    e.g.
    SELECT id, url, tag, YEAR(created) As year FROM fyi_links WHERE EXISTS (SELECT * FROM fyi_rates WHERE fyi_rates.id = fyi_links.id);

    >> How To Return Top 5 Rows?
    If you want the query to return only the first 5 rows, you can use the LIMIT clause, which takes one parameter as the maximum number of rows to return.
    e.g.
    SELECT id, url, counts, tag FROM fyi_links ORDER BY counts DESC LIMIT 5;

    >> How To Return the Second 5 Rows?
    If you want to display query output in multiple pages with 5 rows per page, and the visitor wants to see the output for the second page, you need to display query output from row 6 to row 10.
    e.g.
    SELECT id, url, counts, tag FROM fyi_links ORDER BY counts DESC LIMIT 5, 5; // 0-5 first 5 rows, 6-10 second 5 rows

    >> How To Use UNION to Merge Outputs from Two Queries Together?
    If you have two queries that returns the same row fields, you can merge their outputs together with the UNION operator.
    e.g.
    (SELECT id, url, created FROM fyi_links WHERE created > '2005-12-31' ORDER BY created DESC)
    UNION
    (SELECT id, url, created FROM fyi_links WHERE created <= '2005-12-31' ORDER BY created DESC LIMIT 1); //out put will combination/merge together of result of both queries

    >> What Is a User Account?
    A user account is identified by a user name and defines the user's attributes, including the following:
    Password for connection authentication.
    User privileges, for examples: Shutdown_priv, Create_priv, Drop_priv, Insert_priv, Update_priv, Delete_priv, etc..
    Various limits, for example: max_questions, max_updates, max_connections, etc.

    >> What Are the Predefined User Accounts?
    There is only one predefined user account called "root":
    "root" was created during the installation process.
    "root" has no password initially. You need to assign a new password as soon as you finishes the installation.
    "root" has all access privileges granted.
    e.g.
    mysql -u root
    USE mysql
    SELECT User, Password, Shutdown_priv, Create_priv FROM user WHERE User = 'root'; // root Y Y

    >> How To Add a New User Account?
    If you want to add a new user account, you can connect to the server as "root" and use the "CREATE USER ..." command.
    e.g. CREATE USER userName IDENTIFIED BY 'passwordString';

    mysql -u root mysql

    //create user
    CREATE USER dev IDENTIFIED BY 'retneciyf';

    //rename user name
    RENAME USER dev TO dba;

    //delete user
    DROP USER dev;

    >> How To Test a New User Account and Password?
    If you have new user created with a password, you test it using "mysql" program with the "-u" and "-p" options.
    e.g.
    mysql -u dev // gives error access denited using password null
    mysql -u dev -pTEST // gives error access denited using password YES/wrong password
    mysql -u dev -pretneciyf // gives access as password is correct i.e. retneciyf

    >> How To Change the Password for Your Own User Account?
    use the "SET PASSWORD ..." command to change the password of the current user account.
    e.g. SET PASSWORD = 'encryptedPasswordString'; or SET PASSWORD = PASSWORD('passwordString');
    mysql -u root mysql
    SET PASSWORD = 'retneciyf'; // this will give error Password hash should be a 41-digit hexadecimal number
    SET PASSWORD = PASSWORD('retneciyf'); // correct way

    //set password for another user account
    SET PASSWORD FOR userName = 'encryptedPasswordString';
    SET PASSWORD FOR userName = PASSWORD('passwordString');

    >> What Are User Privileges?
    MySQL offers many user privileges to control user accesses to different funtions and data objects. Here are some commonly used privileges:

    • ALL - All privileges.
    • CREATE - Allows the user to use CREATE TABLE commands.
    • ALTER - Allows the user to use ALTER TABLE commands.
    • DROP - Allows the user to use DROP TABLE commands.
    • DELETE - Allows the user to use DELETE commands.
    • INSERT - Allows the user to use INSERT commands.
    • UPDATE - Allows the user to use UPDATE commands.
    • SELECT - Allows the user to use SELECT commands.
    • SHUTDOWN - Allows the user to use "mysqladmin shutdown".
    • INDEX - Allows the user to create and drop indexes.
    • CREATE USER - Allows the user to manage user accounts.
    • CREATE VIEW - Allows the user to user "CREATE VIEW" commands.
    • USAGE - No privileges.
    >> How Many Scope Levels Can User Privileges Apply?
    MySQL supports 5 scope levels a user privilege can be granted:

    • Global Level - A privilege granted at this level applies to all databases on the server. Privileges granted at the global level stored in "mysql.user" table.
    • Database Level - A privilege granted at this level applies to all tables in the specified database. Privileges granted at the global level stored in "mysql.db" table.
    • Table Level - A privilege granted at this level applies to all columns in the specified table. Privileges granted at the global level stored in "mysql.tables_priv" table.
    • Column Level - A privilege granted at this level applies to only the specified column. Privileges granted at the global level stored in "mysql.columns_priv" table.
    • Routine Level - A privilege granted at this level applies to only the specified stored function procedure. Privileges granted at the global level stored in "mysql.procs_priv" table.

    e.g.
    GRANT CREATE ON *.* TO dev; // assigning Global Level privileges
    GRANT CREATE ON databaseName.* TO userName; // assigning Database Level 'CREATE' privileges
    SHOW GRANTS; // show all previlleges to user
    SHOW GRANTS for dev; // show all previlleges to dev user
    GRANT SELECT ON databaseName.* TO userName; // Give a User Read-Only Access to a Database

    >> Where Are User Privileges Stored on the Server?

    • "mysql.user" - Stores privileges granted at the global level.
    • "mysql.db" - Stores privileges granted at the database level.
    • "mysql.table_priv" - Stores privileges granted at the table level.
    • "mysql.columns_priv" - Stores privileges granted at the column level.
    • "mysql.procs_priv" - Stores privileges granted at the routine level.

    >> What Are the "mysqld" Command Line Options?

    • "mysqld" offers a big list of command line options. Here are some commonly used options:
    • "--help" - Displays a short help message on how to use "mysqld".
    • "--verbose --help" - Displays a long help messages on how to use "mysqld".
    • "--console" - Specifies that the server to send error messages to launching window.
    • "--datadir=dirName" - Specifies that server data goes to the specified director.
    • "--init-file=fileName" - Specifies that server to execute all commands in the specified file at startup time.
    • "--log=fileName" - Specifies that server to write query logs to the specified file.
    • "--log-bin=fileBaseName" - Specifies that server to write binary logs to a file with the specified file base name.
    • "--log-error=fileName" - Specifies that server to write error logs to the specified file.
    • "--port=portNumber" - Specifies that server to listen client connections at the specified port number.
    • "--version" - Returns the version information of the server.

    >> How To Turn on Query Logs?
    If you want MySQL to write query logs to a file, you can use the "--log=fileName" option at the "mysqld" command line.
    e.g.
    mysqld --log=\mysql\logs\query.log // turn on query log
    mysqld --log-error=\mysql\logs\error.log // turn on error.log

    >> What Is Binary Log File?
    MySQL server binary log file plays an important role in restoring database changes to the server. Main features on binary log files are:

    • Binary logs can be turned on by "--log-bin=fileBaseName" option on "mysqld".
    • Binary logs only records statements that are changing data in the database. So a simple SELECT statement will be not recorded in binary logs.
    • Binary logs are organized in multiple files with names like: base.index, base.000001, base.000002, etc. Each time when you restart the server, a new binary log file will be created.
    • Binary log files can be viewed by "mysqlbinlog" program.
    • Binary log files can be piped into back to the server as "mysqlbinlog base.000001 | mysql" for restoring data changes after a server crash.

    e.g.
    mysqld --log-bin=\mysql\logs\binary // turn on binary logs

    >> How To Run MySQL Server on a Different Port?
    By default, MySQL will listen at port number 3306 for any client connections. can change this by starting the server with "--port=portNumber" option.
    e.g.
    cd \mysql\bin
    mysqld --log=\mysql\logs\query.log
     --log-bin=\mysql\logs\binary.log
     --log-error=\mysql\logs\error.log --console --port=8888
    e.g.
    \mysql\bin\mysql -u root -pretneciyf --port=8888 test // By this we can connect mysql on different port

    >> mysql and mysqli?

    • mysql - This is the standard MySQL API extension. It does not support the improved authentication protocol used in MySQL 5.0, nor does it support prepared statements or multiple statements.
    • mysqli - Stands for "MySQL, Improved". This extension is available only in PHP 5. It is intended for use with MySQL 4.1.1 and later. This extension fully supports the authentication protocol used in MySQL 5.0, as well as the Prepared Statements and Multiple Statements APIs. In addition, this extension provides an advanced, object-oriented programming interface.

    >> How To Get a List of Databases from MySQL Servers?
    $con = mysql_connect('localhost:8888', 'dev', 'iyf');
    $res = mysql_list_dbs($con);

    >> What Are Storage Engines?
    Storage engines are programs that are integrated into MySQL database management system to manage data tables.

    • MyISAM Storage Engine - MySQL default storage engine. Based on ISAM database concept. MyISAM is not transaction safe.
    • InnoDB Storage Engine - A transaction safe storage engine developed by Innobase Oy (an Oracle company).
    • BDB (BerkeleyDB) Storage Engine - A transaction safe storage engine originally developed at U.C. Berkeley. Sleepycat Software, Inc. was created in 1996 to continue BDB development. Sleepycat is an Oracle company now.
    • CSV Storage Engine - A simple storage engine storing data as text files using comma-separated values format.
    • MEMORY (HEAP) Storage Engine Storage Engine - A storage engine storing data in computer main memory.


    >> Where Table Data Is Stored by the MyISAM Storage Engine?
    By default, MySQL provides \mysql\data directory for all storage engines to store table data. Under \mysql\data directory, each database will have its own subdirectory to store table data.
    If a new table is created with the MyISAM storage engine, several files will be created. For example, the new table "fyi_isam" created in the previous tutorial exercise will result the following files:
    e.g.
    cd \mysql\data\fyi
    dir // will list fyi_isam.frm, fyi_isam.MYD, fyi_isam.MYI
    fyi_isam.frm - Created by MySQL to store "fyi_isam" table format.
    fyi_isam.myd - Created by MyISAM to store "fyi_isam" table data. "myd" stands for "MyData". The data file size is 0, because there is no data row stored in the table yet.
    fyi_isam.myi - Created by MyISAM to store "fyi_isam" table index. "myi" stands for "MyIndex". The primary key column "id" is indexed by default.

    >> How To Check and Repair MyISAM Tables?
    use the "CHECK TABLE tableName" and "REPAIR TABLE tableName" commands to try to repair it.

    >> Where Table Data Is Stored by the InnoDB Storage Engine?
    By default, MySQL provides \mysql\data directory for all storage engines to store table data. Under \mysql\data directory, InnoDB storage engine will create 3 files to store and manage all tables that use the InnoDB storage engine:

    • ibdata1 - Contains data for all InnoDB tables. "ibdata1" starts with 10MB, but it will be extended, if needed.
    • ib_logfile0 - Log file 1 with 5MB.
    • ib_logfile1 - Log file 2 with 5MB.
    If a new table is created with the InnoDB storage engine, one format file named as databaseName\tableName.frm will be created. Table data and index data will be stored in "ibdata1". For example, the new table "fyi_inno" created in the previous tutorial exercise will result the following files:
    e.g.
    cd \mysql\data
    dir fyi\fyi_inno.* // fyi_inno.frm
    dir  // this will output list of file ibdata1, ib_logfile0, ib_logfile1

    >> Where Table Data Is Stored by the BDB Storage Engine?
    By default, MySQL provides \mysql\data directory for all storage engines to store table data. Under \mysql\data directory, the BDB storage engine will create one file for each table to store table data and index data.
    If a new table is created with the BDB storage engine, one format file named as databaseName\tableName.frm will be created. Another file named as databaseName\tableName.db to store table data and index data. For example, the new table "fyi_bdb" created in the previous tutorial exercise will result the following files:
    e.g.
    cd \mysql\data

    dir fyi\fyi_bdb.* // will display files fyi_bdb.db, fyi_bdb.frm

    =======

    =======
    Database related Interview Questions ans Answers

    >> What is sql injection ?
      SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications.

    >> Where is physically indexes file store in Mysql?

    For the MyISAM engine, a table's indexes are stored in the .MYI file (in the data directory, along with the .MYD and .frm files for the table).
    For InnoDB engine, (no separate file created for indexing in InnoDB), the indexes are stored in the tablespace means  along with the table. If innodb_file_per_table option is set, the indexes will be in the table's .ibd file along with the .frm file

    >> What are triggers and working and storing/calling process of triggers.
    -- Trigger created to fast search and stored in .myi(for myism) file for each search criteria.

    >> What is trigger and how to use/create?
        SHOW TRIGGERS; //to show all triggers
        Create trigger trig_name BEFORE/AFTER INSERT/UPDATE/DELETE ON table_name sql_query;
        DROP TRIGGER trig_name; // to delete trigger
        example:- (http://www.mysqltutorial.org/create-the-first-trigger-in-mysql.aspx)
    DELIMITER $$
    CREATE TRIGGER before_employee_update
        BEFORE UPDATE ON employees
        FOR EACH ROW
    BEGIN
        INSERT INTO employees_audit
        SET action = 'update',
         employeeNumber = OLD.employeeNumber,
    lastname = OLD.lastname,
    changedat = NOW();
    END$$
    DELIMITER ;

    >> Mysql complex search feature? (Solr) (http://lucene.apache.org/solr/)
    If you want to use complex search feature then you can use SOLR search.
    It is file based search different framework have support for it.
    Solr is the popular, blazing-fast, open source enterprise search platform built on Apache Lucene.
    Solr is highly reliable, scalable and fault tolerant, providing distributed indexing, replication and load-balanced querying, automated failover and recovery, centralized configuration and more. Solr powers the search and navigation features of many of the world's largest internet sites.

    >> ACID properties in Database?
    (ACID: Atomicity, Consistency, Isolation, Durability)

    >> Following are Difference between MyISam and InnoDB
    MyISAM Advantage
    1. Faster than InnoDB for search results
    2. support Full-text indexing
    3. When use "select" statement, gives faster results as compare to Innodb

    InnoDB Advantage
    1. Support for transactions (ACID: Atomicity, Consistency, Isolation, Durability).
    2. Better "Row-level locking"
    3. Foreign key constraints
    4. Repair better incase of table corruption
    5. Support Rollback abilities
    6. Automatic crash recovery

    MyISAM Disadvantage
    1. Cascading delete/update not support
    2. Not support ACID compliance
    3. Row limit 4,284,867,296
    4. When we use indexing, insert/update/delete become bit slow
    5. Not Support Row Locking

    InnoDB Disadvantage
    1. Not support full text indexing (<5.6 mysql version)
    2. Can't compressed
    3. Search Slow as compare to MyISAM

    >> Change table engine to MyISAM?
    ALTER TABLE `tableName` ENGINE = MYISAM;

    >> Change table engine to innodb?
    ALTER TABLE `tableName` ENGINE = innodb

    >> 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.

    >>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 DESC limit 1,1

    >> 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;

    >> 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.

    >> Why use MySQLI instead of MySQL?

    • MySQL is Not in Active Development
    • Officially deprecated as of PHP 5.5
    • Will fully removed in PHP 7.0
    • OOP is absent
    • Doesn't Support asynchronous queries
    • Doesn't Support Prepared statements
    • Doesn't Support Multiple Statements
    • MySQL leads to SQL injection vulnerabilities
    • In MySQL, we must use mysql_real_escape_string to avoid attacks where as in MySQLI its inbuilt.

    >> What is replacement of MySQL
    MySQLi
    PDO - PHP Database Object

    >> How to checked MySQLi is installed OR Not?
    if(function_exists('mysqli_connect')){
     echo "MySQLi enabled";
    }else{
     echo "MySQLi NOT enabled";
    }

    OR
    you can check in phpinfo.

    >> How to enable MySQLi in php.ini? If not already enabled?
    open php.ini file and find php_mysqli.dll remove the semicolon from start of extension=php_mysqli.dll

    >> How to connect to MySQLi?
    $mysqliObj = mysqli_connect("localhost", "root", "", "mydb");

    >> Give Example of Free the Memory after getting data?
    $rs->free();

    >> Give Syntax for Transactions in MySQLi?
    /*starts transaction*/
    try {
      /* switch autocommit status to FALSE. Actually */
      $conn->autocommit(FALSE);
      $res = $conn->query($sql1);
      if($res === false) {
        throw new Exception('Wrong SQL: ' . $sql . ' Error: ' . $conn->error);
      }
       $res = $conn->query($sql2);
      if($res === false) {
        throw new Exception('Wrong SQL: ' . $sql . ' Error: ' . $conn->error);
      }
       /** You can use number of SQL Query **/
      $conn->commit();
      echo 'Transaction completed successfully!';
    } catch (Exception $e) {
      echo 'Transaction failed: ' . $e->getMessage();
      $conn->rollback();
    }
    /* switch back autocommit status */
    $conn->autocommit(TRUE);

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

    CREATE FULLTEXT INDEX ft_index_name ON products (name, description);


    -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    Linux Notes:- 

    Understanding Linux File Permissions - 
    >> Permission Groups

    • owner - The Owner permissions apply only the owner of the file or directory, they will not impact the actions of other users.
    • group - The Group permissions apply only to the group that has been assigned to the file or directory, they will not effect the actions of other users.
    • all users - The All Users permissions apply to all other users on the system, this is the permission group that you want to watch the most.

    >> Permission Types

    • read - The Read permission refers to a user's capability to read the contents of the file.
    • write - The Write permissions refer to a user's capability to write or modify a file or directory.
    • execute - The Execute permission affects a user's capability to execute a file or view the contents of a directory.

    >> The permission in the command line is displayed as: _rwxrwxrwx 1 owner:group
     > User rights/Permissions (_rwxrwxrwx)

    •     The first character that I marked with an underscore is the special permission flag that can vary.
    •     The following set of three characters (rwx) is for the owner permissions.
    •     The second set of three characters (rwx) is for the Group permissions.
    •     The third set of three characters (rwx) is for the All Users permissions.

    > Following that grouping since the integer/number displays the number of hardlinks to the file. ( 1 )
    > The last piece is the Owner and Group assignment formatted as Owner:Group. (owner:group)

    >> Explicitly Defining Permissions
      > The Permission Groups used are:

    •     u - Owner
    •     g - Group
    •     o - Others
    •     a - All users

    > The potential Assignment Operators are + (plus) and - (minus); these are used to tell the system whether to add or remove the specific permissions.

    • To make this modification you would invoke the command: chmod a-rw filename
    • To add the permissions above you would invoke the command: chmod a+rw filename

    >> Using Binary References to Set permissions

    •  r = 4
    •  w = 2
    •  x = 1

        So to set a file to permissions on file1 to read _rwxr_____, you would enter chmod 740 file1.


    Console commands:- 

    >> Create a new Database.
    $ create database mydb

    >> List of all databases
    $ show databases

    >> Create Backup of all Database.
    $ mysqldump -h localhost -u username -p password --all-databases > dumpAllDatabases.sql

    >> Create Backup of database (database name mydb) OR Export database into file.
    $ mysqldump -h localhost -u username -p mydb > dump.sql

    >> Create Backup of database structure only
    $ mysqldump -u username -p -no-data mydb > dump.sql

    >> Import SQL file into  database

    $ mysql -h localhost -u username -p password mydb < dump.sql

    >> What is iptables?
    iptables is a utility program that allows a system administrator to configure the tables provided by the Linux kernel firewall. We use Iptables to allow/deny traffic for incoming/outgoing.
    e.g.
    iptables applies to IPv4
    ip6tables applies to IPv6
    arptables applies to ARP
    ebtables to Ethernet frames.

    When someone try to established a connection, iptables looks for a rule in its list to do as per rules.



    -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    Interview Questions and Answers Notes:-


    PHP Common Interview Questions and Answers:- 

    >> Difference between PHP 5 and PHP 7?

    • Improved performance. Its twice as fast as PHP 5. 
    • spaceship operator added (e.g. $abc = $abc??null)
    • Adds Anonymous Classes (e.g. new class($i) {function __constrcut($i){}})
    • Facilitates Imports From the Same Namespace (e.g. use Foo\Bar\{class1, class2, class 3 as Class C})
    • Lower Memory Consumption. 
    • Scalar type declarations. (Accurate Type Declarations)
    • Return and Scalar Type Declarations. 
    • Consistent 64-bit support Many fatal errors converted to Exceptions Secure random number generator. 
    • Various old and unsupported SAPIs and extensions are removed from the latest version 
    • null coalescing operator removed 
    • Anonymous Classes Added. 
    • Zero cost asserts 
    • PHP 7 uses new Zend Engine 3.0

    e.g. scalar type declaration example
    we can define the input type and return type in PHP 7 like bellow function,
    function mydata(int $var): int { }

    >> Types of errors in PHP

    • Notices - for undefined variables,
    • Warnings - included Files not exists
    • Fatal - Causing termination of program. require_once file not found.
    >> Different ways to do caching?

    • FileSystem - Creating new file with key as file name and value as file content.
    • APC - Alternative PHP cache. Also called as memory based cache. It stores the php parsed scripts. (Use it when we have a single webservers)
    • Memcache - Stored on different server.(Use it when we have multiple webservers)
    • Redis -  Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries.Redis contains key value pairs.
    >> What is session and cookie and working on same?
    -- Session are created on server side in tmp directory if user/browser hits first time the unique number generated and stored in cookie is called as phpsessionid. Based on session id the fetching of session variable will done. If you delete the sessionId then new session id created and session reference is saved based on this new session id. If cookie is disabled in browser then php server sends session id on every request in url.
    -- sessions are stored on the server, and cookies are stored on the user’s computers in the text file format.
    -- Cookies can not hold multiple variables,But Session can hold multiple variables.
    -- We can set expiry for a cookie,The session only remains active as long as the browser is open.
    -- Users do not have access to the data you stored in Session,Since it is stored in the server.
    -- Session is mainly used for login/logout purpose while cookies using for user activity tracking.

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

    >> How to pass data in header while using CURL?
    $url='http://example.com';
    $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);

    >> How to pass JSON Data in CURL?
    $url = "http://example.com";
    $jsonData = '{"name":"test name", "email":"contact@email"}';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    curl_close($ch);

    >> What are benefits of 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

    >> 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

    >> Google Analytics and Adobe Analytics?
    Google Analytics and Adobe Analytics both are web analytics services used in the measurement, collection, analysis and reporting of web data for purposes of understanding and optimizing web usage. However, Web analytics is not just a process for measuring web traffic, but can be used as a tool for business and market research, and to assess and improve the effectiveness of a website.


    >> What are the different types of runtime errors in PHP?

    • Fatal errors
    • Parser errors
    • Startup errors.

    >> What is IP address? How to show IP address of the client?

    • A unique string of numbers separated by full stops that identifies each computer using the Internet Protocol to communicate over a network.
    • $_SERVER["REMOTE_ADDR"]

    >> difference between unset() and unlink()

    • unset() - mark variable as undefined
    • unlink() - delete the existing file

    >> enable error reporting in PHP

    • ini_set('display_errors', 1); // check if ini has this setting
    • error_reporting(E_ALL);

    >> What are Traits?

    • Traits are a mechanism that allows you to create reusable code in languages like PHP where multiple inheritance is not supported. 
    • A Trait cannot be instantiated on its own.

    >> PHP Global Variables?

    • Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. $GLOBALS, $_SERVER, $_REQUEST, $_POST, $_GET, $_FILES, $_ENV, $_COOKIE, $_SESSION.
    • PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. $GLOBALS[index] varibale is also accessible from outside the function.
    • $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.
    • PHP $_REQUEST is used to collect data after submitting an HTML form.

    >> Can you extend a Final defined class?
    No, you cannot extend a Final defined class. A Final class or method declaration prevents child class or method overriding.

    >> What are the __construct() and __destruct() methods in a PHP class?
    All objects in PHP have Constructor and Destructor methods built-in. The Constructor method is called immediately after a new instance of the class is being created, and it’s used to initialize class properties. The Destructor method takes no parameters.

    >> The value of the variable input is a string 1,2,3,4,5,6,7. How would you get the sum of the integers contained inside input?
    echo array_sum(explode(',',$input));

    >> What are SQL Injections, how do you prevent them and what are the best practices?
    SQL injections are a method to alter a query in a SQL statement send to the database server. That modified query then might leak information like username/password combinations and can help the intruder to further compromise the server.

    >> What are PSRs? Choose 1 and briefly describe it. (http://www.php-fig.org/psr/)

    • PSR (PHP Standards Recommendations) are PHP Standards Recommendations that aim at standardising common aspects of PHP Development. (PSR0, PSR1, PSR2, PSR3, PSR4, PSR6, PSR7, PSR11, PSR13, PSR16)
    • PSR-0: Autoloading Standard
    • PSR-1: Basic Coding Standard
    • PSR-2: Coding Style Guide
    • PSR-3: Logger Interface
    • PSR-4: Autoloader
    • PSR-6: Caching Interface
    • PSR-7: HTTP message interfaces
    • PSR-11: Container Interface
    • PSR-13: Hypermedia Links
    • PSR-16: Simple Cache

    >> What does FIG stand for?
    The FIG stands for Framework Interoperability Group. The name until recently was “PHP Standards Group” but this was somewhat inaccurate of the intentions of the group.

    >> What are the aims of the PHP-FIG?
    The idea behind the group is for project representatives to talk about the commonalities between our projects and find ways we can work together. Our main audience is each other, but we’re very aware that the rest of the PHP community is watching. If other folks want to adopt what we’re doing they are welcome to do so, but that is not the aim. Nobody in the group wants to tell you, as a programmer, how to build your application.

    >> Rules for defining variables in PHP.
    These are the following rules for naming a PHP variable:All variables in PHP start with a $ sign, followed by the name of the variable.A variable name must start with a letter or the underscore character _.A variable name cannot start with a number.A variable name in PHP can only contain alpha-numeric characters and    underscores (A-z, 0-9, and _).A variable name cannot contain spaces. we cannot add any special characters in variable name except _ (UNDERSCORE). Variable names in PHP are case sensitive, it means $x and $X are two different variables. So be careful while defining variable names. Same rule applies to the constants.

    >> What’s the difference between using mysql_ functions and PDO?
    PDO (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases. PDO with prepared statements. It is a well-designed API and will let you more easily move to another database (including any that supports ODBC) if necessary. Mysql, Mysqli, PDO these are different APIs to access a MySQL backend. mysqli is a replacement for the mysql functions, with object-oriented and procedural versions. It has support for prepared statements.

    >> GET and POST default size in php?

    • GET - up to 2000 character (depending on browser)
    • POST - 8MB default (we can modify this in php.ini 'post_max_size')
    ========
    ========

    REST API and SOAP protocol

    >> What is REST Api?
    REST (representational state transfer) API (Application Programming Interfaces).

    >> What is SOAP?
    SOAP (Simple Object Access Protocol).

    >> Types of Web Services in PHP?
    SOAP
    XML-RPC
    REST

    >> What is API?
    API is known as the Application Programming Interface and is offered by both the client and the server.
    In the client world, this is offered by the browser whereas in the server world it's what is provided by the web service which can either be SOAP or REST.

    >> What is Restful web services
    Any web service that is defined on the principles of REST can be called a RestFul web service.
    A service which is built on the REST architecture is called a RESTful service.
    REST stands for REpresentational State Transfer.
    REST is used to build Web services that are lightweight, maintainable, and scalable in nature.
    The underlying protocol for REST is HTTP, which is the basic web protocol.
    REST is a way to access resources. Now REST defines a way on how these resources can be accessed.
    e.g. example of resources are
    you could have a server that could be hosting important documents or pictures or videos. All of these are an example of resources.
    If a client, say a web browser needs any of these resources, it has to send a request to the server to access these resources.

    >> key elements of a RESTful implementation?
    Resources - The first key element is the resource itself. Let assume that a web application on a server has records of several employees. Let's assume the URL of the web application is http://example.com. Now in order to access an employee record resource via REST, one can issue the command http://example.com/employee/1 - This command tells the web server to please provide the details of the employee whose employee number is 1.
    Request Verbs - (GET, POST, PUT, and DELETE). These describe what you want to do with the resource.
    e.g.
    POST – This would be used to create a new employee using the RESTful web service.
    GET - This would be used to get a list of all employee using the RESTful web service.
    PUT - This would be used to update all employee using the RESTful web service.
    DELETE - This would be used to delete all employee using the RESTful web service.
    Request Headers – These are additional instructions sent with the request. These might define the type of response required or the authorization details.
    Request Body - (POST request has request body)Hence, the request body would have the details of the resource which is required to be added to the server.
    Response Body – (Json/XML response) the response from server interms of json/xml.
    Response Status codes – (200 success etc.) general codes which are returned along with the response from the web server.

    >> Why Restful?

    • Heterogeneous languages and environments – This is one of the fundamental reasons which is the same as we have seen for SOAP as well.
    • It enables web applications that are built on various programming languages to communicate with each other.
    • Web applications can reside on different environments, some could be on Windows, and others could be on Linux.
    • The event of Devices - Nowadays, everything needs to work on Mobile devices, whether it be the mobile device, the notebooks, or even car systems. Again Restful API's can make this job simpler you really don't need to know what is the underlying layer for the device.
    • Finally is the event of the Cloud – Applications now need to be developed in such a way that they are made compatible with the Cloud. So since all Cloud based architectures work on the REST principle, it makes more sense for web services to be programmed on the REST based architecture to make the best use of Cloud based services.

    >> Restful Architecture?

    • State and functionality are divided into distributed resources.
    • Means that every resource should be accessible via the normal HTTP commands of GET, POST, PUT, or DELETE. 
    • So if someone wanted to get a file from a server, they should be able to issue the GET request and get the file. If they want to put a file on the server, they should be able to either issue the POST or PUT request. And finally, if they wanted to delete a file from the server, they an issue the DELETE request.
    • The architecture is client/server, stateless, layered, and supports caching.
    • Stateless means that the state of the application is not maintained in REST.

    >> What is stateless?
    Stateless means that the state of the application is not maintained in REST.
    e.g.
    The server should not maintain any sort of information between requests from the client. It's a very simple independent question-answer sequence. The client asks a question, the server answers it appropriately. The client will ask another question. The server will not remember the previous question-answer scenario and will need to answer the new question independently.
    e.g. If you delete a resource from a server using the DELETE command, you cannot expect that delete information to be passed to the next request.
    In order to ensure that the resource is deleted, you would need to issue the GET request. The GET request would be used to first get all the resources on the server. After which one would need to see if the resource was actually deleted.

    >> RESTFul Characteristics?

    • Client-Server (client <-> server)
    • Stateless - The server should not maintain any sort of information between requests from the client.
    • Cache (client -> cache -> server)
    • Layered System - The concept of a layered system is that any additional layer such as a middleware layer can be inserted between the client and the actual server hosting the RESTFul web service.
    • Interface/Uniform Contract - This is the underlying technique of how RESTful web services should work. 

    >> REST is an Architectural style in which a web service can only be treated as a RESTful service if it follows the constraints of being.
    Client Server
    Stateless
    Cacheable
    Layered System
    Uniform Interface

    >> REST Short summary.

    • REST stands for REpresentational State Transfer. REST is used to build web services that are lightweight, maintainable, and scalable in nature.
    • More and more applications are moving to the Restful architecture. This is because there are a lot of people now using mobile devices and a wider variety of applications moving to the cloud.
    • The main aspects of REST are the resources which reside on the server and the verbs of GET, POST, PUT and DELETE, which can be used to work with these resources.
    • Visual Studio and.Net can be used to create Restful web services.

    >> Difference between SOAP and REST?
    One of the key differences between SOAP and REST is that SOAP is a protocol and REST is an architectural pattern.

    • Other key differences between the SOAP and REST protocol is that the requests sent via REST tend to be much lighter than SOAP. Because of this, applications don't require much bandwidth to use REST web services over SOAP.
    • Security is another major concern with Web services and SOAP. REST is good when working with web services open to the public, but if security is required, then the SOAP API has the necessary implementation for the same.
    • REST has the ability to have a caching solution which will help save responses which have been received from the server. In such cases, the client does not need to make the same request to the server and can make use of the cache to get the desired response.
    • SOAP cannot make use of REST since SOAP is a protocol and REST is an architectural pattern. REST can make use of SOAP as the underlying protocol for web services, because in the end it is just an architectural pattern.
    • SOAP is a protocol. SOAP was designed with a specification. It includes a WSDL file which has the required information on what the web service does in addition to the location of the web service.
    • SOAP uses service interfaces to expose its functionality to client applications. In SOAP, the WSDL file provides the client with the necessary information which can be used to understand what services the web service can offer.
    • REST use Uniform Service locators to access to the components on the hardware device.
    • SOAP requires more bandwidth for its usage. Since SOAP Messages contain a lot of information inside of it, the amount of data transfer using SOAP is generally a lot. REST does not need much bandwidth when requests are sent to the server. 
    • SOAP can only work with XML format. As seen from SOAP messages, all data passed is in XML format. REST permits different data format such as Plain text, HTML, XML, JSON, etc. But the most preferred format for transferring data is JSON.

    >> When to use REST and when to use SOAP?
    REST services should be used in the following instances,
    Limited resources and bandwidth.
    Statelessness
    Caching – If there is a need to cache a lot of requests then REST is the perfect solution.
    Ease of coding – Coding REST Services and subsequent implementation is far easier than SOAP.

    SOAP services should be used in the following instances,
    Asynchronous processing and subsequent invocation – client needs a guaranteed level of reliability and security.
    A Formal means of communication – if both the client and server have an agreement on the exchange format.
    Stateful operations –
    If you need a proper information flow wherein some information from one request needs to flow into another then SOAP is more suited for that purpose.
    e.g.
    online purchasing site.
     The state of the cart items needs to be transferred to the payment page for further processing.

    >> Challenges with the SOAP API?

    • WSDL file - The WSDL document will contain all information such as the data types being used in the SOAP messages and what all operations are available via the web service. WSDL file were to change as per the business requirements.
    • Document size – The other key challenge is the size of the SOAP messages which get transferred from the client to the server. Because of the large messages, using SOAP in places where bandwidth is a constraint can be a big issue.

    >> Challenges with the REST API?

    • Lack of Security – for confidential data being passed between the client and the server, REST should not use and its worst mechanism to be used for web services. 
    • Lack of state – Most web applications require a stateful mechanism.

    >> Difference between SOAP and other Remote Access Techniques.
    Remote access techniques such as the RPC (Remote Procedure calls) methods were in common use before SOAP and REST came along.

    • DCOM(Distributed Component Object Model) – is a proprietary Microsoft technology for clients to access remote components. Drawback is additional coding was required to ensure that applications built in other programming languages could work with DCOM based web services. It was up to the client application to free up resources when no longer required. when the client sent the request, it was up to the client to ensure that the request was wrapped or marshaled in a correct way.
    • Java RMI (Java Remote Method Invocation) –  this was Java implementation on how remote objects could be called through remote procedure calls. The biggest restriction of this technology was that Java RMI could only be run on a Java Virtual Machine. This meant that the calling application also has to be run on the Java framework in order to make use of Java RMI.
    • CORBA(Common Object Request Broker Architecture)– This system was put in place to ensure that applications built on various platforms could talk to each other. CORBA was based on an object-oriented architecture, but it was not necessary for the calling application to be based on this architecture. The major disadvantage of this technique was that it has to be developed in a separate language called the Interface Definition Language, and it just presented an additional language that had to be learnt by developers to make use of the CORBA system.
    • The main differences between SOAP and these techniques are as follows,
    • Working over HTTP – All of the RPC techniques have one big limitation, and it is that they don't work in accordance with the HTTP protocol. Since all applications on the web had to work on this protocol, this used to be a major roadblock for clients which had to access these RPC-style web services.
    • Working with non-standard ports – Since the RPC style web services did not work in accordance with the HTTP protocol, separate ports had to be open for them in order for clients to access the functionality from these web services.

    >> Security Threats and Countermeasure.
    One of the security measures available for the HTTP is the HTTPS protocol.
    HTTPS is the secure way of communication between the client and the server over the web.
    HTTPS makes use of the Secure Sockets layer or SSL for secure communication.
    Both the client and the server will have a digital certificate to identify themselves as genuine when any communication happens between the client and the server.
    In a standard HTTPS communication between the client and the server, the following steps take place,
    The client sends a request to the server via the client certificate. When the server sees the client certificate, it makes a note in its cache system so that it knows the response should only go back to this client.
    The server then authenticates itself to the client by sending its certificate. This ensures that the client is communicating with the right server.
    All communication thereafter between the client and server is encrypted. This ensures that if any other users tries to break the security and get the required data, they would not be able to read it because it would be encrypted.
    There can come a time when the client can talk to multiple servers. An example given below shows a client talking to both a database and a web server at a time. In such cases, not all information can pass through the https protocol. This is where SOAP comes in action to overcome such obstacles by having the WS-Security specification in place. With this specification, all security related data is defined in the SOAP header element.

    ========
    ========

    >> What is composer?
    Composer is PHP dependency manager used for installing dependencies of PHP applications.

    >> What is php artisan in Laravel. List out some artisan commands ?
    PHP artisan is the command line interface/tool included with Laravel. It provides a number of helpful commands that can help you while you build your application easily. eg. php artisan list, php artisan help, php artisan make, php artisan -version, php artisan make model model_name, php artisan make controller controller_name.

    >> Which template engine Laravel use ?
    Laravel uses Blade Templating Engine.

    >> Define ORM ?
    Object-relational Mapping (ORM) is a programming technique for converting data between incompatible type systems in object-oriented programming languages.

    >> Does Laravel support caching?
    Yes, Laravel supports popular caching backends like Memcached and Redis.
    By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the file system .For large projects it is recommended to use Memcached or Redis.

    >> Explain Laravel Eloquent

    • Laravel’s Eloquent ORM is one the most popular PHP ORM (OBJECT RELATIONSHIP MAPPING).
    • It provides a beautiful, simple ActiveRecord implementation to work with your database.
    • In Eloquent each database table has the corresponding MODEL that is used to interact with table and perform a database related operation on the table.

    >> What is Laravel Eloquent?
    Eloquent ORM provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

    >> What is Luman?
    Lumen is a new project from Laravel creator Taylor Otwell. It's a "micro-framework", meaning it's a smaller, faster, leaner version of a full web application framework. It competes other popular micro-frameworks, Slim and Silex.

    >> What is database migration in Laravel?    
    Migrations are like version control for your database, allowing your team to easily modify and share the application's database schema.

    >> What is HTTP middleware?
    Middleware provide a convenient mechanism for filtering HTTP requests entering your application.

    >> Type of middleware in Laravel and what is Terminable Middleware?
    There are 2 types of middleware in Laravel,
    Global
    Route
    We can write Terminable Middleware in route middle ware to performs some task after the response has been sent to the browser. This can be accomplished by creating a middleware with “terminate” method in the middleware.

    >> What are Bundles, Reverse Routing and The IoC container?

    • Bundles - In Laravel, bundles are called packages for different specific functionality. You can also create your own custom package to use it.
    • Reverse Routing - It allows you to change your routes and application will update all of the relevant links as per this link.
    • IoC container - Laravel inversion of control container (IoC container) is a powerful tool for managing class dependencies. Dependency injection is a method of removing hard-coded class dependencies. Instead, the dependencies are injected at run-time, allowing for greater flexibility as dependency implementations may be swapped easily.

    >> List out latest features of Laravel.

    • Inbuilt CRSF (cross-site request forgery) Protection.
    • Inbuilt paginations
    • Reverse Routing
    • Query builder
    • Route caching
    • Database Migration
    • IOC (Inverse of Control) Container Or service container.
    ===========
    ===========
    JavaScript Interview Questions and Answers:- 

    >> Idiomatic JavaScript (https://github.com/necolas/idiomatic-js)

    • Principles of writing consistent, idiomatic JavaScript:- 
    • All code in any code-base should look like a single person typed it, no matter how many people contributed.
    • The following outlines the practices that I seek to adhere to in all code that I originally author - 
    • "Part of being a good steward to a successful project is realizing that writing code for yourself is a Bad Idea. If thousands of people are using your code, then write your code for maximum clarity, not your personal preference of how to get clever within the spec."

    >> What is closures?
    Whenever you defined a the function within another function, the inner function has access to variables in the outer function.

    >> Why it can access to variables in the outer function?
    Because It is defined as var , which means it is global variable.

    >> Loading JavaScript files asynchronously?
    means load JavaScript file parallel.

    >> Can i declare a variable as CONSTANT like in PHP?
    Yes, const MY_CONSTANT_NAME = "value that will never change";//If you want to constant value then it throws error

    >> How do I declare a namespace in JavaScript?
    var myNamespace = {
        function1: function() {   },
        function2: function() {    }
    }
    myNamespace.function2();

    >> What is difference between event.preventDefault() and return false in Javascript?
    e.preventDefault() will prevent the default event from occuring.
    Means If this method is called, the default action of the event will not be triggered.
    e.g. This method does not accept any arguments.
    jQuery(document).ready(function(){
        $('a.link').click(function (e) {
            e.preventDefault();
        });
    });

    e.stopPropagation() will prevent the event from bubbling.
    Means If this method is called, It Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
    e.g. This method also does not accept any arguments.
    jQuery(document).ready(function(){
        $('a.link').click(function (e) {
            e.stopPropagation();
        });
    });

    >> What is basic difference between $(document).ready() and window.onload?
    $(document).ready(): This event occurs after the HTML document has been loaded.
    window.onload This event when all content (e.g. html, js, images) also has been loaded.

    >> Is JavaScript a pass-by-reference OR pass-by-value?
    passed by reference

    >> What is CDATA? When it is required?
    CDATA stand for "Character Data" and it means that the data in between tags.
    CDATA is required when you need an document to parse as XML.

    >> How to compare two Dates in javaScript?
    var date1 = new Date();
    var date2 = new Date(date1);
    if(d1.getTime() === d2.getTime()){
        /* Both Time are are Same **/
    }else{
        /* Time are are Different**/
    }

    >> How to merge two array?
    var array1 = ["One","Two"];
    var array2 = ["Three", "Four"];
    var mergeArray = array1.concat(array2);
    console.log(mergeArray);

    >> How to add element in the begining OR at the end of array?
    var myArray = new Array('a', 'b', 'c', 'd');
    myArray.push('end');
    myArray.unshift('start');
    console.log(myArray);

    >> How can I format numbers as money format?
    var monthlyExpanse=98765.432;
    monthlyExpanse.toFixed(2);//98765.43
    monthlyExpanse.toFixed(1);//98765.4

    >> How to convert a number to hexadecimal,octal ?
    var myNumber= 500;
    //console.log(myNumber.toString(16));//1f4
    //console.log(myNumber.toString(8));//764

    >> How to convert a hexadecimal,octal number to decimal?
    var hexaDecimal='1f4';
    var octal='764';
    console.log(parseInt(hexaDecimal,16)); //500
    console.log(parseInt(octal,8)); //500

    >> What are different Data-Types of JavaScript?
    Following are different data-type in JavaScript.
    String
    Number
    Boolean
    Function
    Object
    Null
    Undefined


    >> What is public, private and static variables in JavaScript?
    Public Varaible: A variable which associate to object and is publicily available with object.
    For Example:
    function funcName1 (name) {
     this.publicVar='1';
    }

    Private Variable: A variable which associate to object and is limited available.
    For Example:
    function funcName2 (name) {
     var privateVar='1';
    }

    Static variable: A static member is shared by all instances of the class as well as the class itself and only stored in one place.
    For Example:
    function funcName3 (name) {

    }
    // Static property
    funcName3.name = "Web Technology Experts Notes";

    >> How to achieve inheritance in JavaScript
    "Pseudo classical inheritance" and "Prototype inheritance"

    >> What is prototype in JavaScript?
    All the JavaScript objects has an object and its property called prototype & it is used to add and the custom functions and property. See Following example in which we create a property and function.
    e.g.
    var empInstance = new employee();
    empInstance.deportment = "Information Technology";
    empInstance.listemployee = function(){
    }

    >> How to modify the URL of page without reloading the page?
    use pushState javascript function.
    window.history.pushState('page2', 'This is page Title', '/newpage.php');

    >> How to convert JSON Object to String?
    var myobject=['Web','Technology','Experts','Notes']
    JSON.stringify(myobject);

    >> How to convert JSON String to Object?
    var jsonData = '{"name":"web technology","year":2015}';
    var myobject = JSON.parse(jsonData);
    console.log(myobject);

    >> How can I check if one string contains another substring?
    var haystack = "full-string-here";
    var needle = 'string';
    if(haystack.indexOf(needle)>=0){
        console.log('String found');
    }else{
    console.log('String Not found');
    }

    >> How do you get a timestamp in JavaScript?
    new Date().getTime();

    >> What is Asynchronous in Ajax?
    We can set the Asynchronous value as true OR false.
    Async=true -- Ajax request execute independently, Its response can come earlier than other request which is execute later .
    Async=false -- Ajax request does not execute independently, Its response can comes when earlier request finished.
    Never use "async: false", Because it has been deprecated. async must be true, whether you are using core ajax, jQuery ajax OR prototype ajax etc.

    >> What are different readystate stages in Ajax Call?
    In Ajax call, ready state have 5 values and are following:
    0- The request is not initialized.
    1- The request has been set up.
    2- The request has been sent.
    3- The request is in process.
    4- The request is complete.

    >> What is Comet in web application?
    Comet is a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it

    >> How to do synchronous AJAX requests?
    set async=false in ajax call.
    e.g.
    function getRemote() {
        return $.ajax({
            type: "GET",
            url: '/ajax/url',
            async: false
        }).responseText;
    }

    >> How to send a ajax call with https when you are http page(Suppose same domain)?
    Add following in header of Ajax Call.
    Access-Control-Allow-Origin: http://www.domain.com

    >> How to call multiple Ajax request in single click with callback function?
    You can use $.when method of jQuery.
    $.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) )
      .then( myFunc, myFailure );

    >> How to send ajax request to another domain using JSONP?
    JSONP is simple way to overcome XMLHttpRequest same domain policy.
    With use of JSONP you can send the request to another domain.
    JSONP is "JSON with Padding", In JSONP we include another domain URL with a parameter i.e callback.
    callback's value have a function name which must be present in your webpage.
    e.g.
    <script>
    function myCalllbackFunction(data){
      console.log(data);
    }
    </script>
    <script src="http://twitter.com/status/user_timeline/padraicb.json?count=10&amp;callback=myCalllbackFunction" type="text/javascript"></script>

    >> What is cache:false in Ajax call?
    If cache:false then ajax response will not come from browser cache.

    >> How to Abort ajax requests using jQuery?
    Use abort() function to abort a ajax request.
    e.g.
    var ajaxRequest = $.ajax({
        type: "POST",
        url: "/ajax",
        data: "name1=value1&name2=value2",
        success: function(msg){
           //here success comes
        }
    });
    //Abort the ajax request
    ajaxRequest.abort();
    When you abort the ajax call, you can see ajax request as aborted in browser console.

    >> How to send AJAX call without jQuery?
    //For sending ajax call in IE7+, Firefox, Chrome, Opera, Safari
    XMLHttpRequest
    //For sending ajax call in IE
    use ActiveXObject
    e.g.
    function callAjax(url,method) {
        var xmlhttp;
        if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
                // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                if (xmlhttp.status == 200) {

                    //console.log(xmlhttp.responseText);
                }
            }
        }

        xmlhttp.open(method, url, true);
        xmlhttp.send();
    }
    callAjax('/ajax?data=1','GET')

    >> How to make all ajax call cache Free?
    $.ajaxSetup ({
        // Disable the caching of AJAX responses for all Ajax
        cache: false
    });

    >> What js library are available to use the Ajax?

    • JQuery
    • MooTools
    • Prototype
    • YUI Library
    • Backbone js

    >> What is XMLHttpRequest?
    XMLHttpRequest is an API available to web browser scripting languages (i.e. JavaScript).
    It is used to send HTTP/HTTPS requests to a web server and load the server's response into the script.

    >> Can I send Ajax Request to another domain?
    No, you can't do this

    >> What are disadvantage of Ajax?
    It does not crawl to search Engine.

    >> Define JSON?
    JSON is JavaScript Object Notation.
    It is text-based standard design for interchange the information Between two or more different application. It is also very light as compare to XML and human readable.
    Json - is stardard format that is human readable used to transmit information from one server to another server.
    Jsonp - is a json with ability to transmit information to another domain.

    >> What is JSON-RPC?
    Remote Procedure call protocol with use of JSON. It is similar to XML-RPC only difference, It use JSON instead of XML.

    >> What type of response we can get in Ajax Response?

    • text data
    • html data
    • JSON data
    • XML data

    >> What is ReactJS?
    ReactJS released in March 2013.
    React is front end library developed by Facebook.
    React is used to handle the view part of Mobile application and Web application.
    React is uses JSX which is simiar to HTM.

    >> How many Grid Classes are available in Bootstrap Grid System?
    xs: phones
    sm : tablets
    md : desktops
    lg : large desktops

    >> How user agent is sent to Server?
    When an browser send request to web server. then request header is sent to web server along with request data

    >> Who is User agent spoofing?
    we change Browser user agent help of User-Agent Spoofing.
    Spoofing means behave differently than in actuality.
    Spam bots, Web scrapers, hackers uses the spoofing to hide their identity.

    >> What is WebSocket?
    WebSocket is a protocol providing full-duplex communication channels over a single TCP connection.
    WebSocket can do communication between client to server OR server to client.

    >> What is Dojo?
    It is JavaScript framework used for rapid development of cross-platform applications and web sites. Also known as Dojo Toolkit.

    >> What is npm install? (NodeJS package manager)
    NPM is a NodeJS package manager. It is used to install the node programs.

    >> Difference between MVC and MVP design pattern?
    MVC Full form is Model View Controller, MVP Full form is Model View Presenter.
    MVC is Front Controller based approach, MVP is Page Controller based approach.
    In MVC When request comes, Controller interact with Model (and get data) and then send the data to view. In MVP  When request comes, View interact with Presenter (presenter interact with model for get data and do format) and presenter sent back the data to view.
    In MVC Controller is responsible for displaying the view and controller can change the view also. In MVP Controller does not exist, View is more loosely coupled to the model. The presenter is responsible for binding the model to the view.
    In MVC View can interact with model directly. In MVP View can't interact with model directly. View must use presenter to interact with Model.
    MVC Limited Support Unit Testing, MVP is Highly Support Unit Testing.
    MVC It is design pattern used to separate the view from model. MVP is Advance form of MVC.

    >> What the mean of different symbols like ^ $ in Regular Expression?
    ^a Search all string which start with "a".
    a$ Search all string which end with "a".
    [a-z0-9]{2,5} there should be 2-5 string which can be a-z and 0-9 characters.
    [a-z]{2,5} there should be 2-5 string which are a-z characters.
    [0-9]{2,5} there should be 2-5 string which are 0-9 characters.

    >> What is Regular Expression to validate Email?
    ^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$

    >> How do I remove all non alphanumeric characters from a string?
    [^a-zA-Z0-9\s]

    >> Simple regular expression for a decimal with a precision of 2
    \d+(\.\d{1,2})?

    >> Explain each meta characters in regular expression.
    [ ] - Match any character within [phc]. e.g. Means find “p” OR “h” OR “c”
    -   - Range. e.g. a-z means a to z(a,b,c, ... z), 0-9 means 0 to 9.
    ^   - Caret It means start with a character. e.g. ^ab (start with “a”). Inside the bracket if have opposite meaning. e.g. [^a](must not start with “a”).
    $   - End with character. e.g. Abc$ means end with “c”
    .   - The . (period) means any character(s) in this position. e.g. ph. will find php, php-tutorial but not aphp because it has no following character.
    ?   - Matches the preceding character 0 or 1 times only. e.g. colou?r will find both color (0 times) and colour (1 time).
    *   - Matches the preceding character 0 or more times. e.g. tre* will find tree (2 times) and tread (1 time) and trough (0 times).
    +   - Matches the previous character 1 or more times. e.g. tre+ will find tree (2 times) and tread (1 time) but NOT trough (0 times).
    {n} - Preceding character, or character range, n times exactly. e.g. find a local phone number we could use [0-9]{3}-[0-9]{4} will find 723-4567 OR 132-3234 OR 214-3433.
    ()  - To group a character. e.g. (php), will find the “php” only.
    |   - Vertical bar used for OR e.g. (a|c) find either “a” OR “c”
    \d  - any character in the range 0 – 9
    \D  - Any character not in between 0-9
    \s  - Whitespace or tab    
    \S  - Not whitespace or tab
    \w  - Alphanumeric characters (a-z, 0-9, A-Z)
    \W  - Not alphanumeric character (a-z, 0-9, A-Z)
    \$A - Find $A anywhere on the line
    ^\^ - '^' At the begining of a line.
    \$$ - "$" At the end of line
    [0-9]\] - any number followed by a ]
    ^\*  - Any line starting with an asterisk.
    ^A\* -  Any line starting with an "A*"
    ^A{4}B - Any line starting with "AAAAB"

    -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=




    Comments

    Post a Comment

    Popular posts from this blog

    Learn phpfox

    PHPFox  is a social network script, it is an internet application and when you install it, it is a website. The  phpfox  script comes in 3 packages, each with a different set of modules. it has two products: 1. Nebula (upto phpfox 3.8) 2. Neutron (Newer) You can check the demo on :  http://www.phpfox.com =================================================== To clear cache in phpfox follow the following steps, admincp >> Tools >> Maintenance >> Cache Manager >> Click on Clear All button =================================================== To work facebook app on local Following settings need to done in facebook app   1) go => setting => Advance 2) see "OAuth Settings" area and set "Valid OAuth redirect URIs" =  http:// projectdomain /index.php?do=/user/login/, http:// projectdomain .com/index.php?do=/user/register/, http:// projectdomain .com, http:// projectdomain .com/index.php 3) en...

    How to Make Your Own PHP Captcha Generator

    In this article we will create file based simple yet successful captcha generator. 3 Major Anti-spamming techniques used? Mathematical Operation like Random number + Random Number = -> The user must specify the answer Random word -> User must type the word Random question -> Obvious one which the user should answer correctly [ex: Are you human?] How Captcha works? The captcha generator generates an IMAGE with the question and then put up a session variable storing the value. User input though an input box. Using php POST, we compare the session variable data with the user input and tell whether its a bot or human. Its coding time The Code First let's write the php script which generates the captcha image. We use the simple header-content change technique, from which we can easily bring up an image from a given text. captcha.php PHP Code: array("Num" => "Num"), 1 => array("Are y...