Categories
AJAX Angular CSS CSS3 HTML HTML5 JavaScript jQuery NodeJS UI

UI Architect Interview Questions and Answers

what is tail call optimization ?
TCO (Tail Call Optimization) is the process by which a smart compiler can make a call to a function and take no additional stack space.

Recursive function approach has a problem. It builds up a call stack of size O(n), which makes our total memory cost O(n). This makes it vulnerable to a stack overflow error, where the call stack gets too big and runs out of space. Tail Cost Optimization (TCO) Scheme. Where it can optimize recursive functions to avoid building up a tall call stack and hence saves the memory cost.

what is Map, Set, WeakMap and WeakSet ?
Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

A Set is a collection of values, where each value may occur only once means it will contain unique set of keys. 

WeakSet is a special kind of Set that does not prevent JavaScript from removing its items from memory. WeakMap is the same thing for Map.
WeakMap does not support iteration and methods keys(), values(), entries(), so there’s no way to get all keys or values from it.

Map – is a collection of keyed values.

The differences from a regular Object:

Any keys, objects can be keys.
Iterates in the insertion order.
Additional convenient methods, the size property.
Set – is a collection of unique values.

Unlike an array, does not allow to reorder elements.
Keeps the insertion order.
Collections that allow garbage-collection:

WeakMap – a variant of Map that allows only objects as keys and removes them once they become inaccessible by other means.

It does not support operations on the structure as a whole: no size, no clear(), no iterations.
WeakSet – is a variant of Set that only stores objects and removes them once they become inaccessible by other means.

Also does not support size/clear() and iterations.
WeakMap and WeakSet are used as “secondary” data structures in addition to the “main” object storage. Once the object is removed from the main storage, if it is only found in the WeakMap/WeakSet, it will be cleaned up automatically.

how to do peer to peer communication in ANgular ?

what is directive & components in angular ?

if loop functions are removed from script, how can you achieve same functionality ?

how to drop both data and collection in mongodb ?

what is generic types in Typescript ? advantages ?

how to define custom types in Typescript ?

how to capture the process specific exceptions in NodeJS ?

how do you print name of file currently executing in NodeJS ?

how to use custom pipes in Angular ? can you pass additional parameters in custom pipes ?

what is the max data can be stored in a mongodb document ?

how to acheieve variable length documents in mongodb ?

how do you set autoincrement field in mongodb ?

what is the difference between throttling & debouncing ?
Throttling enforces a maximum number of times a function can be called over time. As in “execute this function at most once every 100 milliseconds.”
Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in “execute this function only if 100 milliseconds have passed without it being called.”

what is event bubbling ? how to stop ?
what is digest cycle in angularJS ?
how to stop propgation ?
what is interpolation ? how does it work ?
what is shadow dom ?
what is webworker ?
how to cache the page/data in HTML 5 ?
how to give offline view expereince in HTML5 ?
what is lazyloadng? how it works ?
what are pure / impure pipes ?
what is redux ? how does it work ?
unit testing code coverage how to check ?
what tool used for unit test ?
streaming , how does it work ?
any custom video/audio player developed?
how does cache works in HTML5 ?
what is method chaining ?
difference between canvas vs SVG ?
what is XSS and how to avoid it ?

difference between Responsive and Adaptive design ?
diff b/w flexbar & grid designs ?
what is cors ? how to allow ?
symmetric & asymetric keys ?
scope usage in OAuth token ?
explain component lifecycle
how to use service in Angular ?
what is event emitters ?
latest ECMA version ?
INPUT & OUTPUT variables usage in Angular
explain Digest Lifecycle in Angular ?
difference between Angular 1.x & Angular 2.x
what is SASS & SCSS ?
what is ViewChild ? OR ViewCildren ?

Explain the following :

Directives,
decorators,
Services,
Modules,
Data Binding,
Components,
Filters,
DOM ,
Events ,
Routing,
Dependency injection.

Categories
Agile AJAX Angular CSS CSS3 HTML HTML5 JavaScript jQuery NodeJS UI

Javascript / UI / Angular Architect Questions and Answers

1.Difference between var let and const. ?

a. Var is hoisted in JS, let and const are not hoisted.

b. Let, const are block level, var is function level The candidate has to tell at least one of these apart from any other difference he tells.

2. What is a closure and how does it work

a. A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain.

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain.

3. What is a JavaScript class

a. ES 6 standard introduced classes in JS, which internally use the prototypal approach to implement Class .

4. How does JS implement inheritance

a. JS uses prototypal inheritance in which objects inherit properties from other objects (or) JS uses prototypes to implement inheritance

5. What is the difference between == and === in JS

a. == checks only for the value, where === checks for both value and data type

6. What is the use of hasOwnProperty method in JS

a. This method returns true, only when the passed property is present directly on the object.

7. Explain call, apply and bind

a. Call and apply are used to invoke a method, by setting the context of ‘this’ keyword. Call takes comma separated individual parameters, and apply takes array of parameters as arguments

b. Bind method does the same operation as call and apply, but returns a new function definition instead of invoking the method

8. What is ‘arguments’ keyword in JS

a. Arguments is a special property in every function, that holds all the parameters passed to that function. Its an array-like object.

9. What is arrow function

a. Arrow function is introduced in ES 6 standard of JS, and does implicit binding of this property.

10. What are benefits of TypeScript

a. * TS provides type safety for the variables

Skills checked:

JS core – Intermediate / Advanced

  1. What is a closure and how it works in JavaScript
  2. What is a ‘hosting’ , How this works in JavaScript ?
  3. call, apply and bind with example
  4. Event bubbling and Event capturing
  5. event delegation
  6. prototypical inheritance / prototypical chain
  7. strict mode and usual mode
  8. What is EventLoop?

ECMA

  1. Difference between var, let and const?
  2. What is a promise and how it works?
  3. What is a arrow function and its difference from function syntax?
  4. Generator and how it works
  5. JS modules, export and export default
  6. async/await

Angular – Intermediate / Advanced

  1. Virtual DOM concept.
  2. Subscribe, Observables and Promises.
  3. Different ways of data bindings.
  4. Sequence of Angular Lifecycle Hooks
  5. Routing
  6. Reactive Forms.

React JS and Redux – Novice / Intermediate

  1. Virtual DOM concept.
  2. Explain lifecycle of React component.
  3. Difference between state and props.
  4. Redux
  5. Role of reducer

HTML – Novice / Intermediate

  1. What is a Doctype?
  2. quirks mode and standart mode
  3. new features in html5
  4. Html storage Localstorage and sessionstorage

CSS – Novice

  1. Difference between adaptive and responsive design?
  2. What is a repaint and reflow?
  3. Media query.
  4. Layout Methodology.
  5. How browser search selector?

Networking – Intermediate

  1. What is REST?
  2. REST principles.
  3. Difference between POST and PUT requests

Design Patterns – Advanced

  1. Factory Patterns
  2. Singleton Patterns

Unit testing

  1. TDD/BDD
  2. jasmine/karma

Processes

  1. GIT
  2. Code review process and tools
  3. CI/CD
  4. SOLID
  5. SCRUM
  6. Webpack
  7. IDE

Categories
AJAX Angular CSS HTML HTML5 JavaScript jQuery NodeJS UI Uncategorized VueJS XML

UI Developer – Angular JS INTERVIEW Question and Answer | UI Lead Angular

Migration from any other to MEAN/Angular PROS and CONS ?
checklist for new RFP ? what are all things will be considered for RFP response ?
checklist for development ? deployment ?
coding standard guidelines what is followed ? any libraries integrated ?
For live release of an existing site, how to manage the deployment of new functionality ? without affecting the existing site.
Tools used for code review in Agile ?

If ABC are angular components and  A is parent and B is child and  c is child of child.   how do you delegate event directly from C to A. ?

What is dependency injector ?

What is RxJs ?

explain http response of angular 4.3.2 ?
explain observable response in Angular ?

Difference between http / httpclient in angular ?

what is interceptor ?

what is service injector ?  how to pass authentication specific credentials using injector ?

what is message queue  ?
explain any project with nosql experience  ?

Categories
AJAX Angular HTML HTML5 JavaScript jQuery NodeJS UI VueJS

Angular Interview Questions and Answers | UI Architect Advanced Level Questions

Angular Interview Questions and Answers | UI Architect Advanced Level Questions

How to write Custom Filter in Angular ?

Angular exposes a simple API for creating a filter. similiar to controller declaration with syntax  app.controller(‘myCtrl', function(){});, you can create a new filter by appending .filter(‘filterName', function(){}) to your Angular application. A filter is very similar to a factory or service but has a global scope once its created.You can invoke a filter on both the data binding in your html or directly inside of your controller or directive by using the $filter service.

Function to find the longest word in a sentence ?
First take string sentence and convert this into a array using split()  with separator as space (‘ ‘).

const stringArray = str.split(" ");

And than pass this array into custom sort function to sort based on the word length.

function findLongestWord(str) {
  const stringArray = str.split(" ");
  const orderedArray = stringArray.sort((a, b) => {
    return a.length < b.length;
  });
  return orderedArray;
}

Now just return the  first word (0-index of the array) of the array which contains longest word of the sentence.

Difference between service & factory in Angular ?

The difference between factory and service is just like the difference between a function and an object

Factory Provider

  • Gives us the function’s return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario)
  • Singleton and will only be created once
  • Reusable components
  • Factory are a great way for communicating between controllers like sharing data.
  • Can use other dependencies
  • Usually used when the service instance requires complex creation logic
  • Cannot be injected in .config() function.
  • Used for non configurable services
  • If you’re using an object, you could use the factory provider.
  • Syntax: module.factory('factoryName', function);

Service Provider

  • Gives us the instance of a function (object)- You just instantiated with the ‘new’ keyword and you’ll add properties to ‘this’ and the service will return ‘this’.When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. (Hypothetical Scenario)
  • Singleton and will only be created once
  • Reusable components
  • Services are used for communication between controllers to share data
  • You can add properties and functions to a service object by using the this keyword
  • Dependencies are injected as constructor arguments
  • Used for simple creation logic
  • Cannot be injected in .config() function.
  • If you’re using a class you could use the service provider
  • Syntax: module.service(‘serviceName’, function);

AngularJS .service


module.service('MyService', function() {

    this.method1 = function() {
            //..method1 logic
        }

    this.method2 = function() {
            //..method2 logic
        }
});

AngularJS .factory


module.factory('MyFactory', function() {

    var factory = {}; 

    factory.method1 = function() {
            //..method1 logic
        }

    factory.method2 = function() {
            //..method2 logic
        }

    return factory;
});

Explain CSS position attribute ?

The position property specifies the type of positioning method used for an element (static, relative, absolute, fixed, or sticky).

static Default value. Elements render in order, as they appear in the document flow
absolute The element is positioned relative to its first positioned (not static) ancestor element
fixed The element is positioned relative to the browser window
relative The element is positioned relative to its normal position
sticky The element is positioned based on the user’s scroll position
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Explain Isolate Scope in Angular ?
Scope in AngularJS inherits from Parent Scope by default. Isolated scope does not inherit from the parent scope by default. It can access its parent scope through the $parent property.  So, Directive has three options for isolating its scope from parent scope. The following are the three options:

  1. scope: false  It is default in Directive. It lets to reuse the scope from the place where the component is being used.
  2. scope: true – It creates a child scope. This child scope prototypically inherits from the scope where the component is being used.
  3. scope: {…} – It creates Isolates scope. It does not prototypically inherit from the scope where the component is being used.

Isolated scope completely decouples component or template from the rest of the application or a place where it is being used.

There are three types of interface to specify between the element’s attributes and the isolated scope:
  1. interpolate (@)
  2. data bind (=)
  3. expression (&)
Attributes or Interpolate (@)
An Isolated scope property can be bind with DOM attributes. Interpolate or attribute sets up a one-way data binding from the Parent scope to the Isolated Scope of Directive.
Binding (=)
Binding works almost exactly like the attribute except that it provides two-way mode binding.
Expression (&)
Expression is used to call a function on the Parent scope from the Isolated Scope.

Explain angular Prototype ? 

 

Difference between async and defer tags in Javascript ?
Defer and Async tags are available only for external scripts (with src=”” tag). If you will try to use them for internal scripts like <script>…</script> tags, defer and async will be ignored.
Adding an async tag to the JavaScript code , so that creation of the DOM model happens in parallel, and won’t be interrupted while the JavaScript is loading and executed.
Adding a defer tag with JavaScript code, it will not stop loading the DOM and CSSOM models. All scripts with a defer tag will be loaded and run immediately after the DOM and CSSOM models are completed. Any scripts will be loaded in the order you code.

What is Event delegation in JS ?
JavaScript event delegation is a simple technique by which you add a single event handler to a parent element in order to avoid having to add event handlers to multiple child elements.

What is Closure in JS ?
A closure is basically when an inner function has access to variables outside of its scope. Closures can be used for things like implementing privacy and creating function factories.

What is Debouncing & Throttling in JS ?
Debouncing is one way to solve the issue of same function calling multiple times on event action, by limiting the time that needs to pass by until a function is called again.

Throttling is another technique that’s is similar to debouncing, except that instead of waiting for some time to pass by before calling a function, throttling just spreads the function calls across a longer time interval.
So if an event occurs 10 times within 100 milliseconds, throttling could spread out each of the function calls to be executed once every 2 seconds instead of all firing within 100 milliseconds.

Difference between  TDD vs BDD ?
In TDD (Test Driven Development), the test is written to check the implementation of functionality, but as the code evolves, tests can give false results. BDD (Behavior Driven Development) is also a test-first approach, but differs by testing the actual behavior of the system from the end users perspective.

 

Categories
AJAX Angular CSS CSS3 HTML HTML5 JavaScript jQuery NodeJS UI Uncategorized VueJS

SAP – UI Architect – Angular Interview Questions and Answers

List and explain XSS attack types?

Cross-site scripting (XSS) is a code injection attack that allows an attacker to execute malicious JavaScript in another user’s browser.

XSS attacks are of three types:

  • Persistent XSS, where the malicious string originates from the website’s database.
  • Reflected XSS, where the malicious string originates from the victim’s request.
  • DOM-based XSS, where the vulnerability is in the client-side code rather than the server-side code.

Methods of preventing XSS

  • Encoding, which escapes the user input so that the browser interprets it only as data, not as code.
  • Validation, which filters the user input so that the browser interprets it as code without malicious commands.

What is CORS , how to manage? How to secure the requests?

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.

two response headers are most important for security:  

  • Access-Control-Allow-Origin specifies which domains can access a site’s resources. For example, if ABC Corp. has domains ABC.com and XYZ.com, then its developers can use this header to securely grant XYZ.com access to ABC.com’s resources. 
  • Access-Control-Allow-Methods specifies which HTTP request methods (GET, PUT, DELETE, etc.) can be used to access resources. This header lets developers further enhance security by specifying what methods are valid when XYZ accesses ABC’s resources. 

As CORS can lead to multiple security vulnerabilities , so instead of allowing CORS use a trusted server as a proxy / reverse proxy and allow all requests/resources to be served  from that dedicated server.

What is Virtual polymorphism ?

Polymorphism is the ability for objects of different classes related by inheritance to respond differently to the same member function call.

virtual function allows a programmer to call a function and let the program determine dynamically which version of the function to use.
To enable this type of behavior, the function will be declared in the base class as a virtual function and then be redefined in each of the derived classes.
To declare a virtual function, precede the function’s prototype with the keyword virtual in the base class.
Combination of both Virtual Function with polymorphism concept is called Virtual Polymorphism.

Write a Sql query for products table to get total price of products sold in a quarter ?

 SELECT
  productname, 
  SUM(price) as total_count
  FROM products
  WHERE `date` >= startdate AND `date` <= enddate
  GROUP BY productname
  ;

Write a Sql query for products table to get total price of products sold in a quarter ?

To calculate any factorial in real-time, you can speed it with a cache, saving the numbers you’ve calculated before.

factorial = (function() {
    var cache = {},
        fn = function(n) {
            if (n === 0) {
                return 1;
            } else if (cache[n]) {
                return cache[n];
            }
            return cache[n] = n * fn(n -1);
        };
    return fn;
})();

Types of requests which can be handled through browser?

HTTP, HTTPS, FILE, and FTP protocols are supported by most of the commonly used browsers.

What is promise? Advantages of it ?

A Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

Advantages of promises are

  • Callbacks will never be called before the completion of the current run of the JavaScript event loop.
  • Callbacks added with then() even after the success or failure of the asynchronous operation, will be called, as above.
  • Multiple callbacks may be added by calling then() several times. Each callback is executed one after another, in the order in which they were inserted.
  • One of the great things about using promises is chaining.

How to improve the Performance of webpage?

  • Reduce External HTTP Requests
  • Minify CSS, JS and HTML
  • Compress Components with Gzip
  • Optimize Your Images
  • Add CSS at top/header section
  • Add JS at bottom section
  • Reduce DNS Lookups
  • Use CDN and Cache
  • Make Fewer HTTP Requests
  • Avoid empty src or href
  • Add Expires Headers
  • Avoid CSS Expressions
  • Avoid URL Redirects
  • Remove Duplicate JavaScript and CSS
  • CleanUP the unecessary code
  • Configure Entity Tags (ETags)
  • Reduce the Number of DOM Elements
  • Avoid HTTP 404 (Not Found) Error
  • Do Not Scale Images in HTML
  • Make favicon Small and Cacheable

IF Request/Response taking too much time than How to keep alive the request ?

A Request/Gateway Timeout response code indicates that the server did not receive a complete request from the client within a specific period of time tracked by the server.
You can set custom timeout for your http request in the second parameter of http.get() method:
$http.get(‘request-path’, {timeout: 300000});
This will set timeout to 300 seconds = 5 minutes. Increasing it to something much larger should help.
OR
req.setTimeout(0) for no timeout for all requests
Another solution is doing a long polling or short polling to keep alive the request.

DB 2 queries same record update? How to manage? How to intimate the second request to update itself?

Use SQL transaction statements like BEGIN and COMMIT to avoid concurrent updates to same record.
OR
You may have additional field which indicates that column is being edited. When first user starts work, the field would be updated. The second user would query object with ‘on hold’ status and your code would handle this.

Lot of requests , how to manage?

  • Use CDN for optimized content delivery
  • Use Cache Layers like memcache , redis etc..
  • Use Load Balancing techniques for Application Servers / Cache Layers
  • Use Master / Salve configuration for DB Servers

Same application, for 2 different companies but for all users, request to come, how to manage?

Use Proxy / Reverse proxy configuration along with a flag specific to company to manage the requests to handle internally from different servers.

Bind, apply and call difference in angular ?

The bind() method creates a new function that, when called, has its “this” keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
fun.bind(thisarg[, arg1[,arg2[,….]]])

Function.call allows us to set the this value of a function manually. Instead of simply calling a function like fn(), we use fn.call(param), passing in the object we want this to equal as the parameter.
call also allows us to pass in parameters to the function being called. Anything given after the object to be bound to thiswill be passed along to the function.

Function.apply works the same exact way as call, except instead of passing in arguments one by one, we pass in an array of arguments that gets spread into the function.

In call method parameter will be passed separately. whereas in apply you can pass parameters as Array arguments.

Globalization or internationalization , how to do in angular?

Internationalization (i18n) is the process of developing products in such a way that they can be localized for languages and cultures easily. Localization (l10n), is the process of adapting applications and text to enable their usability in a particular cultural or linguistic market.
internationalizing an application means abstracting all of the strings and other locale-specific bits (such as date or currency formats) out of the application. Localizing an application means providing translations and localized formats for the abstracted bits.
AngularJS supports i18n/l10n for date, number and currency filters.
Localizable pluralization is supported via the ngPluralize directive.
All localizable AngularJS components depend on locale-specific rule sets managed by the $locale service.

How to avoid same button multiple clicks  ?

There are multiple ways to avoid multiple clicks of a same button

  • Once the click event is fired , disable the button till event response is processed
  • Unbind the click event on first click event
  • Provide a time interval for between the same object click event
Categories
AJAX JavaScript

Chart JS canvas dynamic draw chart and clear using AJAX based JSON data

Chart.js  :  How to Clear canvas after drawing a chart based on the dynamic data received from AJAX based JSON response data ?

Normally  if you try to draw a new dynamic chart after an AJAX request based on the JSON data received than the the graph starts jumping around and gets fuzzy between the grid lines. This issue happens every time when the JSON data has changing datasets based on the AJAX cal request. 

To sort out this issue , you need to destroy the chart before redrawing with new dataset. 

create a global variable and use that variable while creating chart :

myChart:

and use this variable to assign chart instance, before assigning the chart instance make sure to check if any previous chart instance is available with the global variable, if exist than clear and destroy the chart distance : 
createChart: function() {
var ctx = document.getElementById(myChart); // check if any existing chart instance data is available and destroy
if(this.myChart instanceof Chart){
this.myChart.clear();
this.myChart.destroy();
} //draw new chart
this.myChart = new Chart(ctx, {
type: this.chartData.type,
data: this.chartData.data
});
}
I have taken the vue.js implementation with chart.js as the example in above scenario. 
Categories
AJAX CSS LAMP MySQL PHP XML

MNC php interview questions and answers

1) what is session_set_save_handler in PHP? session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.

2) what is garbage collection? default time ? refresh time? Garbage Collection is an automated part of PHP , If the Garbage Collection process runs, it then analyzes any files in the /tmp for any session files that have not been accessed in a certain amount of time and physically deletes them. arbage Collection process only runs in the default session save directory, which is /tmp. If you opt to save your sessions in a different directory, the Garbage Collection process will ignore it. the Garbage Collection process does not differentiate between which sessions belong to whom when run. This is especially important note on shared web servers. If the process is run, it deletes ALL files that have not been accessed in the directory.

There are 3 PHP.ini variables, which deal with the garbage collector: PHP ini  value

name                                          default

session.gc_maxlifetime     1440 seconds or 24 minutes

session.gc_probability      1

session.gc_divisor              100

3) PHP how to know user has read the email? Using Disposition-Notification-To: in mailheader we can get read receipt.

Add the possibility to define a read receipt when sending an email.

It’s quite straightforward, just edit email.php, and add this at vars definitions:

var $readReceipt = null;

And then, at ‘createHeader’ function add:

if (!empty($this->readReceipt)) { $this->__header .= ‘Disposition-Notification-To: ‘ . $this->__formatAddress($this->readReceipt) . $this->_newLine; }

4) Runtime library loading ? without default mysql support, how to run mysql with php?

dl — Loads a PHP extension at runtime int dl ( string $library )

Loads the PHP extension given by the parameter library .

Use extension_loaded() to test whether a given extension is already available or not. This works on both built-in extensions and dynamically loaded ones (either through php.ini or dl()).

bool extension_loaded ( string $name ) — Find out whether an extension is loaded

Warning :This function has been removed from some SAPI’s in PHP 5.3.

5) what is XML-RPC ? XML-RPC is a remote procedure call protocol which uses XML to encode its calls and HTTP as a transport mechanism. An XML-RPC message is an HTTP-POST request. The body of the request is in XML. A procedure executes on the server and the value it returns is also formatted in XML.

6) default session time ? default session time in PHP is 1440 seconds or 24 minutes.

7) default session save path ? Default session save path id temporary folder /tmp

8) What is the difference between htmlentities() and htmlspecialchars()?

htmlspecialchars() – Convert some special characters to HTML entities (Only the most widely used) htmlentities() – Convert ALL special characters to HTML entities

9) how to do session using DB?

bool session_set_save_handler ( callback $open , callback $close , callback $read , callback $write , callback $destroy , callback $gc ) using this function we can store sessions in DB.

PHP has a built-in ability to override its default session handling. The function session_set_save_handler() lets the programmer specify which functions should actually be called when it is time to read or write session information. by overriding the default functions using session_set_save_handler handle we can store session in Db like below example

class SessionManager {

var $life_time;

function SessionManager() {

// Read the maxlifetime setting from PHP $this->life_time = get_cfg_var(“session.gc_maxlifetime”);

// Register this object as the session handler session_set_save_handler( array( &$this, “open” ), array( &$this, “close” ), array( &$this, “read” ), array( &$this, “write”), array( &$this, “destroy”), array( &$this, “gc” ) );

}

function open( $save_path, $session_name ) {

global $sess_save_path;

$sess_save_path = $save_path;

// Don’t need to do anything. Just return TRUE.

return true;

}

function close() {

return true;

}

function read( $id ) {

// Set empty result $data = ”;

// Fetch session data from the selected database

$time = time();

$newid = mysql_real_escape_string($id); $sql = “SELECT `session_data` FROM `sessions` WHERE `session_id` = ‘$newid’ AND `expires` > $time”;

$rs = db_query($sql); $a = db_num_rows($rs);

if($a > 0) { $row = db_fetch_assoc($rs); $data = $row[‘session_data’];

}

return $data;

}

function write( $id, $data ) {

// Build query $time = time() + $this->life_time;

$newid = mysql_real_escape_string($id); $newdata = mysql_real_escape_string($data);

$sql = “REPLACE `sessions` (`session_id`,`session_data`,`expires`) VALUES(‘$newid’, ‘$newdata’, $time)”;

$rs = db_query($sql);

return TRUE;

}

function destroy( $id ) {

// Build query $newid = mysql_real_escape_string($id); $sql = “DELETE FROM `sessions` WHERE `session_id` = ‘$newid'”;

db_query($sql);

return TRUE;

}

function gc() {

// Garbage Collection

// Build DELETE query. Delete all records who have passed the expiration time $sql = ‘DELETE FROM `sessions` WHERE `expires` < UNIX_TIMESTAMP();’;

db_query($sql);

// Always return TRUE return true;

}

}

10) how to track user logged out or not? when user is idle ? By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes.

The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server.

11) how to track no of user logged in ? whenever a user logs in track the IP, userID etc..and store it in a DB with a active flag while log out or sesion expire make it inactive. At any time by counting the no: of active records we can get the no: of visitors.

12) in PHP for pdf which library used?

The PDF functions in PHP can create PDF files using the PDFlib library With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. There is also the » Panda module.

FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs.

FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5.

13) for image work which library?

You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.

14) what is oops? encapsulation? abstract class? interface?

Object oriented programming language allows concepts such as modularity, encapsulation, polymorphism and inheritance.

Encapsulation passes the message without revealing the exact functional details of the class. It allows only the relevant information to the user without revealing the functional mechanism through which a particular class had functioned.

Abstract class is a template class that contains such things as variable declarations and methods, but cannot contain code for creating new instances. A class that contains one or more methods that are declared but not implemented and defined as abstract. Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract. Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class.

Interface: Interfaces are one type of class where all the methods are abstract. That means all the methods only declared but not defined. All the methods must be define by its implemented class.

15) what is design pattern? singleton pattern?

A design pattern is a general reusable solution to a commonly occurring problem in software design.

The Singleton design pattern allows many parts of a program to share a single resource without having to work out the details of the sharing themselves.

16) what are magic methods?

Magic methods are the members functions that is available to all the instance of class Magic methods always starts with “__”. Eg. __construct All magic methods needs to be declared as public To use magic method they should be defined within the class or program scope Various Magic Methods used in PHP 5 are: __construct() __destruct() __set() __get() __call() __toString() __sleep() __wakeup() __isset() __unset() __autoload() __clone()

17) what is magic quotes? Magic Quotes is a process that automagically escapes incoming data to the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime, as needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

18) diff b/w php4 & php5 ? In PHP5 1 Implementation of exceptions and exception handling

2. Type hinting which allows you to force the type of a specific argument as object, array or NULL

3. Overloading of methods through the __call function

4. Full constructors and destructors etc through a __constuctor and __destructor function

5. __autoload function for dynamically including certain include files depending on the class you are trying to create.

6 Finality : can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.

7 Interfaces & Abstract Classes

8 Passed by Reference : In PHP4, everything was passed by value, including objects. This has changed in PHP5 — all objects are now passed by reference.

9 An __clone method if you really want to duplicate an object

19) in php4 can you define a class? how to call class in php4? can you create object in php4?

yes you can define class and can call class by creating object of that class. but the diff b/w php4 & php5 is that in php4 everything was passed by value where as in php5 its by reference. And also any value change in reference object changes the actucal value of object also. And one more thing in introduction of __clone object in PHP5 for copying the object.

20) types of error? how to set error settings at run time?

here are three basic types of runtime errors in PHP:

1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although you can change this default behaviour.

2. Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.

3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP?s default behaviour is to display them to the user when they take place.

by using ini_set function.

21) what is cross site scripting? SQL injection?

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Examples of such code include HTML code and client-side scripts.

SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed

22) what is outerjoin? inner join?

OUTER JOIN in SQL allows us to retrieve all values in a certain table regardless of whether these values are present in other tables

An inner join requires each record in the two joined tables to have a matching record. An inner join essentially combines the records from two tables (A and B) based on a given join-predicate.

23) what is URL rewriting?

Using URL rewriting we can convert dynamic URl to static URL Static URLs are known to be better than Dynamic URLs because of a number of reasons 1. Static URLs typically Rank better in Search Engines. 2. Search Engines are known to index the content of dynamic pages a lot slower compared to static pages. 3. Static URLs are always more friendlier looking to the End Users.

along with this we can use URL rewriting in adding variables [cookies] to the URL to handle the sessions.

24) what is the major php security hole? how to avoid?

1. Never include, require, or otherwise open a file with a filename based on user input, without thoroughly checking it first. 2. Be careful with eval() Placing user-inputted values into the eval() function can be extremely dangerous. You essentially give the malicious user the ability to execute any command he or she wishes! 3. Be careful when using register_globals = ON It was originally designed to make programming in PHP easier (and that it did), but misuse of it often led to security holes 4. Never run unescaped queries 5. For protected areas, use sessions or validate the login every time. 6. If you don’t want the file contents to be seen, give the file a .php extension.

25) whether PHP supports Microsoft SQL server ? The SQL Server Driver for PHP v1.0 is designed to enable reliable, scalable integration with SQL Server for PHP applications deployed on the Windows platform. The Driver for PHP is a PHP 5 extension that allows the reading and writing of SQL Server data from within PHP scripts. using MSSQL or ODBC modules we can access Microsoft SQL server.

26) what is MVC? why its been used? Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model.

WHY ITS NEEDED IS 1 Modular separation of function 2 Easier to maintain 3 View-Controller separation means:

A — Tweaking design (HTML) without altering code B — Web design staff can modify UI without understanding code

27) what is framework? how it works? what is advantage?

In general, a framework is a real or conceptual structure intended to serve as a support or guide for the building of something that expands the structure into something useful. Advantages : Consistent Programming Model Direct Support for Security Simplified Development Efforts Easy Application Deployment and Maintenance

28) what is CURL?

CURL means Client URL Library

curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos…), file transfer resume, proxy tunneling and a busload of other useful tricks.

CURL allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

29) HOW we can transfer files from one server to another server without web forms?

using CURL we can transfer files from one server to another server. ex:

Uploading file

<?php

/* http://localhost/upload.php: print_r($_POST); print_r($_FILES); */

$ch = curl_init();

$data = array(‘name’ => ‘Foo’, ‘file’ => ‘@/home/user/test.png’);

curl_setopt($ch, CURLOPT_URL, ‘http://localhost/upload.php’);

curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch); ?>

output:

Array ( [name] => Foo ) Array ( [file] => Array ( [name] => test.png
[type] => image/png [tmp_name] => /tmp/phpcpjNeQ [error] => 0 [size] => 279 )   )
  30) using CSS can we have a scroll to table? 
No table won't support scrolling of its data. but we can do another workaround like placing a table
 in a DIV  layer and setting the DIV css property to overflow:auto will do the trick.
  31) how to increase session time in PHP ? 
In php.ini by setting session.gc_maxlifetime and session.cookie_lifetime values
we can change the session time in PHP.   
 32) what is UI? What are the five primary user-interface components?  
 A user interface is a means for human beings to interact with computer-based "tools" and"messages".
One presumed goal is to make the user's experience productive, efficient, pleasing, and humane.
 The primary components of UIs are  a) metaphors (fundamental concepts communicated
 through words, images, sounds, etc.)
b) mental models (structure of data, functions, tasks, roles, jobs, and people in organizations of work
and/or play)
 c) navigation (the process of moving through the mental models)
d) interaction (all input-output sequences and means for conveying feedback)
 e) and appearance (visual, verbal, acoustic, etc.).
33) How can I set a cron and how can I execute it in Unix, Linux, and windows?

Cron is very simply a Linux module that allows you to run commands at predetermined times or intervals.
In Windows, it’s called Scheduled Tasks. The name Cron is in fact derived from the same word from which we get the word chronology, which means order of time.
The easiest way to use crontab is via the crontab command. # crontab This command ‘edits’ the crontab.
Upon employing this command, you will be able to enter the commands that you wish to run.
My version of Linux uses the text editor vi. You can find information on using vi here.
The syntax of this file is very important – if you get it wrong, your crontab will not function properly.
The syntax of the file should be as follows: minutes hours day_of_month month day_of_week command All the variables, with the exception of the command itself, are numerical constants.
In addition to an asterisk (*), which is a wildcard that allows any value, the ranges permitted for each field are as follows: Minutes: 0-59 Hours: 0-23 Day_of_month: 1-31 Month: 1-12 Weekday: 0-6 We can also include multiple values for each entry, simply by separating each value with a comma.
command can be any shell command and, as we will see momentarily, can also be used to execute a Web document such as a PHP file. So, if we want to run a script every Tuesday morning at 8:15 AM, our mycronjob file will contain the following content on a single line: 15 8 * * 2 /path/to/scriptname This all seems simple enough, right? Not so fast! If you try to run a PHP script in this manner, nothing will happen (barring very special configurations that have PHP compiled as an executable, as opposed to an Apache module).
The reason is that, in order for PHP to be parsed, it needs to be passed through Apache. In other words, the page needs to be called via a browser or other means of retrieving Web content.
For our purposes, I’ll assume that your server configuration includes wget, as is the case with most default configurations. To test your configuration, log in to shell.
If you’re using an RPM-based system (e.g. Redhat or Mandrake), type the following: # wget help If you are greeted with a wget package identification, it is installed in your system.
You could execute the PHP by invoking wget on the URL to the page, like so: # wget http://www.example.com/file.php Now, let’s go back to the mailstock.php file we created in the first part of this article.
We saved it in our document root, so it should be accessible via the Internet. Remember that we wanted it to run at 4PM Eastern time, and send you your precious closing bell report? Since I’m located in the Eastern timezone, we can go ahead and set up our crontab to use 4:00, but if you live elsewhere, you might have to compensate for the time difference when setting this value.
This is what my crontab will look like: 0 4 * * 1,2,3,4,5 wget http://www.example.com/mailstock.php
34)Difference b/w OOPS concept in php4 and PHP5 ?
version 4’s object-oriented functionality was rather hobbled. Although the very basic premises of objectoriented programming (OOP) were offered in version 4, several deficiencies existed, including: • An unorthodox object-referencing methodology • No means for setting the scope (public, private, protected, abstract) of fields and methods • No standard convention for naming constructors • Absence of object destructors • Lack of an object-cloning feature • Lack of support for interfaces
35) Difference b/w MyISAM and InnoDB in MySQL?
Ans:

  • The big difference between MySQL Table Type MyISAM and InnoDB is that InnoDB supports transaction
  • InnoDB supports some newer features: Transactions, row-level locking, foreign keys
  • InnoDB is for high volume, high performance
  • use MyISAM if they need speed and InnoDB for data integrity.
  • InnoDB has been designed for maximum performance when processing large data volumes
  • Even though MyISAM is faster than InnoDB
  • InnoDB supports transaction. You can commit and rollback with InnoDB but with MyISAM once you issue a command it’s done
  • MyISAM does not support foreign keys where as InnoDB supports
  • Fully integrated with MySQL Server, the InnoDB storage engine maintains its own buffer pool for caching data and indexes in main memory. InnoDB stores its tables and indexes in a tablespace, which may consist of several files (or raw disk partitions). This is different from, for example, MyISAM tables where each table is stored using separate files. InnoDB tables can be of any size even on operating systems where file size is limited to 2GB.
  • 36) how to set session tiem out at run time or how to extend the session timeout at runtime?
    Ans:
    Sometimes it is necessary to set the default timeout period for PHP. To find out what the default (file-based-sessions) session timeout value on the server is you can view it through a ini_get command:

    // Get the current Session Timeout Value
    $currentTimeoutInSecs = ini_get(’session.gc_maxlifetime’);

    Change the Session Timeout Value

    // Change the session timeout value to 30 minutes
    ini_set(’session.gc_maxlifetime’, 30*60);

    If you have changed the sessions to be placed inside a Database occasionally implementations will specify the expiry manually. You may need to check through the session management class and see if it is getting the session timeout value from the ini configuration or through a method parameter (with default). It may require a little hunting about.