ALL CSS Interview question and answer

1. What is CSS?
CSS stands for Cascading Style Sheets and is a simple styling language which allows attaching style to HTML elements. Every element type as well as every occurance of a specific element within that type can be declared an unique style, e.g. margins, positioning, color or size.

2. What are Cascading Style Sheets?
A Cascading Style Sheet (CSS) is a list of statements (also known as rules) that can assign various rendering properties to HTML elements. Style rules can be specified for a single element occurrence, multiple elements, an entire document, or even multiple documents at once. It is possible to specify many different rules for an element in different locations using different methods. All these rules are collected and merged (known as a “cascading” of styles) when the document is rendered to form a single style rule for each element.

3. How do I center block-elements with CSS1?
There are ways of centering block level elements:

By setting the properties margin-left and margin-right to auto and width to some explicit value:

BODY {width: 30em; background: cyan;}
P {width: 22em; margin-left: auto; margin-right: auto}

In this case, the left and right margins will each be four ems wide, since they equally split up the eight ems left over from (30em – 22em). Note that it was not necessary to set an explicit width for the BODY element; it was done here to keep the math clean.

4.If background and color should always be set together, why do they exist as separate properties?
There are serveral reasons for this. First, style sheets become more legible — both for humans and machines. The background property is already the most complex property in CSS1 and combining it with color would make it even more complex. Second, color inherits, but background doesn’t and this would be a source of confusion.

5. What is class?
Class is a group of 1) instances of the same element to which an unique style can be attached or 2) instances of different elements to which the same style can be attached.

6. What is grouping?
Grouping is gathering into a comma separated list two or more selectors that share the same style or into a semicolon separated list two or more declarations that are attached to the same selector .

1. The selectors LI, P with class name .first and class .footnote share the same style, e.g.:
LI {font-style: italic}
P.first {font-style: italic}
.footnote {font-style: italic}

To reduce the size of style sheets and also save some typing time they can all be grouped in one list.
LI, P.first, .footnote {font-style: italic}

7. What is external Style Sheet? How to link?
External Style Sheet is a template/document/file containing style information which can be linked with any number of HTML documents. This is a very convenient way of formatting the entire site as well as restyling it by editing just one file. The file is linked with HTML documents via the LINK element inside the HEAD element. Files containing style information must have extension .css, e.g. style.css.

8. Is CSS case sensitive?
Cascading Style Sheets (CSS) is not case sensitve. However, font families, URLs to images, and other direct references with the style sheet may be.

9. What is CSS rule ‘ruleset’?
There are two types of CSS rules: ruleset and at-rule. Ruleset identifies selector or selectors and declares style which is to be attached to that selector or selectors. For example P {text-indent: 10pt} is a CSS rule. CSS rulesets consist of two parts: selector, e.g. P and declaration, e.g. {text-indent: 10pt}.

P {text-indent: 10pt} – CSS rule (ruleset)
{text-indent: 10pt} – CSS declaration
text-indent – CSS property
10pt – CSS value

10. ‘Fixed’ Background?
There is the possibility to use the HTML tag bgproperties=”fixed”, but that is IE proprietary, and dependent upon the ‘background’ attribute (deprecated in HTML4).

With CSS, you can declare the background like:

BODY {
font-family : “Trebuchet MS”, Verdana, Arial, Helvetica, sans-serif;
background-image: url(images/yourimage.gif);
background-repeat: no-repeat; /*no-tiling background*/
background-position: center;
background-attachment: fixed;
background-color: #hexcolor;
color : #hexcolor;
margin: 10px;
}

that shows a background-image in the center of the element, non-scrolling and non-repeating – in IE or NN6. NN 4.xx gets the non-repeat-part right, but stuffs the picture in the upper left corner and scrolls ..

11. What is embedded style? How to link?
Embedded style is the style attached to one specific document. The style information is specified as a content of the STYLE element inside the HEAD element and will apply to the entire document.

Note: The styling rules are written as a HTML comment, that is, between to hide the content in browsers without CSS support which would otherwise be displayed.

12. What is ID selector?
ID selector is an individually identified (named) selector to which a specific style is declared. Using the ID attribute the declared style can then be associated with one and only one HTML element per document as to differentiate it from all other elements. ID selectors are created by a character # followed by the selector’s name. The name can contain characters a-z, A-Z, digits 0-9, period, hyphen, escaped characters, Unicode characters 161-255, as well as any Unicode character as a numeric code, however, they cannot start with a dash or a digit.

#abc123 {color: red; background: black}

This and only this element can be identified as abc123

13. What is contextual selector?
Contextual selector is a selector that addresses specific occurrence of an element. It is a string of individual selectors separated by white space, a search pattern, where only the last element in the pattern is addressed providing it matches the specified context.

TD P CODE {color: red}

The element CODE will be displayed in red but only if it occurs in the context of the element P which must occur in the context of the element TD.

14. How do I have a background image that isn’t tiled?
Specify the background-repeat property as no-repeat. You can also use the background property as a shortcut for specifying multiple background-* properties at once. Here’s an example:

BODY {background: #fff url(watermark.jpg) no-repeat;}

15. What does \ABCD (and \ABCDE) mean?
CSS allows Unicode characters to be entered by number. For example, if a CLASS value in some Russian document contains Cyrillic letters EL PE (Unicode numbers 041B and 041F) and you want to write a style rule for that class, you can put that letter into the style sheet by writing:

.41B41F {font-style: italic;}
This works on all keyboards, so you don’t need a Cyrillic keyboard to write CLASS names in Russian or another language that uses that script.

The digits and letters after the backslash (\) are a hexadecimal number. Hexadecimal numbers are made from ordinary digits and the letters A to F (or a to f). Unicode numbers consist of four such digits.

If the number starts with a 0, you may omit it. The above could also be written as:

.\41B\41F {font-style: italic;}
But be careful if the next letter after the three digits is also a digit or a letter a to f! This is OK: .\41B-\41F, since the dash (-) cannot be mistaken for a hexadecimal digit, but .\41B9\41F is only two letters, not three.

Four digits is the maximum, however, so if you write:
.41B941F {font-style: italic;}

16. What are the advantages/disadvantages of the various style methods?
External Style Sheets
Advantages

* Can control styles for multiple documents at once
* Classes can be created for use on multiple HTML element types in many documents
* Selector and grouping methods can be used to apply styles under complex contexts

Disadvantages

* An extra download is required to import style information for each document
* The rendering of the document may be delayed until the external style sheet is loaded
* Becomes slightly unwieldy for small quantities of style definitions

Embedded Style Sheets
Advantages

* Classes can be created for use on multiple tag types in the document
* Selector and grouping methods can be used to apply styles under complex contexts
* No additional downloads necessary to receive style information

Disadvantages

* This method can not control styles for multiple documents at once

Inline Styles
Advantages

* Useful for small quantities of style definitions
* Can override other style specification methods at the local level so only exceptions need to be listed in conjunction with other style methods

Disadvantages

* Does not distance style information from content (a main goal of SGML/HTML)
* Can not control styles for multiple documents at once
* Author can not create or control classes of elements to control multiple element types within the document
* Selector grouping methods can not be used to create complex element addressing scenarios

17. What is inline style? How to link?
Inline style is the style attached to one specific element. The style is specified directly in the start tag as a value of the STYLE attribute and will apply exclusively to this specific element occurance.

Indented paragraph

18. What is imported Style Sheet? How to link?
Imported Style Sheet is a sheet that can be imported to (combined with) another sheet. This allows creating one main sheet containing declarations that apply to the whole site and partial sheets containing declarations that apply to specific elements (or documents) that may require additional styling. By importing partial sheets to the main sheet a number of sources can be combined into one.
To import a style sheet or style sheets include the @import notation or notations in the STYLE element. The @import notations must come before any other declaration. If more than one sheet is imported they will cascade in order they are imported – the last imported sheet will override the next last; the next last will override the second last, and so on. If the imported style is in conflict with the rules declared in the main sheet then it will be overridden.

.
19. What is alternate Style Sheet? How to link?
Alternate Style Sheet is a sheet defining an alternate style to be used in place of style(s) declared as persistent and/or preferred .
Persistent style is a default style that applies when style sheets are enabled but can disabled in favor of an alternate style, e.g.:

Preferred style is a default style that applies automatically and is declared by setting the TITLE attribute to the LINK element. There can only be one preferred style, e.g.:

Alternate style gives an user the choice of selecting an alternative style – a very convenient way of specifying a media dependent style. Note: Each group of alternate styles must have unique TITLE, e.g.:

20. How can you set a minimum width for IE?
To set a minimum width, the CSS property is ‘min-width’. This can be very useful and works well in good browsers. IE doesn’t understand ‘min-width’. However, it has a proprietary property called ‘expression’ which allows us to feed it javascript via a stylesheet. Below is how to set a (780px) minimum width for IE…


body {
width:expression(documentElement.clientWidth < 780 ? (documentElement.clientWidth == 0 ? (body.clientWidth < 780 ? “780px” : “auto”) : “780px”) : “auto” );
}

As the property is non-standard, it won’t validate with the W3C validator, so if we put it in the head like this (above) – in an IE conditional comment – the validator will ignore it and the page will get a clean bill of health.

21. How do I place text over an image?
To place text or image over an image you use the position property. The below exemple is supported by IE 4.0. All you have to do is adapt the units to your need.

“<div style=”position: relative; width: 200px; height: 100px”>
<div style=”position: absolute; top: 0; left: 0; width: 200px”>
<image>
</div>
<div style=”position: absolute; top: 20%; left: 20%; width: 200px”>
Text that nicely wraps
</div>
</div> ”

22. What is attribute selector?

Attribute selector is a selector defined by 1) the attribute set to element(s), 2) the attribute and value(s), 3) the attribute and value parts:

1a) A[title] {text-decoration: underline}
All A elements containing the TITLE attribute will be underlined

1b) A[class=name] {text-decoration: underline}
The A elements classed as ‘name’ will be underlined

2) A[title="attribute element"] {text-decoration: underline}
The A elements containing the TITLE attribute with a value that is an exact match of the specified value, which in this example is ‘attribute element’, will be underlined

3) A[title~="attribute"] {text-decoration: underline}
The A elements containing the TITLE attribute with a value containing the specified word, which in this example is ‘attribute’, will be underlined

23. What is parent-child selector?
Parent-child selector is a selector representing the direct descendent of a parent element. Parent-child selectors are created by listing two or more tilde (~) separated selectors.

“BODY ~ P {background: red; color: white}

The P element will be declared the specified style only if it directly descends from the BODY element:
<BODY> <P>Red and white paragraph </P> </BODY>

BODY ~ P ~ EM {background: red; color: white}
The EM element will be declared the specified style only if it directly descends from the P element which in its turn directly descends from the BODY element:

<P> <EM>Red and white EM </EM> </P> </BODY>”

24. What are inline, block, parent, children, replaced and floating elements?

Inline
elements which do not have line breaks. Can occur in block elements or other inline elements, cannot contain block elements.
Inline elements in HTML 3.2; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, TT, I, B, U, STRIKE, BIG, SMALL, SUB, SUP, A, IMG, APPLET, FONT, BASEFONT, BR, SCRIPT, MAP, INPUT, SELECT, TEXTAREA.

Inline elements in HTML 4.0; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, ABBR, ACRONYM, TT, I, B, BIG, SMALL, SUB, SUP, A, IMG, OBJECT, BR, SCRIPT, MAP, Q, SPAN, BDO, INPUT, SELECT, TEXTAREA, LABEL, BUTTON, (INS, DEL).

Inline elements in HTML 4.0 Transitional; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, ABBR, ACRONYM, TT, I, B, U, S, STRIKE, BIG, SMALL, SUB, SUP, A, IMG, APPLET, OBJECT, FONT, BASEFONT, BR, SCRIPT, MAP, Q, SPAN, BDO, IFRAME, INPUT, SELECT, TEXTAREA, LABEL, BUTTON, (INS, DEL).

Block
elements which do have line breaks. May occur in other block elements, cannot occur in inline elements, may contain both block and inline elements.

Block elements in HTML 3.2; H1, H2, H3, H4, H5, H6, ADDRESS, P, DL, DT, DD, UL, OL, DIR, MENU, LI, DIV, CENTER, BLOCKQUOTE, PRE, HR, ISINDEX, TABLE, FORM.

Block elements in HTML 4.0; P, H1, H2, H3, H4, H5, H6, UL, OL, PRE, DL, DIV, NOSCRIPT, BLOCKQUOTE, FORM, HR, TABLE, FIELDSET, ADDRESS, (INS, DEL).

Block elements in HTML 4.0 Transitional; P, H1, H2, H3, H4, H5, H6, UL, OL, DIR, MENU, PRE, DL, DIV, CENTER, NOSCRIPT, NOFRAMES, BLOCKQUOTE, FORM, ISINDEX, HR, TABLE, FIELDSET, ADDRESS, (INS, DEL).

Parents and children
elements which either contain (parents) or are in the content of (children) other elements, e.g.

“ e.g. <P>text<STRONG>text</STRONG>text</P>.”  P is a parent of STRONG. STRONG is a child of P. If not specified otherwise, children will inherit parent’s properties.

Replaced
elements which content is replaced. For example content of the IMG element is replaced with an image, content of the INPUT element is replace with a field.
Floating
elements which follow the flow of a parent – inline elements.

25. What are pseudo-classes?
Pseudo-classes are fictional element types that do not exist in HTML. In CSS1 there is only one element type which can be classed this way, namely the A element (anchor). By creating three fictional types of the A element individual style can be attached to each class. These three fictional element types are: A as unvisited link, A as active link and A as visited link. Pseudo-classes are created by a colon followed by pseudo-class’s name. They can also be combined with normal classes, e.g.:

A:link {background: black; color: white}
A:active {background: black; color: red}
A:visited {background: transparent; color: black}

This anchor (or rather these anchors) will be displayed as declared above

A.foot:link {background: black; color: white}
A.foft:active {background; black: color: red}
A.foot:visited {background: transparent; color: black}

This anchor and all other anchors with CLASS foot will be displayed as declared above

26. What is CSS rule ‘at-rule’?
There are two types of CSS rules: ruleset and at-rule. At-rule is a rule that applies to the whole style sheet and not to a specific selector only (like in ruleset). They all begin with the @ symbol followed by a keyword made up of letters a-z, A-Z, digits 0-9, dashes and escaped characters, e.g. @import or @font-face.

27. What is ‘important’ declaration?
Important declaration is a declaration with increased weight. Declaration with increased weight will override declarations with normal weight. If both reader’s and author’s style sheet contain statements with important declarations the author’s declaration will override the reader’s.

BODY {background: white ! important; color: black}

In the example above the background property has increased weight while the color property has normal.

27 To what are partial URLs relative?
Partial URLs are relative to the source of the style sheet. The style sheet source can either be linked or embedded. To which source partial URLs are relative to depends on their occurrence.
If a partial URL occurs in a linked style sheet then it is relative to the linked style sheet. The URL of the linked style sheet is the URL of the directory where the sheet is kept.
If a partial URL occurs in an embedded style sheet then it is relative to the embedded style sheet. The URL of the embedded style sheet is the URL of the HTML document in which the sheet is embedded.
Note that Navigator 4.x treats partial URLs as being relative to the HTML document, regardless of the place where the partial URL occurs. This is a serious bug which forces most authors to use absolute URLs in their CSS.

28 What is the difference between ID and CLASS?
ID identifies and sets style to one and only one occurrence of an element while class can be attached to any number of elements. By singling out one occurrence of an element the unique value can be declared to said element.

CSS
#eva1 {background: red; color: white}
.eva2 {background: red; color: white}

“HTML – ID

<P ID=eva1>Paragraph 1 – ONLY THIS occurrence of the element P (or single occurrence of some other element) can be identified as eva1</P>
<P ID=eva1>Paragraph 2 – This occurrence of the element P CANNOT be identified as eva1</P>

HTML – CLASS
<P class=eva2>Paragraph 1 – This occurrence of the element P can be classified as eva2</P>
<P class=eva2>Paragraph 2 – And so can this, as well as occurrences of any other element, </P> ”

29. What is shorthand property?
Shorthand property is a property made up of individual properties that have a common “addressee”. For example properties: font-weight, font-style, font-variant, font-size, font-family, refer to the font. To reduce the size of style sheets and also save some keystrokes as well as bandwidth they can all be specified as one shorthand property font, e.g.:

H1 {font-weight: bold;
font-style: italic;
font-variant: small-caps;
font-size: 160%;
font-family: serif}

can be all shorthanded to a space separated list:

H1 {font: bold italic small-caps 160% serif}

Note: To make things even simpler the line-height property can be specified together with the font-size property:

H1 {font: bold italic small-caps 160%/170% serif}

30. How does inheritance work?
HTML documents are structured hierarchically. There is an ancestor, the top level element, the HTML element, from which all other elements (children) are descended. As in any other family also children of the HTML family can inherit their parents, e.g. color or size.

By letting the children inherit their parents a default style can be created for top level elements and their children. (Note: not all properties can be inherited). The inheritance starts at the oldest ancestor and is passed on to its children and then their children and the children’s children and so on.

Inherited style can be overridden by declaring specific style to child element. For example if the EM element is not to inherit its parent P then own style must be declared to it. For example:

BODY {font-size: 10pt}
All text will be displayed in a 10 point font

BODY {font-size: 10pt}
H1 {font-size: 14pt} or H1 {font-size: 180%}

All text except for the level 1 headings will be displayed in a 10 point font. H1 will be displayed in a 14 point font (or in a font that is 80% larger than the one set to BODY). If the element H1 contains other elements, e.g. EM then the EM element will also be displayed in a 14 point font (or 180%) it will inherit the property of the parent H1. If the EM element is to be displayed in some other font then own font properties must be declared to it, e.g:

BODY {font-size: 10pt}
H1 {font-size: 14pt} or H1 {font-size: 180%}
EM {font-size: 15pt} or EM {font-size: 110%}

The EM element will be displayed in a 15 point font or will be 10% larger than H1. NOTE: EM is, in this example, inside H1 therefore will inherit H1’s properties and not BODY’s.

The above declaration will display all EM elements in 15 point font or font that is 10% larger than font declared to the parent element. If this specific font is to apply to EM elements but only if they are inside H1 and not every occurrence of EM then EM must take a form of a contextual selector.

H1 EM {font-size: 15pt} or H1 EM {font-size: 110%}

In the example above EM is a contextual selector. It will be displayed in specified font only if it will be found in the context of H1.

Not all properties are inherited. One such property is background. However, since it’s initial value is transparent the background of the parent element will shine through by default unless it is explicitly set.

31. What is Extensible Stylesheet Language (XSL)?
XSL is a proposed styling language for formatting XML (eXtensible Markup Language) documents. The proposal was submitted to the W3C by Microsoft, Inso, and ArborText.

32. How do you make a tooltip that appears on hover?
The most simple way is to use the ‘title’ attribute like this…

“HTML

<span title=”Example of the title attribute in use”>like this</span>

CSS
a.tooltip {
position:relative;
cursor:help;
}
a.tooltip span {
display:none;
position:absolute;
top:1.5em;
left:0;
width:15em;
padding:0 2px;
}
a.tooltip:hover {
display:inline;
}
a.tooltip:hover span {
display:block;
border:1px solid gray;
background-color:white;
}

HTML

<a class=”tooltip” href=”#n”>Karl Marx<span>-info goes here-</span></a>

Without this part… a.tooltip:hover {
display:inline;
}

..it won’t work in IE.

The “#n” in the link is to prevent the page from jumping to the top if the link is clicked. The “href” part is necessary as it won’t work in IE without it.”

var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.” : “http://www.”);
document.write(unescape(“%3Cscript src=’” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));

try {
var pageTracker = _gat._getTracker(“UA-1855756-5″);
pageTracker._trackPageview();
} catch(err) {}

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

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

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.

    Aztecsoft php web developer interview questions and answers

    1) how to increase the web page performance ?

    1) Use lightweight templates
    2) Put Stylesheets at the Top
    3) Put Scripts at the Bottom
    4) Avoid CSS Expressions like As an example, the background color could be set to alternate every hour using CSS expressions.
    background-color: expression( (new Date()).getHours()%2 ? “#B8D4FF” : “#F08A00″ );

    5) Make JavaScript and CSS External
    6) Minify JavaScript and CSS : Minification is the practice of removing unnecessary characters from code to reduce its size thereby improving load times.

    7) Remove Duplicate Scripts
    8) Choose over @import
    9) Don’t Scale Images in HTML
    10) Make favicon.ico Small and Cacheable
    11) use Ajax, JSON, Jquery for fastening results

     

    2) $test=array( 0=>’one’ , 2=> ‘two’ , ‘3 ‘=>’three’ , ‘3a’=>5, ‘myindex’); print_r($test); what will be the output? 

    Array ( [0] => one [2] => two [3 ] => three [3a] => 5 [3] => myindex )

    3) what is output of this mysql function select substring_index(‘abc@123.com’,”@”,-1); 

    Ans:  123.com   explanation is below

    SUBSTRING_INDEX(str,delim,count)

    Returns the substring from string str before count occurrences of the delimiter delim. If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count is negative, everything to the right of the final delimiter (counting from the right) is returned. SUBSTRING_INDEX() performs a case-sensitive match when searching for delim.

    mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2);
            -> 'www.mysql'
    mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2);
            -> 'mysql.com'

    This function is multi-byte safe.

     

    4) An employee table having columns  id {employee id} , name {employee name},  m_id {manager id }  , write a query to select employee and their manager names  ? 

     

    Main table    
    id name m_id
    1 John 2
    2 Greek Tor 1
    3 Alex John 1
    4 Mike tour 1
    5 Brain J 3
    6 Ronald 3
    7 Kin 4
    8 Herod 3
    9 Alen 2
    10 Ronne 1

    Ans:  INNER join SQL command is mostly used to join one table to it self. The biggest advantage of doing this is to get linking information from the same table. We will try to understand this with an example. The best example of INNER join will be employee table where we will keep the employee and its manager as a single record. This way by linking to the table it self we will generate a report displaying it as two linked tables. Each record will have one additional field storing the data of the manager by keeping the employee ID and we will use M_ID ( manager ID ) to link with main employee ID. This way we will link two virtual tables generated from one main table. 

    let us use inner join to create one report on who is the manager of which employee. Check this SQL 
    SELECT t1.id, t1.name as emp_name, t2.name as manager FROM emp as t1 INNER JOIN emp as t2 on t2.id = t1.m_id

    id emp_name manager
    1 John Greek Tor
    2 Greek Tor John
    3 Alex John John
    4 Mike tour John
    5 Brain J Alex John
    6 Ronald Alex John
    7 Kin Mike tour
    8 Herod Alex John
    9 Alen Greek Tor
    10 Ronne John

    for more :  To generate only the manager table used this SQL

    SELECT t1.id,t1.name as emp_name from emp as t1 INNER JOIN emp as t2 on t1.id=t2.m_id 

    Managers Table

     

     
    id emp_name
    2 Greek Tor
    1 John
    1 John
    1 John
    3 Alex John
    3 Alex John
    4 Mike tour
    3 Alex John
    2 Greek Tor
    1 John

     

    To generate only the employee table  used this SQL
    SELECT t1.id,t1.name as emp_name from emp as t1 INNER JOIN emp as t2 on t2.id=t1.m_id 

       
    id emp_name
    1 John
    2 Greek Tor
    3 Alex John
    4 Mike tour
    5 Brain J
    6 Ronald
    7 Kin
    8 Herod
    9 Alen
    10 Ronne

     

    use below dump for your reference 

    CREATE TABLE `emp` (
    `id` int(4) NOT NULL auto_increment,
    `name` varchar(25) NOT NULL default ”,
    `m_id` int(4) NOT NULL default ‘0′,
    UNIQUE KEY `id` (`id`)
    ) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

    – 
    – Dumping data for table `emp`
    – 

    INSERT INTO `emp` VALUES (1, ‘John’, 2);
    INSERT INTO `emp` VALUES (2, ‘Greek Tor’, 1);
    INSERT INTO `emp` VALUES (3, ‘Alex John’, 1);
    INSERT INTO `emp` VALUES (4, ‘Mike tour’, 1);
    INSERT INTO `emp` VALUES (5, ‘Brain J’, 3);
    INSERT INTO `emp` VALUES (6, ‘Ronald’, 3);
    INSERT INTO `emp` VALUES (7, ‘Kin’, 4);
    INSERT INTO `emp` VALUES (8, ‘Herod’, 3);
    INSERT INTO `emp` VALUES (9, ‘Alen’, 2);
    INSERT INTO `emp` VALUES (10, ‘Ronne’, 1);


    5) write code to read the following file content “rag.txt”  and replace postgre SQL to MySQL and output the content ?

    The postgre SQL database has become the world’s most popular open source database because of its consistent fast performance, high reliability and ease of use. postgre SQL used on every continent — Yes, even Antarctica! — by individual Web developers as well as many of the world’s largest and fastest-growing organizations to save time and money powering their high-volume Web sites, business-critical systems and packaged software by postgre SQL.

    Ans:

     $str = file_get_contents(‘rag.txt’);

    $str = str_replace(‘postgre SQL’ ,’MySQL’, $str);

    echo $str;

     

    6) how we can destroy session cookie?

    Ans: we can use session_destroy() or  to destroy particular cookie set it to past time using  setcookie () function like  setcookie (“TestCookie”“”time() - 3600);

    7) True or False 

    a) session_destroy()  : destroys all of the data from session   TRUE

    b) session_unset() : frees all session variable  TRUE

    c) unset($_SESSION) deletes all session data   FALSE    ”Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.”  

    8) $array = array( “hi”, “Hello World” , “what”, “Good Morning”);  write code to output the array contents havng more than one word ?
    Ans: 
        

    <? $array = array( “hi”, “Hello World” , “what”, “Good Morning”); 
    $count = sizeof($array);
    $i =0;
    while ($i < $count )
    {
    echo “<br> ***********<br>”;
    $exp = explode ( ” ” ,$array[$i] );
    if (count($exp) > 1)
    echo $array[$i] .” is having more than  one word in “. $i.” position of array  <br>”;
    $i++;
    }
    ?>
    9) what is the output of the below code 
    $sec_array = array(“red”, “green”, “blue”,”yellow”);
    array_splice( $sec_array , 1, -1);
    print_r($sec_array );   ? 

     

    Ans: Array ( [0] => red [1] => yellow )
    10) how we can get the second value from the last in an array ?
    Ans: 
    example  <? 
    $check = array ( “rag”, “shara”, “sharag”, “man”,”woman”,”child”, “human”);
    echo $check[count($check)-2];
    ?>

    11)  What is the maximum length of a URL?

    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL

    Firefox, Safari , Opera  supports more than 100,000 characters.  but some times server like Apache, IIS may not support these longer URL’s. so better to keep it short URL.


    AJAX Interview Questions and Answers

    What’s AJAX?
    AJAX (Asynchronous JavaScript and XML) is a newly coined term for two powerful browser features that have been around for years, but were overlooked by many web developers until recently when applications such as Gmail, Google Suggest, and Google Maps hit the streets.

    Asynchronous JavaScript and XML, or Ajax (pronounced “Aye-Jacks”), is a web development technique for creating interactive web applications using a combination of XHTML (or HTML) and CSS for marking up and styling information. (XML is commonly used, although any format will work, including preformatted HTML, plain text, JSON and even EBML).
    The Document Object Model manipulated through JavaScript to dynamically display and interact with the information presented
    The XMLHttpRequest object to exchange data asynchronously with the web server. In some Ajax frameworks and in some situations, an IFrame object is used instead of the XMLHttpRequest object to exchange data with the web server.
    Like DHTML, LAMP, or SPA, Ajax is not a technology in itself, but a term that refers to the use of a group of technologies together. In fact, derivative/composite technologies based substantially upon Ajax, such as AFLAX, are already appearing.
    Ajax applications are mostly executed on the user’s computer; they can perform a number of tasks without their performance being limited by the network. This permits the development of interactive applications, in particular reactive and rich graphic user interfaces.
    Ajax applications target a well-documented platform, implemented by all major browsers on most existing platforms. While it is uncertain that this compatibility will resist the advent of the next generations of browsers (in particular, Firefox), at the moment, Ajax applications are effectively cross-platform.
    While the Ajax platform is more restricted than the Java platform, current Ajax applications effectively fill part of the one-time niche of Java applets: extending the browser with portable, lightweight mini-applications.

    Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:
    * standards-based presentation using XHTML and CSS;
    * dynamic display and interaction using the Document Object Model;
    * data interchange and manipulation using XML and XSLT; * asynchronous data retrieval using XMLHttpRequest;
    * and JavaScript binding everything together.

    Who’s Using Ajax ?
    Google is making a huge investment in developing the Ajax approach. All of the major products Google has introduced over the last year ? Orkut, Gmail, the latest beta version of Google Groups, Google Suggest, and Google Maps ? are Ajax applications. (For more on the technical nuts and bolts of these Ajax implementations, check out these excellent analyses of Gmail, Google Suggest, and Google Maps.) Others are following suit: many of the features that people love in Flickr depend on Ajax, and Amazon?s A9.com search engine applies similar techniques.
    These projects demonstrate that Ajax is not only technically sound, but also practical for real-world applications. This isn?t another technology that only works in a laboratory. And Ajax applications can be any size, from the very simple, single-function Google Suggest to the very complex and sophisticated Google Maps.

    Who’s Using Ajax ?
    Google is making a huge investment in developing the Ajax approach. All of the major products Google has introduced over the last year ? Orkut, Gmail, the latest beta version of Google Groups, Google Suggest, and Google Maps ? are Ajax applications. (For more on the technical nuts and bolts of these Ajax implementations, check out these excellent analyses of Gmail, Google Suggest, and Google Maps.) Others are following suit: many of the features that people love in Flickr depend on Ajax, and Amazon?s A9.com search engine applies similar techniques.
    These projects demonstrate that Ajax is not only technically sound, but also practical for real-world applications. This isn?t another technology that only works in a laboratory. And Ajax applications can be any size, from the very simple, single-function Google Suggest to the very complex and sophisticated Google Maps.

    At Adaptive Path, we?ve been doing our own work with Ajax over the last several months, and we?re realizing we?ve only scratched the surface of the rich interaction and responsiveness that Ajax applications can provide. Ajax is an important development for Web applications, and its importance is only going to grow. And because there are so many developers out there who already know how to use these technologies, we expect to see many more organizations following Google?s lead in reaping the competitive advantage Ajax provides.
    Moving Forward

    The biggest challenges in creating Ajax applications are not technical. The core Ajax technologies are mature, stable, and well understood. Instead, the challenges are for the designers of these applications: to forget what we think we know about the limitations of the Web, and begin to imagine a wider, richer range of possibilities

    Should I consider AJAX?
    AJAX definitely has the buzz right now, but it might not be the right thing for you. AJAX is limited to the latest browsers, exposes browser compatibility issues, and requires new skill-sets for many. There is a good blog entry by Alex Bosworth on AJAX Mistakes which is a good read before you jump full force into AJAX.
    On the other hand you can achieve highly interactive rich web applications that are responsive and appear really fast. While it is debatable as to whether an AJAX based application is really faster, the user feels a sense of immediacy because they are given active feedback while data is exchanged in the background. If you are an early adopter and can handle the browser compatibility issues, and are willing to learn some more skills, then AJAX is for you. It may be prudent to start off AJAX-ifying a small portion or component of your application first. We all love technology, but just remember the purpose of AJAX is to enhance your user’s experience and not hinder it.

    Does AJAX work with Java?
    Absolutely. Java is a great fit for AJAX! You can use Java Enterprise Edition servers to generate AJAX client pages and to serve incoming AJAX requests, manage server side state for AJAX clients, and connect AJAX clients to your enterprise resources. The JavaServer Faces component model is a great fit for defining and using AJAX components.

    Won’t my server-side framework provide me with AJAX?
    You may be benefiting from AJAX already. Many existing Java based frameworks already have some level of AJAX interactions and new frameworks and component libraries are being developed to provide better AJAX support. I won’t list all the Java frameworks that use AJAX here, out of fear of missing someone, but you can find a good list at www.ajaxpatterns.org/Java_Ajax_Frameworks.
    If you have not chosen a framework yet it is recommended you consider using JavaServer Faces or a JavaServer Faces based framework. JavaServer Faces components can be created and used to abstract many of the details of generating JavaScript, AJAX interactions, and DHTML processing and thus enable simple AJAX used by JSF application developer and as plug-ins in JSF compatible IDE’s, such as Sun Java Studio Creator.

    Where should I start?
    Assuming the framework you are using does not suffice your use cases and you would like to develop your own AJAX components or functionality I suggest you start with the article Asynchronous JavaScript Technology and XML (AJAX) With Java 2 Platform, Enterprise Edition.
    If you would like to see a very basic example that includes source code you can check out the tech tip Using AJAX with Java Technology. For a more complete list of AJAX resources the Blueprints AJAX home page.
    Next, I would recommend spending some time investigating AJAX libraries and frameworks. If you choose to write your own AJAX clients-side script you are much better off not re-inventing the wheel.
    AJAX in Action by Dave Crane and Eric Pascarello with Darren James is good resource. This book is helpful for the Java developer in that in contains an appendix for learning JavaScript for the Java developer.

    Did Adaptive Path invent Ajax? Did Google? Did Adaptive Path help build Google?s Ajax applications?
    Neither Adaptive Path nor Google invented Ajax. Google?s recent products are simply the highest-profile examples of Ajax applications. Adaptive Path was not involved in the development of Google?s Ajax applications, but we have been doing Ajax work for some of our other clients.

    Is it possible to set session variables from javascript?
    It’s not possible to set any session variables directly from javascript as it is purely a client side technology. You can use AJAX though to asyncronously…

    Cannot parse XML generated by JSP I am generating an XML using JSP, when i run the JSP in IE it shows the XML as per DOM, but when i try to parse it using Javascript , the command xmldoc.documentElement…

    This is working code I am using, it might help you. if (!isIE) xmldoc = req.responseXML; else { //IE does not take the responseXML as…

    What do I need to know to create my own AJAX functionality?
    If you plan not to reuse and existing AJAX component here are some of the things you will need to know.
    Plan to learn Dynamic HTML (DHTML), the technology that is the foundation for AJAX. DHTML enables browser-base real time interaction between a user and a web page. DHTML is the combination of JavaScript, the Document Object Model (DOM) and Cascading Style Sheets (CSS).
    * JavaScript – JavaScript is a loosely typed object based scripting language supported by all major browsers and essential for AJAX interactions. JavaScript in a page is called when an event in a page occurs such as a page load, a mouse click, or a key press in a form element.
    * DOM – An API for accessing and manipulating structured documents. In most cases DOM represent the structure of XML and HTML documents.
    * CSS – Allows you to define the presentation of a page such as fonts, colors, sizes, and positioning. CSS allow for a clear separation of the presentation from the content and may be changed programmatically by JavaScript.
    Understanding the basic request/response nature of HTTP is also important. Many subtle bugs can result if you ignore the differences between the GET and OIst methods when configuring an XMLHttpRequest and HTTP response codes when processing callbacks.
    JavaScript is the client-side glue, in a sense. JavaScript is used to create the XMLHttpRequest Object and trigger the asynchronous call. JavaScript is used to parse the returned content. JavaScript is used to analyze the returned data and process returned messages. JavaScript is used to inject the new content into the HTML using the DOM API and to modify the CSS.

    Do I really need to learn JavaScript?
    Basically yes if you plan to develop new AJAX functionality for your web application.
    On the other hand, JSF components and component libraries can abstract the details of JavaScript, DOM and CSS. These components can generate the necessary artifacts to make AJAX interactions possible. Visual tools such as Java Studio Creator may also use AJAX enabled JSF components to create applications, shielding the tool developer from many of the details of

    AJAX. If you plan to develop your own JSF components or wire the events of components together in a tool it is important that you have a basic understanding of JavaScript. There are client-side JavaScript libraries (discussed below) that you can call from your in page JavaScript that abstract browser differences. Object Hierarchy and Inheritance in JavaScript is a great resource for a Java developer to learn about JavaScript objects.

    Do Ajax applications always deliver a better experience than traditional web applications?
    Not necessarily. Ajax gives interaction designers more flexibility. However, the more power we have, the more caution we must use in exercising it. We must be careful to use Ajax to enhance the user experience of our applications, not degrade it.

    What JavaScript libraries and frameworks are available?
    There are many libraries/frameworks out there (and many more emerging) that will help abstract such things as all the nasty browser differences. Three good libraries are The Dojo Toolkit, Prototype, and DWR.

    * The Dojo Toolkit contains APIs and widgets to support the development of rich web applications. Dojo contains an intelligent packaging system, UI effects, drag and drop APIs, widget APIs, event abstraction, client storage APIs, and AJAX interaction APIs. Dojo solves common usability issues such as support for dealing with the navigation such as the ability to detect the browser back button, the ability to support changes to the URL in the URL bar for bookmarking, and the ability to gracefully degrade when AJAX/JavaScript is not fully support on the client. Dojo is the Swiss Army Knife of JavaScript libraries. It provides the widest range of options in a single library and it does a very good job supporting new and older browsers.
    * Prototype focuses on AJAX interactions including a JavaScript AJAX object that contains a few objects to do basic tasks such as make a request, update a portion of a document, insert content into a document, and update a portion of a document periodically. Prototype JavaScript library contains a set of JavaScript objects for representing AJAX requests and contains utility functions for accessing in page components and DOM manipulations. Script.aculo.us and Rico are built on top of Prototype and provide UI effects, support for drag and drop, and include common JavaScript centric widgets. If you are just looking to support AJAX interactions and a few basic tasks Prototype is great. If you are looking for UI effects Rico and Script.aculo.us are good options.
    * Yahoo UI Library is a utility library and set of widgets using the APIs to support rich clients. The utility library includes support for cross-browser AJAX interactions, animation, DOM scriptging support, drag and drop, and cross browser event support. The Yahoo UI Library is well documnented and contains many examples.
    * DWR (Dynamic Web Remoting) is a client-side and server-side framework that focuses on allowing a developer to do RPC calls from client-side JavaScript to plain old Java objects in a Java Enterprise Edition web container. On the server side DWR uses a Servlet to interact with the Java objects and returns object representations of the Java objects or XML documents. DWR will be easy to get up and running and plays well with other Java technologies. If you are looking for a client-side and server-side framework that integrates well use DWR.
    * Google Web Toolkit (GWT) is client/server framework provided by Google that allows a developer to write an AJAX application in pure Java. The GWT takes care of the details of generating all the client-side code using a Java-to-JavaScript compiler. One of the key benefits of the GWT Software Developer Kit (SDK) is that it allows you to debug your applications in what is known as GWT hosted mode using an embedded browser (IE on Windows and Mozilla/Gecko on Linux) that is tied to the toolkit. In GWT hosted mode you setup through the code and debug it as it is running on both the client and server. The GWT contains a default set of widgets and widget containers. An application is built by coding a set of widgets and containers together much like would be done in a Swing application. The GWT Software Developer Kit (SDK) is limited to Linux and Windows XP/2000 though the web applications it generates are compatible with the latest generation of the mainstream browsers.

    There are many new and emerging libraries for JavaScript and this list only reviews some of the more common libraries. When making a choice choose the library which suites your needs the best. While it might be better to choose one, there is nothing stopping you from using more than one framework. For a more extensive list of client-side frameworks see: Survey of AJAX/JavaScript Libraries.

    What is the difference between proxied and proxyless calls?
    Proxied calls are made through stub objects that mimic your PHP classes on the JavaScript side. E.g., the helloworld class from the Hello World example.
    Proxyless calls are made using utility javascript functions like HTML_AJAX.replace() and HTML_AJAX.append().

    Should I use XML or text, JavaScript, or HTML as a return type?
    It depends. Clearly the ‘X’ in AJAX stands for XML, but several AJAX proponents are quick to point out that nothing in AJAX, per se, precludes using other types of payload, such as, JavaScript, HTML, or plain text.

    * XML – Web Services and AJAX seem made for one another. You can use client-side API’s for downloading and parsing the XML content from RESTful Web Services. (However be mindful with some SOAP based Web Services architectures the payloads can get quite large and complex, and therefore may be inappropriate with AJAX techniqes.)
    * Plain Text – In this case server-generated text may be injected into a document or evaluated by client-side logic.
    * JavaScript – This is an extension to the plain text case with the exception that a server-side component passes a fragment of JavaScript including JavaScript object declarations. Using the JavaScript eval() function you can then create the objects on the client. JavaScript Object Notation (JSON), which is a JavaScript object based data exchange specification, relies on this technique.
    * HTML – Injecting server-generated HTML fragments directly into a document is generally a very effective AJAX technique. However, it can be complicated keeping the server-side component in sync with what is displayed on the client.

    Mashup is a popular term for creating a completely new web application by combining the content from disparate Web Services and other online API’s. A good example of a mashup is housingmaps.com which graphically combines housing want-ads from craiglist.org and maps from maps.google.com.

    Are there Usability Issues with AJAX?
    The nature of updating a page dynamically using data retrieved via AJAX interactions and DHTML may result in drastically changing the appearance and state of a page. A user might choose to use the browser’s back or forward buttons, bookmark a page, copy the URL from the URL bar and share it with a friend via an email or chat client, or print a page at any given time. When designing an AJAX based application you need to consider what the expected behavior would be in the case of navigation, bookmarking, printing, and browser support as described below.

    * Navigation – What would be the expected behavior of the back, forward, refresh, and bookmark browser buttons in your application design. While you could implement history manipulation manually it may be easer to use a JavaScript frameworks such as Dojo that provides API’s history manipulation and navigation control.
    * Bookmarking and URL sharing – Many users want to bookmark or cut and paste the URL from the browser bar. Dojo provides client-side for bookmarking and URL manipulation.
    * Printing – In some cases printing dynamically rendered pages can be problematic.
    Other considerations as a developer when using AJAX are:
    * Browser Support – Not all AJAX/DHTML features are supported on all browsers or all versions of a browser. See quirksmode.org for a list of browser support and possible workarounds.
    * JavaScript disabled – You should also consider what happens if the user disables JavaScript. Additionally, there are several legitimate reasons why JavaScript and CSS support may be unavailable on a user’s web browser.
    * Latency – Keep in mind latency in your design. A running application will be much more responsive than when it is deployed.
    Latency problems: myth or reality?
    * Accessibility – Guaranteeing your site is accessible to people with disabilities is not only a noble goal, it is also requited by law in many markets. Some marvelous enabling technology is available to help people use the Web in spite of disabilities including visual, auditory, physical, speech, cognitive, and neurological disabilities. With a little forethought, and comprehension of some well documented best practices, you can assure that your application is compatible with that enabling technology.
    Degradability is the term used to describe techniques used by web applications to adapt to the wide range of web browser capabilities. Many AJAX libraries have automatic degradability built in. But if you are coding your own custom AJAX functionality, simply taking some care to follow the best practices promoted by standards bodies like the World Wide Web Consortium (W3C), and grass root movements like the Web Standards community and many others, your application can run usefully on browsers that are incapable of AJAX behaviors. Granted, your application may loose some of the “wow factor” on these less capable browsers, but your application will still be usable.
    Remember to not design with AJAX just for the sake of coolness. The reason you built your application is so people will use it. And people will not use your application if your application is not compatible with their web browser.

    Are there any frameworks available to help speedup development with AJAX?
    There are several browser-side frameworks available, each with their own uniqueness…

    Is Adaptive Path selling Ajax components or trademarking the name? Where can I download it?
    Ajax isn?t something you can download. It?s an approach ? a way of thinking about the architecture of web applications using certain technologies. Neither the Ajax name nor the approach are proprietary to Adaptive Path.

    Should I use an HTTP GET or POST for my AJAX calls?
    AJAX requests should use an HTTP GET request when retrieving data where the data will not change for a given request URL. An HTTP POST should be used when state is updated on the server. This is in line with HTTP idempotency recommendations and is highly recommended for a consistent web application architecture.

    How do I debug JavaScript?
    There are not that many tools out there that will support both client-side and server-side debugging. I am certain this will change as AJAX applications proliferate. I currently do my client-side and server-side debugging separately. Below is some information on the client-side debuggers on some of the commonly used browsers.

    * Firefox/Mozilla/Netscape – Have a built in debugger Venkman which can be helpful but there is a Firefox add on known as FireBug which provides all the information and AJAX developer would ever need including the ability to inspect the browser DOM, console access to the JavaScript runtime in the browser, and the ability to see the HTTP requests and responses (including those made by an XMLHttpRequest). I tend to develop my applications initially on Firefox using Firebug then venture out to the other browsers.
    * Safari – Has a debugger which needs to be enabled. See the Safari FAQ for details.
    * Internet Explorer – There is MSDN Documentation on debugging JavaScript. A developer toolbar for Internet Explorer may also be helpful.

    While debuggers help a common technique knowing as “Alert Debugging” may be used. In this case you place “alert()” function calls inline much like you would a System.out.println. While a little primitive it works for most basic cases. Some frameworks such as Dojo provide APIs for tracking debug statements.

    How do I provide internationalized AJAX interactions?
    Just because you are using XML does not mean you can properly send and receive localized content using AJAX requests. To provide internationalized AJAX components you need to do the following:

    * Set the charset of the page to an encoding that is supported by your target languages. I tend to use UTF-8 because it covers the most languages. The following meta declaration in a HTML/JSP page will set the content type:

    * In the page JavaScript make sure to encode any parameters sent to the server. JavaScript provides the escape() function which returns Unicode escape strings in which localized text will appear in hexadecimal format. For more details on JavaScript encoding see Comparing escape(), encodeURI(), and encodeURIComponent().
    * On the server-side component set the character encoding using the HttpServletRequest.setCharacterEncoding() method. Before you access the localized parameter using the HttpServletRequest.getParameter() call. In the case of UTF this would be request.setCharactherEncoding(“UTF-8″);.
    A server-side component returning AJAX responses needs to set the encoding of the response to the same encoding used in the page.
    response.setContentType(“text/xml;charset=;UTF-8″);
    response.getWriter().write(” invalid “);

    For more information on using AJAX with Java Enterprise Edition technologies see AJAX and Internationalization and for developing multi-lingual applications see Developing Multilingual Web Applications Using JavaServer Pages Technology.

    Some of the Google examples you cite don?t use XML at all. Do I have to use XML and/or XSLT in an Ajax application?
    No. XML is the most fully-developed means of getting data in and out of an Ajax client, but there?s no reason you couldn?t accomplish the same effects using a technology like JavaScript Object Notation or any similar means of structuring data for interchange.

    Are Ajax applications easier to develop than traditional web applications?
    Not necessarily. Ajax applications inevitably involve running complex JavaScript code on the client. Making that complex code efficient and bug-free is not a task to be taken lightly, and better development tools and frameworks will be needed to help us meet that challenge.

    When do I use a synchronous versus a asynchronous request?
    Good question. They don’t call it AJAX for nothing! A synchronous request would block in page event processing and I don’t see many use cases where a synchronous request is preferable.

    How do I handle concurrent AJAX requests?
    With JavaScript you can have more than one AJAX request processing at a single time. In order to insure the proper post processing of code it is recommended that you use JavaScript Closures. The example below shows an XMLHttpRequest object abstracted by a JavaScript object called AJAXInteraction. As arguments you pass in the URL to call and the function to call when the processing is done.
    function AJAXInteraction(url, callback) {

    var req = init();
    req.onreadystatechange = processRequest;

    function init() {
    if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
    return new ActiveXObject(“Microsoft.XMLHTTP”);
    }
    }

    function processRequest () {
    if (req.readyState == 4) {
    if (req.status == 200) {
    if (callback) callback(req.responseXML);
    }
    }
    }

    this.doGet = function() {
    req.open(“GET”, url, true);
    req.send(null);
    }

    this.doPost = function(body) {
    req.open(“POST”, url, true);
    req.setRequestHeader(“Content-Type”, “
    application/x-www-form-urlencoded”);
    req.send(body);
    }
    }

    function makeRequest() {
    var ai = new AJAXInteraction(“processme”,
    function() { alert(“Doing Post Process”);});
    ai.doGet();
    }

    The function makeRequest() in the example above creates an AJAXInteraction with a URL to of “processme” and an inline function that will show an alert dialog with the message “Doing Post Process”. When ai.doGet() is called the AJAX interaction is initiated and when server-side component mapped to the URL “processme” returns a document which is passed to the callback function that was specified when the AJAXInteraction was created.
    Using this closures insures that the proper callback function associated with a specific AJAX interaction is called. Caution should still be taken when creating multiple closure objects in that make XmlHttpRequests as to there is a limited number of sockets that are used to make requests at any given time. Because there are limited number of requests that can be made concurrently. Internet Explorer for example only allows for two concurrent AJAX requests at any given time. Other browsers may allow more but it is generally between three and five requests. You may choose to use pool of AJAXInteraction objects.
    One thing to note when making multiple AJAX calls from the client is that the calls are not guaranteed to return in any given order. Having closures within the callback of a closure object can be used to ensure dependencies are processed correctly.
    There is a discussion titled Ajaxian Fire and Forget Pattern that is helpful.

    What do I do on the server to interact with an AJAX client?
    The “Content-Type” header needs to be set to”text/xml”. In servlets this may be done using the HttpServletResponse.setContentType()should be set to “text/xml” when the return type is XML. Many XMLHttpRequest implementations will result in an error if the “Content-Type” header is set The code below shows how to set the “Content-Type”.

    response.setContentType(“text/xml”);
    response.getWriter().write(“invalid”);

    You may also want to set whether or not to set the caches header for cases such as autocomplete where you may want to notify proxy servers/and browsers not to cache the results.

    response.setContentType(“text/xml”);
    response.setHeader(“Cache-Control”, “no-cache”);
    response.getWriter().write(“invalid”);

    Note to the developer: Internet Explorer will automatically use a cached result of any AJAX response from a HTTP GET if this header is not set which can make things difficult for a developer. During development mode you may want set this header. Where do I store state with an AJAX client

    As with other browser based web applications you have a few options which include:
    * On the client in cookies – The size is limited (generally around 4KB X 20 cookies per domain so a total of 80KB) and the content may not be secure unless encrypted which is difficult but not impossible using JavaScript.
    * On the client in the page – This can be done securely but can be problematic and difficult to work with. See my blog entry on Storing State on the Client for more details on this topic.
    * On the client file system – This can be done if the client grants access to the browser to write to the local file system. Depending on your uses cases this may be necessary but caution is advised.
    * On the Server – This is closer to the traditional model where the client view is of the state on the server. Keeping the data in sync can be a bit problematic and thus we have a solution Refreshing Data on this. As more information processing and control moves to the client where state is stored will need to be re-evaluated.

    Whats with the -alpha in the install instructions?
    HTML_AJAX hasn’t had a stable release yet and the pear installer doesn’t install non stable packages by default unless you specify a version.

    How do I submit a form or a part of a form without a page refresh?
    When creating a form make sure that the “form” element “onSubmit” attribute is set to a JavaScript function that returns false.

    You can also submit data by associating a function with a form button in a similar way.

    Note that the form “onSubmit” attribute is still set. If the user hits the enter key in the text field the form will be submitted so you still need to handle that case.
    When updating the page it is recommend you wait to make sure that the AJAX update of the form data was successful before updating the data in the page. Otherwise, the data may not properly update and the user may not know. I like to provide an informative message when doing a partial update and upon a successful AJAX interaction I will then update the page.

    How do I test my AJAX code?
    There is a port of JUnit for client-side JavaScript called JsUnit

    What exactly is the W3C DOM?
    The W3C Document Object Model (DOM) is defined by the W3C as the following: The Document Object Model is a platform- and language-neutral interface…

    When will HTML_AJAX have a stable release?
    Once all the major features are complete and the API has been tested, the roadmap gives an idea of whats left to be done.

    What parts of the HTML_AJAX API are stable?
    We don’t have a list right now, but most of the API is stable as of 0.3.0. There should be no major changes at this point, though there will be lots of new additions.

    What Browsers does HTML_AJAX work with?
    As of 0.3.0, all the examples that ship with HTML_AJAX have been verified to work with
    * Firefox 1.0+
    * Internet Explorer 5.5+ (5.0 should work but it hasn’t been tested)
    Most things work with
    * Safari 2+
    * Opera 8.5+

    Is the server or the client in control?
    It depends. With AJAX the answer is more in between. Control can be more centralized in a server-side component or as a mix of client-side and server-side controllers.

    * Centralized server-side controller – When having a more centralized controller the key is to make sure the data in client-side page is in sync with that of the server. Some applications may keep all the state on the server and push all updates to client DOM via a simple JavaScript controller.
    * Client and server-side controllers – This architecture would use JavaScript to do all presentation related control, event processing, page manipulation, and rendering of model data on the client. The server-side would be responsible for things such as business logic and pushing updated model data to the client. In this case the server would not have intimate knowledge of the presentation short of the initial page that would be sent to the client page request.

    There are some use cases where an entire AJAX application can be written in a single page. Keep in mind if you choose this type of architecture that navigation and bookmarking should be considered.
    Both methods are viable depending on what you are trying to accomplish. I tend to prefer spreading the control across the client and server.

    Is Ajax just another name for XMLHttpRequest?
    No. XMLHttpRequest is only part of the Ajax equation. XMLHttpRequest is the technical component that makes the asynchronous server communication possible; Ajax is our name for the overall approach described in the article, which relies not only on XMLHttpRequest, but on CSS, DOM, and other technologies.

    How do I abort the current XMLHttpRequest?
    Just call the abort() method on the request.

    What is the minimum version of PHP that needs to be running in order to use HTML_AJAX?
    The oldest PHP version i’ve fully tested HTML_AJAX is 4.3.11, but it should run on 4.2.0 without any problems. (Testing reports from PHP versions older then 4.3.11 would be appreciated.)

    Why does HTML_AJAX hang on some server installs?
    If you run into an HTML_AJAX problem only on some servers, chances are your running into a problem with output compression. If the output compression is handled in the PHP config we detect that and do the right thing, but if its done from an apache extension we have no way of knowing its going to compress the body. Some times setting HTML_AJAX::sendContentLength to false fixes the problem, but in other cases you’ll need to disabled the extension for the AJAX pages.
    I’ve also seen problems caused by debugging extensions like XDebug, disabling the extension on the server page usually fixes that. Questions dealing with Using HTML_AJAX, and general JavaScript development

    How do I get the XMLHttpRequest object?
    Depending upon the browser… if (window.ActiveXObject) { // Internet Explorer http_request = new ActiveXObject(“Microsoft.XMLHTTP”); } else if…

    Are there any security issues with AJAX?
    JavaScript is in plain view to the user with by selecting view source of the page. JavaScript can not access the local filesystem without the user’s permission. An AJAX interaction can only be made with the servers-side component from which the page was loaded. A proxy pattern could be used for AJAX interactions with external services.
    You need to be careful not to expose your application model in such as way that your server-side components are at risk if a nefarious user to reverse engineer your application. As with any other web application, consider using HTTPS to secure the connection when confidential information is being exchanged.

    What about applets and plugins ?
    Don’t be too quick to dump your plugin or applet based portions of your application. While AJAX and DHTML can do drag and drop and other advanced user interfaces there still limitations especially when it comes to browser support. Plugins and applets have been around for a while and have been able to make AJAX like requests for years. Applets provide a great set of UI components and APIs that provide developers literally anything.
    Many people disregard applets or plugins because there is a startup time to initialize the plugin and there is no guarantee that the needed version of a plugin of JVM is installed. Plugins and applets may not be as capable of manipulating the page DOM. If you are in a uniform environment or can depend on a specific JVM or plugin version being available (such as in a corporate environment) a plugin or applet solution is great.
    One thing to consider is a mix of AJAX and applets or plugins. Flickr uses a combination of AJAX interactions/DHTML for labeling pictures and user interaction and a plugin for manipulating photos and photo sets to provide a great user experience. If you design your server-side components well they can talk to both types of clients.

    Why did you feel the need to give this a name?
    I needed something shorter than ?Asynchronous JavaScript+CSS+DOM+XMLHttpRequest? to use when discussing this approach with clients.

    Is AJAX code cross browser compatible?
    Not totally. Most browsers offer a native XMLHttpRequest JavaScript object, while another one (Internet Explorer) require you to get it as an ActiveX object….

    Techniques for asynchronous server communication have been around for years. What makes Ajax a ?new? approach?
    What?s new is the prominent use of these techniques in real-world applications to change the fundamental interaction model of the Web. Ajax is taking hold now because these technologies and the industry?s understanding of how to deploy them most effectively have taken time to develop.

    Is Ajax a technology platform or is it an architectural style?
    It?s both. Ajax is a set of technologies being used together in a particular way.

    How do I handle the back and forward buttons?
    While you could go out and create a custom solution that tracks the current state on your application I recommend you leave this to the experts. Dojo addresses the navigation in a browser neutral way as can be seen in the JavaScript example below.
    function updateOnServer(oldId, oldValue,
    itemId, itemValue) {
    var bindArgs = {
    url: “faces/ajax-dlabel-update”,
    method: “post”,
    content: {“component-id”: itemId, “component-value”:
    itemValue},
    mimetype: “text/xml”,
    load: function(type, data) {
    processUpdateResponse(data);
    },
    backButton: function() {
    alert(“old itemid was ” + oldId);
    },
    forwardButton: function(){
    alert(“forward we must go!”);
    }
    };
    dojo.io.bind(bindArgs);
    }

    The example above will update a value on the server using dojo.io.bind() with a function as a property that is responsible for dealing with the browser back button event. As a developer you are capable of restoring the value to the oldValue or taking any other action that you see fit. The underlying details of how the how the browser button event are detected are hidden from the developer by Dojo.
    AJAX: How to Handle Bookmarks and Back Buttons details this problem and provides a JavaScript library Really Simple History framework (RSH) that focuses just on the back and forward issue.

    How does HTML_AJAX compare with the XAJAX project at Sourceforge?
    XAJAX uses XML as a transport for data between the webpage and server, and you don’t write your own javascript data handlers to manipulate the data received from the server. Instead you use a php class and built in javascript methods, a combination that works very similiar to the HTML_AJAX_Action class and haSerializer combo. XAJAX is designed for simplicity and ease of use.
    HTML_AJAX allows for multiple transmission types for your ajax data – such as urlencoding, json, phpserialized, plain text, with others planned, and has a system you can use to write your own serializers to meet your specific needs. HTML_AJAX has a class to help generate javascript (HTML_AJAX_Helper) similiar to ruby on rail’s javascript helper (although it isn’t complete), and an action system similiar to XAJAX’s “action pump” that allows you to avoid writing javascript data handlers if you desire.
    But it also has the ability to write your own data handling routines, automatically register classes and methods using a server “proxy” script, do different types of callbacks including grabbing remote urls, choose between sync and async requests, has iframe xmlhttprequest emulation fallback capabilities for users with old browsers or disabled activeX, and is in active development with more features planned (see the Road Map for details)
    HTML_AJAX has additional features such as client pooling and priority queues for more advanced users, and even a javascript utility class. Although you can use HTML_AJAX the same way you use XAJAX, the additional features make it more robust, extensible and flexible. And it is a pear package, you can use the pear installer to both install and keep it up to date.
    If you’re asking which is “better” – as with most php scripts it’s a matter of taste and need. Do you need a quick, simple ajax solution? Or do you want something that’s flexible, extensible, and looking to incorporate even more great features? It depends on the project, you as a writer, and your future plans.

    What browsers support AJAX?
    Internet Explorer 5.0 and up, Opera 7.6 and up, Netscape 7.1 and up, Firefox 1.0 and up, Safari 1.2 and up, among others.

    How do I send an image using AJAX?
    While it may appear that images are being sent when using AJAX with an application like Google Maps what is really happening is that the URLs of images are being send as the response of an AJAX request and those URLs are being set using DHTML.
    In this example an XML document is returned from an AJAX interaction and the category bar is populated.

    1
    Books
    Fun to read
    books_icon.gif

    2
    Electronics
    Must have gadgets
    electronics.gif

    Notice that the image-url element contains the location of the URL for the image representing a category. The callback method of an AJAX interaction will parse the response XML document and call the addCategory function for each category included in the response XML document. The addCategory function looks up a table row element “categoryTable” in body of the page and adds a row to the element which contains the image.

    function addCategory(id, name, imageSrc) {

    var categoryTable = document.getElementById(“categoryTable”);
    var row = document.createElement(“tr”);
    var catCell = document.createElement(“td”);
    var img = document.createElement(“img”);
    img.src = (“images\\” + imageSrc);
    var link = document.createElement(“a”);
    link.className =”category”;
    link.appendChild(document.createTextNode(name));
    link.setAttribute(“onclick”, “catalog?command=category&catid=” + id);
    catCell.appendChild(img);
    catCell.appendChild(link);
    row.appendChild(catCell);
    categoryTable.appendChild(row);
    }

      Body Here

    Note that the source of the image is set to the image source. The image is loaded by a subsequent HTTP request for the image at the URL “images/books_icon.gif” or “images/electronic_icon.gif” that occurs when the img element is added to the categoryTable.

    Will HTML_AJAX integrate with other Javascript AJAX libraries such as scriptaculous ? How would this integration look like?
    HTML_AJAX doesn’t have specific plans to integrate with other JavaScript libraries. Part of this is because external dependencies make for a more complicated installation process. It might make sense to offer some optional dependencies on a library like scriptaculous automatically using its visual effects for the loading box or something, but there isn’t a lot to gain from making default visuals like that flashier since they are designed to be easily replaceable.

    Most integration would take place in higher level components. Its unclear whether higher level components like that should be part of HTML_AJAX delivered through PEAR or if they should just be supported by HTML_AJAX and made available from http://htmlajax.org or some other site. If your interested in building widgets or components based on HTML_AJAX please let me know.

    HTML_AJAX does however offer the ability to use its library loading mechanism with any JavaScript library. I use scriptaculous in conjunction with HTML_AJAX and I load both libraries through the server.

    To do this you just need to register the library with your server and load add its flag to your include line.

    server->registerJSLibrary(’scriptaculous’,
    array(‘prototype.js’,’scriptaculous.js’,'builder.js’,'effects.js’,'dragdrop.js’,'controls.js’,’slider.js’), ‘/pathto/scriptaculous/’);?>

    When should I use an Java applet instead of AJAX?
    Applets provide a rich experience on the client side and there are many things they can do that an AJAX application cannot do, such as custom data streaming, graphic manipulation, threading, and advanced GUIs. While DHTML with the use of AJAX has been able to push the boundaries on what you can do on the client, there are some things that it just cannot do. The reason AJAX is so popular is that it only requires functionality built into the browser (namely DHTML and AJAX capabilities). The user does not need to download and/or configure plugins. It is easy to incrementally update functionality and know that that functionality will readily available, and there are not any complicated deployment issues. That said, AJAX-based functionality does need to take browser differences into consideration. This is why we recommend using a JavaScript library such as Dojo which abstracts browser differences. So the “bottom line” is: If you are creating advanced UIs where you need more advanced features on the client where you want UI accuracy down to the pixel, to do complex computations on the client, use specialized networking techniques, and where you know that the applet plugin is available for your target audience, applets are the way to go. AJAX/DHTML works well for applications where you know the users are using the latest generation of browsers, where DHTML/AJAX “good enough” for you, and where your developers have JavaScript/DHTML/AJAX skills. Many amazing things can be done with AJAX/DHTML but there are limitations. AJAX and applets can be used together in the same UIs with AJAX providing the basic structure and applets providing more advanced functionality. The Java can communicate to JavaScript using the Live-Connect APIs. The question should not be should framed as do I use AJAX or applets, but rather which technology makes the best sense for what you are doing. AJAX and applets do not have to be mutually exclusive.

    What kinds of applications is Ajax best suited for?
    We don?t know yet. Because this is a relatively new approach, our understanding of where Ajax can best be applied is still in its infancy. Sometimes the traditional web application model is the most appropriate solution to a problem.

    Does this mean Adaptive Path is anti-Flash?
    Not at all. Macromedia is an Adaptive Path client, and we?ve long been supporters of Flash technology. As Ajax matures, we expect that sometimes Ajax will be the better solution to a particular problem, and sometimes Flash will be the better solution. We?re also interested in exploring ways the technologies can be mixed (as in the case of Flickr, which uses both).

    Where can I find examples of AJAX?
    While components of AJAX have been around for some time (for instance, 1999 for XMLHttpRequest), it really didn’t become that popular until Google took…

    What is the XMLHttpRequest object?
    It offers a non-blocking way for JavaScript to communicate back to the web server to update only part of the web page.

    Does Ajax have significant accessibility or browser compatibility limitations? Do Ajax applications break the back button? Is Ajax compatible with REST? Are there security considerations with Ajax development? Can Ajax applications be made to work for users who have JavaScript turned off?
    The answer to all of these questions is ?maybe?. Many developers are already working on ways to address these concerns. We think there?s more work to be done to determine all the limitations of Ajax, and we expect the Ajax development community to uncover more issues like these along the way.

    How do I access data from other domains to create a mashup with Java?
    From your JavaScript clients you can access data in other domains if the return data is provide in JSON format. In essence you can create a JavaScript client that runs operates using data from a different server. This technique is know as JSON with Padding or JSONP. There are questions as to whether this method is secure as you are retrieving data from outside your domain and allowing it to be excuted in the context of your domain. Not all data from third parties is accessible as JSON and in some cases you may want an extra level of protection. With Java you can provide a proxy to third party services using a web component such as a servlet. This proxy can manage the communication with a third party service and provide the data to your clients in a format of your choosing. You can also cache data at your proxy and reduce trips to service. For more on using a Java proxy to create mashups see The XmlHttpProxy Client for Java.

    Does Java have support for Comet style server-side push?
    Current AJAX applications use polling to communicate changes data between the server and client. Some applications, such as chat applications, stock tickers, or score boards require more immediate notifications of updates to the client. Comet is an event based low latency server side push for AJAX applications. Comet communication keeps one of the two connections available to the browser open to continously communicate events from the server to the client. A Java based solution for Comet is being developed for Glassfish on top of the Grizzly HTTP connector. See Enabling Grizzly by Jean-Francois Arcand for more details.

    How do I create a thread to do AJAX polling?
    JavaScript does not have threads. JavaScript functions are called when an event happens in a page such as the page is loaded, a mouse click, or a form element gains focus. You can create a timer using the setTimeout which takes a function name and time in milliseconds as arguments. You can then loop by calling the same function as can be seen in the JavaScript example below.

    function checkForMessage() {
    // start AJAX interaction with processCallback as the callback function
    }

    // callback for the request
    function processCallback() {

    // do post processing
    setTimeout(“checkForMessage()”, 10000);
    }

    Notice that the checkForMessage will continue to loop indefinitely. You may want to vary the increment the interval based on activity in the page or your use cases. You may also choose to have logic that would break out of the loop based on some AJAX response processing condition.

    Is the XMLHttpRequest object part of a W3C standard?
    No. Or not yet. It is part of the DOM Level 3 Load and Save Specification proposal.

    PHP interview questions & ANSWERS

    Q:1 What are the differences between Get and post methods in form submitting.
    give the case where we can use get and we can use post methods?
    A:1
    When to use GET or  POST

    The HTML 2.0 specification says, in section Form
    Submission (and the HTML 4.0 specification repeats this with minor
    stylistic changes):

    –>If the processing of a form is idempotent
    (i.e. it has no lasting observable effect on the state of the
    world), then the form method should be GET. Many database searches
    have no visible side-effects and make ideal applications of query
    forms.

    –>If the service associated with the processing of a form has side
    effects (for example, modification of a database or subscription to
    a service), the method should be POST.
    How the form data is transmitted?

    quotation from the HTML 4.0 specification

    –> If the method is “get” – -, the user agent
    takes the value of action, appends a ? to it, then appends the form
    data set, encoded using the application/x-www-form-urlencoded
    content type. The user agent then traverses the link to this URI. In
    this scenario, form data are restricted to ASCII codes.
    –> If the method is “post” –, the user agent conducts an HTTP post
    transaction using the value of the action attribute and a message
    created according to the content type specified by the enctype
    attribute.
    Quote from CGI FAQ

    Firstly, the the HTTP protocol specifies
    differing usages for the two methods. GET requests should always be
    idempotent on the server. This means that whereas one GET request
    might (rarely) change some state on the Server, two or more
    identical requests will have no further effect.

    This is a theoretical point which is also good
    advice in practice. If a user hits “reload” on his/her browser, an
    identical request will be sent to the server, potentially resulting
    in two identical database or
    guestbook entries, counter increments, etc. Browsers may reload a
    GET URL automatically, particularly if cacheing is disabled (as is
    usually the case with CGI output), but will typically prompt the
    user before
    re-submitting a POST request. This means you’re far less likely to
    get inadvertently-repeated entries from POST.

    GET is (in theory) the preferred method for
    idempotent operations, such as querying a database, though it
    matters little if you’re using a form. There is a further practical
    constraint that many systems have built-in limits to the length of a
    GET request they can handle: when the total size of a request (URL+params)
    approaches or exceeds 1Kb, you are well-advised to use POST in any
    case.

    I would prefer POST when I don’t want the status to
    be change when user resubmits. And GET
    when it does not matter.

    Q:2 Who is the father of PHP and explain the changes in PHP versions?
    A:2 Rasmus Lerdorf is known as the father of PHP.PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3
    is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current
    generation of PHP, which uses the
    Zend engine
    under the
    hood. PHP 5 uses
    Zend engine 2 which,
    among other things, offers many additionalOOP features

    Q:3 How can we submit a form without a submit button?
    A:3 The main idea behind this is to use Java script submit() function in
    order to submit the form without explicitly clicking any submit button.
    You can attach the document.formname.submit() method to onclick,
    onchange events of different inputs and perform the form submission. you
    can even built a timer function where you can automatically submit the
    form after xx seconds once the loading is done (can be seen in online
    test sites).

    Q:4 In how many ways we can retrieve the data in the result set of
    MySQL using PHP?

    A:4 You can do it by 4 Ways1. mysql_fetch_row.
    2. mysql_fetch_array
    3. mysql_fetch_object
    4. mysql_fetch_assoc

    Q:5 What is the difference between mysql_fetch_object and
    mysql_fetch_array?

    A:5 mysql_fetch_object() is similar tomysql_fetch_array(), with one difference -
    an object is returned, instead of an array. Indirectly, that means that
    you can only access the data by the field names, and not by their
    offsets (numbers are illegal property names).

    Q:6 What is the difference between $message and $$message?
    A:6 It is a classic example of PHP’s variable variables. take the
    following example.$message = “Mizan”;$$message = “is a moderator of PHPXperts.”;$message is a simple PHP variable that we are used to. But the
    $$message is not a very familiar face. It creates a variable name $mizan
    with the value “is a moderator of PHPXperts.” assigned. break it like
    this${$message} => $mizanSometimes it is convenient to be able to have variable variable
    names. That is, a variable name which can be set and used dynamically.

    Q:7 How can we extract string ‘abc.com ‘ from a string ‘http://info@abc.com’
    using regular expression of PHP?

    A:7 preg_match(”/^http:\/\/.+@(.+)$/”,’http://info@abc.com’,$found);
    echo $found[1];

    Q:8 How can we create a database using PHP and MySQL?
    A:8 We can create MySQL database with the use of
    mysql_create_db(“Database Name”)

    Q:9 What are the differences between require and include,
    include_once and require_once?
    A:9

    The include() statement includes
    and evaluates the specified file.The documentation below also applies to
    require(). The two constructs
    are identical in every way except how they handle
    failure. include() produces a
    Warning while require() results
    in a Fatal Error. In other words, use
    require() if you want a missing
    file to halt processing of the page.
    include() does not behave this way, the script will
    continue regardless.

    The include_once()
    statement includes and evaluates the
    specified file during the execution of
    the script. This is a behavior similar
    to the include()
    statement, with the only difference
    being that if the code from a file has
    already been included, it will not be
    included again. As the name suggests, it
    will be included just once.include_once()
    should be used in cases where the same
    file might be included and evaluated
    more than once during a particular
    execution of a script, and you want to
    be sure that it is included exactly once
    to avoid problems with function
    redefinitions, variable value
    reassignments, etc.

    require_once()
    should be used in cases where the same
    file might be included and evaluated
    more than once during a particular
    execution of a script, and you want to
    be sure that it is included exactly once
    to avoid problems with function
    redefinitions, variable value
    reassignments, etc.

    Q:10 Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?
    A:10 Yes we can use include() more than one time in any page though it is
    not a very good practice.

    Q:11 What are the different tables present in MySQL, which type of
    table is generated when we are creating a table in the following syntax:
    create table employee (eno int(2),ename varchar(10)) ?

    A:11 Total 5 types of tables we can create
    1. MyISAM
    2. Heap
    3. Merge
    4. INNO DB
    5. ISAM
    MyISAM is the default storage engine as of MySQL 3.23 and as a result if
    we do not specify the table name explicitly it will be assigned to the
    default engine.

    Q:12 Functions in IMAP, POP3 AND LDAP?
    A:12 These functions enable you to operate with the IMAP protocol, as well as the NNTPPOP3 and local mailbox access methods  You can find these specific information in PHP Manual.

    Q:13 How can I execute a PHP script using command line?
    A:13 As of version 4.3.0, PHP supports a new SAPI type (Server
    Application Programming Interface) named CLI which means Command Line
    Interface. Just run the PHP CLI (Command Line Interface) program and
    provide the PHP script file name as the command line argument. For
    example, “php myScript.php”, assuming “php” is the command to invoke the
    CLI program.
    Be aware that if your PHP script was written for the Web CGI interface,
    it may not execute properly in command line environment.

    Q:14 Suppose your Zend engine supports the mode Then how can u
    configure your PHP Zend engine to support mode ?

    A:14 In php.ini file:
    set
    short_open_tag=on
    to make PHP support

    Q:15 Shopping cart online validation i.e. how can we configure Paypal,
    etc.?

    A:15 We can find the detail documentation about different paypal
    integration process at the following site

    PayPal PHP
    SDK : http://www.paypaldev.org

    Q:16 What is meant by nl2br()?
    A:16 Inserts HTML line breaks (
    ) before all newlines in a string
    string nl2br (string); Returns string with ” inserted before all
    newlines. For example: echo nl2br(”god bless\n you”) will output “god
    bless
    you” to your browser.

    Q:17 Draw the architecture of Zend engine?
    A:17 The Zend Engine is the internal compiler and runtime engine used by
    PHP4. Developed by Zeev Suraski and Andi Gutmans, the Zend Engine is an
    abbreviation of their names. In the early days of PHP4, it worked as
    follows:
    The PHP script was loaded by the Zend Engine and compiled into Zend
    opcode. Opcodes, short for operation codes, are low level binary
    instructions. Then the opcode was executed and the HTML generated sent
    to the client. The opcode was flushed from memory after execution.Today, there are a multitude of products and techniques to help you
    speed up this process. In the following diagram, we show the how modern
    PHP scripts work; all the shaded boxes are optional.
    PHP Scripts are loaded into memory and compiled into Zend opcodes.

    Q:18 What are the current versions of apache, PHP, and MySQL?
    A:18 As of February, 2007 the current versions arePHP: php5.2.1
    MySQL: MySQL 5.2
    Apache: Apache 2.2.4Note: visit www.php.net,

    http://dev.mysql.com/downloads/mysql/,
    www.apache.org to get current
    versions.

    Q:19 What are the reasons for selecting lamp (Linux, apache, MySQL,
    PHP) instead of combination of other software programs, servers and
    operating systems?

    A:19 All of those are open source resource. Security of Linux is very
    very more than windows. Apache is a better server that IIS both in
    functionality and security. MySQL is world most popular open source
    database. PHP is more faster that asp or any other scripting language.

    Q:20 How can we encrypt and decrypt a data present in a MySQL table
    using MySQL?

    A:20 AES_ENCRYPT () and AES_DECRYPT ()

    Q:21 How can we encrypt the username and password using PHP?
    A:21 The functions in this section perform encryption and decryption, and
    compression and uncompression:

    encryption decryption
    AES_ENCRYT() AES_DECRYPT()
    ENCODE() DECODE()
    DES_ENCRYPT() DES_DECRYPT()
    ENCRYPT() Not available
    MD5() Not available
    OLD_PASSWORD() Not available
    PASSWORD() Not available
    SHA() or SHA1() Not available
    Not available UNCOMPRESSED_LENGTH()

    Q:22 What are the features and advantages of object-oriented
    programming?

    A:22 One of the main advantages of OO programming is its ease of
    modification; objects can easily be modified and added to a system there
    by reducing maintenance costs. OO programming is also considered to be
    better at modeling the real world than is procedural programming. It
    allows for more complicated and flexible interactions. OO systems are
    also easier for non-technical personnel to understand and easier for
    them to participate in the maintenance and enhancement of a system
    because it appeals to natural human cognition patterns.
    For some systems, an OO approach can speed development time since many
    objects are standard across systems and can be reused. Components that
    manage dates, shipping, shopping carts, etc. can be purchased and easily
    modified for a specific system

    Q:23 What are the differences between procedure-oriented languages and
    object-oriented languages?

    A:23 Traditional programming has the following characteristics:Functions are written sequentially, so that a change in programming can
    affect any code that follows it.
    If a function is used multiple times in a system (i.e., a piece of code
    that manages the date), it is often simply cut and pasted into each
    program (i.e., a change log, order function, fulfillment system, etc).
    If a date change is needed (i.e., Y2K when the code needed to be changed
    to handle four numerical digits instead of two), all these pieces of
    code must be found, modified, and tested.
    Code (sequences of computer instructions) and data (information on which
    the instructions operates on) are kept separate. Multiple sets of code
    can access and modify one set of data. One set of code may rely on data
    in multiple places. Multiple sets of code and data are required to work
    together. 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:Code and data are merged into one indivisible item – an object (the
    term “component” has also been used to describe an object.) An object is
    an abstraction of a set of real-world things (for example, an object may
    be created around “date”) The object would contain all information and
    functionality for that thing (A date
    object it may contain labels like January, February, Tuesday, Wednesday.
    It may contain functionality that manages leap years, determines if it
    is a business day or a holiday, etc., See Fig. 1). Ideally, information
    about a particular thing should reside in only one place in a system.
    The information within an object is encapsulated (or hidden) from the
    rest of the system.
    A system is composed of multiple objects (i.e., date function, reports,
    order processing, etc., See Fig 2). When one object needs information
    from another object, a request is sent asking for specific information.
    (for example, a report object may need to know what today’s date is and
    will send a request to the date object) These requests are called
    messages and each object has an interface that manages messages.
    OO programming languages include features such as “class”, “instance”,
    “inheritance”, and “polymorphism” that increase the power and
    flexibility of an object.

    Q:24 What is the use of friend function?
    A:24 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. In either case they can be set to be
    friends of other classes, by using a friend specifier in the class that
    is admitting them. Such functions can use all attributes of the class
    which names them as a friend, as if they were themselves members of that
    class.
    A friend declaration is essentially a prototype for a member function,
    but instead of requiring an implementation with the name of that class
    attached by the double colon syntax, a global function or member
    function of another class provides the match.

    Q:25 What are the differences between public, private, protected,
    static, transient, final and volatile?

    A:25 Public: Public declared items can be accessed everywhere.
    Protected: Protected limits access to inherited and parent
    classes (and to the class that defines the item).
    Private: Private limits visibility only to the class that defines
    the item.
    Static: A static variable exists only in a local function scope,
    but it does not lose its value when program execution leaves this scope.
    Final: Final keyword prevents child classes from overriding a
    method by prefixing the definition with final. If the class itself is
    being defined final then it cannot be extended.
    transient: A transient variable is a variable that may not
    be serialized.
    volatile: a variable that might be concurrently modified by multiple
    threads should be declared volatile. Variables declared to be volatile
    will not be optimized by the compiler because their value can change at
    any time.

    Q:26 What are the different types of errors in PHP?
    A:26 Three are three types of errors: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, as you will
    see, you can change this default behavior.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 behavior is to display them to the user
    when they take place.

    Q:27 What is the functionality of the function strstr and stristr?
    A:27 strstr:

    Returns part of haystack
    string from the first occurrence of
    needle to the end of
    haystack.If needle is not found,
    returns FALSE.

    If needle is not a
    string, it is converted to an integer and applied as the
    ordinal value of a character.

    This function is case-sensitive. For
    case-insensitive searches, use
    stristr().

    Q:28 What are the differences between PHP 3 and PHP 4 and PHP 5?
    A:28 Please read the release notes at
    http://www.php.net.

    Q:29 How can we convert asp pages to PHP pages?
    A:29 there are lots of tools available for asp to PHP conversion. you can
    search Google for that. the best one is available athttp://asp2php.naken.cc./

    Q:30 What is the functionality of the function htmlentities?
    A:30 Convert all applicable characters to HTML entities
    This function is identical to htmlspecialchars() in all ways, except
    with htmlentities(), all characters which have HTML character entity
    equivalents are translated into these entities.

    Q:31 How can we get second of the current time using date function?
    A:31 $second = date(”s”);

    Q:32 How can we convert the time zones using PHP?
    A:32 By using date_default_timezone_get and
    date_default_timezone_set function on PHP 5.1.0

    // Discover what 8am in Tokyo relates to on the East Coast of the US

    // Set the default timezone to Tokyo time:
    date_default_timezone_set(‘Asia/Tokyo’);

    // Now generate the timestamp for that particular timezone, on Jan 1st, 2000
    $stamp = mktime(8, 0, 0, 1, 1, 2000);

    // Now set the timezone back to US/Eastern
    date_default_timezone_set(‘US/Eastern’);

    // Output the date in a standard format (RFC1123), this will print:
    // Fri, 31 Dec 1999 18:00:00 EST
    echo ‘

    ‘, date(DATE_RFC1123, $stamp) ,’

    ‘;?>

    Q:33 What is meant by urlencode and urldecode?
    A:33 URLencode returns a string in which all non-alphanumeric characters
    except -_. have been replaced with a percent (%)
    sign followed by two hex digits and spaces encoded as plus (+)
    signs. It is encoded the same way that the posted data from a WWW form
    is encoded, that is the same way as in
    application/x-www-form-urlencoded media type.

    urldecode decodes any %##
    encoding in the given string.

    Q:34 What is the difference between the functions unlink and unset?
    A:34 unlink() deletes the given file from the file system.
    unset() makes a variable undefined.

    Q:35 How can we register the variables into a session?
    A:35 $_SESSION[’name’] = “Mizan”;

    Q:36 How can we get the properties (size, type, width, height) of an
    image using PHP image functions?

    A:36 To know the Image type use exif_imagetype () function
    To know the Image size use getimagesize () function
    To know the image width use imagesx () function
    To know the image height use imagesy() function t

    Q:37 How can we get the browser properties using PHP?
    A:37 By using
    $_SERVER['HTTP_USER_AGENT']
    variable.

    Q:38 What is the maximum size of a file that can be uploaded using PHP
    and how can we change this?

    A:38 By default the maximum size is 2MB. and we can change the following
    setup at php.iniupload_max_filesize = 2M

    Q:39 How can we increase the execution time of a PHP script?
    A:39 by changing the following setup at php.inimax_execution_time = 30
    ; Maximum execution time of each script, in seconds

    Q:40 How can we take a backup of a MySQL table and how can we restore
    it. ?

    A:40 To backup: BACKUP TABLE tbl_name[,tbl_name…] TO
    ‘/path/to/backup/directory’
    RESTORE TABLE tbl_name[,tbl_name…] FROM ‘/path/to/backup/directory’mysqldump: Dumping Table Structure and DataUtility to dump a database or a collection of database for backup or
    for transferring the data to another SQL server (not necessarily a MySQL
    server). The dump will contain SQL statements to create the table and/or
    populate the table.
    -t, –no-create-info
    Don’t write table creation information (the CREATE TABLE statement).
    -d, –no-data
    Don’t write any row information for the table. This is very useful if
    you just want to get a dump of the structure for a table!

    Q:41 How can we optimize or increase the speed of a MySQL select
    query?

    A:41

    * first of all instead of using select * from table1, use select
    column1, column2, column3.. from table1
    * Look for the opportunity to introduce index in the table you are
    querying.
    * use limit keyword if you are looking for any specific number of
    rows from the result set.

    Q:42 How many ways can we get the value of current session id?
    A:42 session_id() returns the session id for the current session.

    Q:43 How can we destroy the session, how can we unset the variable of
    a session?

    A:43 session_unregister — Unregister a global variable from the current
    session
    session_unset — Free all session variables

    Q:44 How can we destroy the cookie?
    A:44 Set the cookie in past.

    Q:45 How many ways we can pass the variable through the navigation
    between the pages?

    A:45

    * GET/QueryString
    * POST

    Q:46 What is the difference between ereg_replace() and eregi_replace()?
    A:46 eregi_replace() function is identical to ereg_replace() except that
    this ignores case distinction when matching alphabetic
    characters.eregi_replace() function is identical to ereg_replace()
    except that this ignores case distinction when matching alphabetic
    characters.

    Q:47 What are the different functions in sorting an array?
    A:47 Sort(), arsort(),
    asort(), ksort(),
    natsort(), natcasesort(),
    rsort(), usort(),
    array_multisort(), and
    uksort().

    Q:48 How can we know the count/number of elements of an array?
    A:48 2 ways
    a) sizeof($urarray) This function is an alias of count()
    b) count($urarray)

    Q:49 What is the PHP predefined variable that tells the What types of
    images that PHP supports?

    A:49 Though i am not sure if this is wrong or not, With the exif
    extension you are able to work with image meta data.

    Q:50 How can I know that a variable is a number or not using a
    JavaScript?

    A:50 bool is_numeric ( mixed var)
    Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is not a number.

    Q:51 List out some tools through which we can draw E-R diagrams for
    mysql.

    A:51 Case Studio
    Smart Draw

    Q:52 How can I retrieve values from one database server and store them
    in other database server using PHP?

    A:52 we can always fetch from one database and rewrite to another. here
    is a nice solution of it.$db1 = mysql_connect(”host”,”user”,”pwd”)
    mysql_select_db(”db1″, $db1);
    $res1 = mysql_query(”query”,$db1);$db2 = mysql_connect(”host”,”user”,”pwd”)
    mysql_select_db(”db2″, $db2);
    $res2 = mysql_query(”query”,$db2);At this point you can only fetch records from you previous ResultSet,
    i.e $res1 – But you cannot execute new query in $db1, even if you
    supply the link as because the link was overwritten by the new db.so at this point the following script will fail
    $res3 = mysql_query(”query”,$db1); //this will failSo how to solve that?

    take a look below.
    $db1 = mysql_connect(”host”,”user”,”pwd”)
    mysql_select_db(”db1″, $db1);
    $res1 = mysql_query(”query”,$db1);

    $db2 = mysql_connect(”host”,”user”,”pwd”, true)
    mysql_select_db(”db2″, $db2);
    $res2 = mysql_query(”query”,$db2);

    So mysql_connect has another optional boolean parameter which
    indicates whether a link will be created or not. as we connect to the
    $db2 with this optional parameter set to ‘true’, so both link will
    remain live.

    now the following query will execute successfully.
    $res3 = mysql_query(”query”,$db1);

    Thanks goes to Hasan and Hasin for this solution.

    Q:53 List out the predefined classes in PHP?
    A:53 Directory
    stdClass
    __PHP_Incomplete_Class
    exception
    php_user_filter

    Q:54 How can I make a script that can be bi-language (supports
    English, German)?

    A:54 You can maintain two separate language file for each of the
    language. all the labels are putted in both language files as variables
    and assign those variables in the PHP source. on runtime choose the
    required language option.

    Q:55 What are the difference between abstract class and interface?
    A:55 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.

    Q:56 How can we send mail using JavaScript?
    A:56 JavaScript does not have any networking capabilities as it is
    designed to work on client site. As a result we can not send mails using
    JavaScript. But we can call the client side mail protocol mailto
    via JavaScript to prompt for an email to send. this requires the client
    to approve it.

    Q:57 How can we repair a MySQL table?
    A:57 The syntex for repairing a MySQL table is
    REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended]
    This command will repair the table specified if the quick is given the
    MySQL will do a repair of only the index tree if the extended is given
    it will create index row by row

    Q:58 What are the advantages of stored procedures, triggers, indexes?
    A:58 A stored procedure is a set of SQL commands that can be compiled and
    stored in the server. Once this has been done, clients don’t need to
    keep re-issuing the entire query but can refer to the stored procedure.
    This provides better overall performance because the query has to be
    parsed only once, and less information needs to be sent between the
    server and the client. You can also raise the conceptual level by having
    libraries of functions in the server. However, stored procedures of
    course do increase the load on the database server system, as more of
    the work is done on the server side and less on the client (application)
    side.Triggers will also be implemented. A trigger is effectively a type of
    stored procedure, one that is invoked when a particular event occurs.
    For example, you can install a stored procedure that is triggered each
    time a record is deleted from a transaction table and that stored
    procedure automatically deletes the corresponding customer from a
    customer table when all his transactions are deleted.Indexes are used to find rows with specific column values quickly.
    Without an index, MySQL must begin with the first row and then read
    through the entire table to find the relevant rows. The larger the
    table, the more this costs. If the table has an index for the columns in
    question, MySQL can quickly determine the position to seek to in the
    middle of the data file without having to look at all the data. If a
    table has 1,000 rows, this is at least 100 times faster than reading
    sequentially. If you need to access most of the rows, it is faster to
    read sequentially, because this minimizes disk seeks.

    Q:59 What is the maximum length of a table name, database name, and
    fieldname in MySQL?

    A:59 The following table describes the maximum length for each type of
    identifier.

    Identifier Maximum Length
    (bytes)
    Database 64
    Table 64
    Column 64
    Index 64
    Alias 255

    There are some restrictions on the characters that may appear in
    identifiers:

    Q:60 How many values can the SET function of MySQL take?
    A:60 MySQL set can take zero or more values but at the maximum it can
    take 64 values

    Q:61 What are the other commands to know the structure of table using
    MySQL commands except explain command?

    A:61 describe Table-Name;

    Q:62 How many tables will create when we create table, what are they?
    A:62 The ‘.frm’ file stores the table definition.
    The data file has a ‘.MYD’ (MYData) extension.
    The index file has a ‘.MYI’ (MYIndex) extension,

    Q:63 What is the purpose of the following files having extensions 1) .frm
    2) .myd 3) .myi? What do these files contain?

    A:63 In MySql, the default table type is MyISAM.
    Each MyISAM table is stored on disk in three files. The files have names
    that begin with the table name and have an extension to indicate the
    file type.
    The ‘.frm’ file stores the table definition.
    The data file has a ‘.MYD’ (MYData) extension.
    The index file has a ‘.MYI’ (MYIndex) extension,

    Q:64 What is maximum size of a database in MySQL?
    A:64 If the operating system or filesystem places a limit on the number
    of files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers of
    files in a directory can place a practical limit on the number of tables
    in a database. If the time required to open a file in the directory
    increases significantly as the number of files increases, database
    performance can be adversely affected.
    The amount of available disk space limits the number of tables.
    MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM
    storage engine in MySQL 3.23, the maximum table size was increased to
    65536 terabytes (2567 – 1 bytes). With this larger allowed table size,
    the maximum effective table size for MySQL databases is usually
    determined by operating system constraints on file sizes, not by MySQL
    internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace
    that can be created from several files. This allows a table to exceed
    the maximum individual file size. The tablespace can include raw disk
    partitions, which allows extremely large tables. The maximum tablespace
    size is 64TB.
    The following table lists some examples of operating system file-size
    limits. This is only a rough guide and is not intended to be definitive.
    For the most up-to-date information, be sure to check the documentation
    specific to your operating system.
    Operating System File-size LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB)
    Linux 2.4+ (using ext3 filesystem) 4TB
    Solaris 9/10 16TB
    NetWare w/NSS filesystem 8TB
    Win32 w/ FAT/FAT32 2GB/4GB
    Win32 w/ NTFS 2TB (possibly larger)
    MacOS X w/ HFS+ 2TB

    Q:65 Give the syntax of Grant and Revoke commands?
    A:65 The generic syntax for grant is as following
    > GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY
    [password]
    now rights can be
    a) All privileges
    b) combination of create, drop, select, insert, update and delete etc.We can grant rights on all databse by using *.* or some specific
    database by database.* or a specific table by database.table_name
    username@hotsname can be either username@localhost, username@hostname
    and username@%
    where hostname is any valid hostname and % represents any name, the *.*
    any condition
    password is simply the password of userThe generic syntax for revoke is as following
    > REVOKE [rights] on [database/s] FROM [username@hostname]
    now rights can be as explained above
    a) All privileges
    b) combination of create, drop, select, insert, update and delete etc.
    username@hotsname can be either username@localhost, username@hostname
    and username@%
    where hostname is any valid hostname and % represents any name, the *.*
    any condition

    Q:66 Explain Normalization concept?
    A:66 The normalization process involves getting our data to conform to
    three progressive normal forms, and a higher level of normalization
    cannot be achieved until the previous levels have been achieved (there
    are actually five normal forms, but the last two are mainly academic and
    will not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of redundant data
    from horizontal rows. We want to ensure that there is no duplication of
    data in a given row, and that every column stores the least amount of
    information possible (making the field atomic).Second Normal FormWhere the First Normal Form deals with redundancy of data across a
    horizontal row, Second Normal Form (or 2NF) deals with redundancy of
    data in vertical columns. As stated earlier, the normal forms are
    progressive, so to achieve Second Normal Form, your tables must already
    be in First Normal Form.Third Normal Form

    I have a confession to make; I do not often use Third Normal Form. In
    Third Normal Form we are looking for data in our tables that is not
    fully dependant on the primary key, but dependant on another value in
    the table

    Q:67 How can we find the number of rows in a table using MySQL?
    A:67 Use this for mysql
    >SELECT COUNT(*) FROM table_name;

    Q:68 How can we find the number of rows in a result set using PHP?
    A:68 $result = mysql_query($sql, $db_link);
    $num_rows = mysql_num_rows($result);
    echo “$num_rows rows found”;

    Q:69 How many ways we can we find the current date using MySQL?
    A:69 SELECT CURDATE();
    CURRENT_DATE() = CURDATE()
    for time use
    SELECT CURTIME();
    CURRENT_TIME() = CURTIME()

    Q:70 What are the advantages and disadvantages of Cascading Style
    Sheets?

    A:70 External Style SheetsAdvantagesCan control styles for multiple documents at once. Classes can be
    created for use on multiple HTML element types in many documents.
    Selector and grouping methods can be used to apply styles under complex
    contextsDisadvantagesAn extra download is required to import style information for each
    document The rendering of the document may be delayed until the external
    style sheet is loaded Becomes slightly unwieldy for small quantities of
    style definitionsEmbedded Style Sheets

    Advantages

    Classes can be created for use on multiple tag types in the document.
    Selector and grouping methods can be used to apply styles under complex
    contexts. No additional downloads necessary to receive style information

    Disadvantages

    This method can not control styles for multiple documents at once

    Inline Styles

    Advantages

    Useful for small quantities of style definitions. Can override other
    style specification methods at the local level so only exceptions need
    to be listed in conjunction with other style methods

    Disadvantages

    Does not distance style information from content (a main goal of
    SGML/HTML). Can not control styles for multiple documents at once.
    Author can not create or control classes of elements to control multiple
    element types within the document. Selector grouping methods can not be
    used to create complex element addressing scenarios

    Q:71 What type of inheritance that PHP supports?
    A:71 In PHP an extended class is always dependent on a single base class,
    that is, multiple inheritance is not supported. Classes are extended
    using the keyword ‘extends’.

    Q:72 What is the difference between Primary Key and
    Unique key?

    A:72 Primary Key: A column in a table whose values uniquely identify the
    rows in the table. A primary key value cannot be NULL.

    Unique Key: Unique Keys are used to uniquely identify each row in the
    table. There can be one and only one row for each unique key value. So
    NULL can be a unique key.There can be only one primary key for a table but there can be more
    than one unique for a table.

    Q:73 The structure of table view buyers is as follows:

    Field Type Null Key Default Extra
    user_pri_id int(15) PRI null auto_increment
    userid varchar(10) YES null

    the value of user_pri_id the last row 999 then What will happen in
    the following conditions?

    Condition1: Delete all the rows and insert another row then.
    What is the starting value for this auto incremented field user_pri_id ,
    Condition2: Delete the last row(having the field value 999) and
    insert another row then. What is the value for this auto incremented
    field user_pri_id
    A:73 In both cases let the value for auto increment field be n then next
    row will have value n+1 i.e. 1000

    Q:74 What are the advantages/disadvantages of MySQL and PHP?
    A:74 Both of them are open source software (so free of cost), support
    cross platform. php is faster then ASP and JSP.

    Q:75 What is the difference between GROUP BY and ORDER BY in Sql?
    A:75 ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns
    it should sort the result. If two rows will hawe the same value in col1
    it will try to sort them according to col2 and so on.GROUP BY
    [col1],[col2],…,[coln]; Tels DBMS to group results with same value of
    column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if
    you want to count all items in group, sum all values or view average

    Q:76 What is the difference between char and varchar data types?
    A:76 Set char to occupy n bytes and it will take n bytes even if u r
    storing a value of n-m bytes
    Set varchar to occupy n bytes and it will take only the required space
    and will not use the n bytes
    eg. name char(15) will waste 10 bytes if we store ‘mizan’, if each char
    takes a byte
    eg. name varchar(15) will just use 5 bytes if we store ‘mizan’, if each
    char takes a byte. rest 10 bytes will be free.

    Q:77 What is the functionality of md5 function in PHP?
    A:77 Calculate the md5 hash of a string. The hash is a 32-character
    hexadecimal number. I use it to generate keys which I use to identify
    users etc. If I add random no techniques to it the md5 generated now
    will be totally different for the same string I am using.

    Q:78 How can I load data from a text file into a table?
    A:78 you can use LOAD DATA INFILE file_name; syntax to load data
    from a text file. but you have to make sure thata) data is delimited
    b) columns and data matched correctly

    Q:79 How can we know the number of days between two given dates using
    MySQL?

    A:79 SELECT DATEDIFF(’2007-03-07′,’2005-01-01′);

    Q:80 How can we know the number of days between two given dates using
    PHP?

    A:80 $date1 = date(’Y-m-d’);
    $date2 = ‘2006-08-15′;
    $days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);

     

    Q:81 What is ‘float’ property in CSS?

    A:81 The float property sets where an image or a text will appear in another element.

        

    Q:82 What is descendant structure in CSS?

    A:82 Descendant selectors are used to select elements that are descendants of another element in the document tree.For example, you may wish to target a specific <em> element on the page, but not all <em> elements. A sample document could contain the following code: <body>

    <h1>Heading <em>here</em> </h1>

    <p>Lorem ipsum dolor <em>sit</em> amet.</p>

    </body> The document tree diagram (with the <em> element to be targeted) would be:Document tree showing descendant selectorsIf you use a type selector like the example below, you will select all <em> elements on the page:

     

    em {color: blue; } However, if you use a descendant selector, you can refine the <em> elements that you select. The rule below will only select <em> elements that are descendants of <p> elements. If this rule is applied, the <em> element within the <h1> will not be colored blue.

     

    p em {color: blue; } You can also jump levels in the document tree structure to select descendants. For example, the following code:

     

    <body>

    <p>Lorem ipsum dolor <em>sit</em> amet.</p>

    <ul>

    <li>item 1</li>

    <li>item 2</li>

    <li><em>item 3</em></li>

    </ul>

    </body> The document tree (with a third-level <em> element highlighted) would be:

     

    Document tree showing descendant selectors

     

    Using the following rule you can isolate any <em> element inside a <ul> element, without having to describe the <li> element. If this rule is applied, any <em> element within a <ul> element will be colored blue. However, the <em> element within the <p> will not be colored blue:

     

    ul em {color: blue; } Descendant selectors are well supported across standards-compliant browsers.

        

    Q:83 What is Child Descendant structure in CSS?

    A:83

    Child selectors

     

    A child selector is used to select an element that is a direct child of another element (parent). Child selectors will not select all descendants, only direct children.

     

    For example, you may wish to target an <em> that is a direct child of a <div>, but not other <em> elements that are descendants of the <div>. A sample document could contain the following code:

     

    <body>

    <h1>Heading <em>text</em></h1>

    <div>

    This is some <em>text</em>

    <p>This is a paragraph of <em>text</em></p>

    </div>

    </body>

    The document tree (highlighting the <em> that is a child of the <div>) would be:

     

    Document tree showing child selector

     

    Using the following rule you can target any <em> element that is a child of the <div>. Other <em> elements that are descendants but not direct children of the <div> will not be targeted.

     

    div > em { color: blue; }

     

    OR

     

    div>em { color: blue; }

    Child selectors are not supported by Windows Internet Explorer 5, 5.5 and 6, but are supported by most other standards-compliant browsers.

        

    Q:84 How to create a class in JavaScript?

    A:84 Classes can seem off-putting at first, but once you see the point of them, their use can be invaluable.We have already met objects. A computer object is a representation of a real object. For an estate agent the object may be a house, including information about the number of rooms and the price.An estate agent may have a lot of houses available. These houses all have different characteristics, and as objects they all go through the same processes. They are viewed, surveyed and bought, and so on.A full estate agent program would be difficult to demonstrate here, but we can introduce the use of classes.In this example, we have the house class. The house class produces house objects, all with object properties, such as number of rooms and price, and all having access to the same methods, such as sold and bought.

     

    So a class can create objects with a group of properties and methods.

     

    JavaScript doesn’t have a keyword specific to class, so we must go back to basics and develop classes in a different way. This isn’t very difficult.

    Class Properties

     

    Let us examine a very small estate agent program.

     

    <HTML>

    <HEAD>

    <TITLE>Estate Agent</TITLE>

    <SCRIPT>

    function House(rooms,price,garage) {

    this.rooms=rooms;

    this.price=price;

    this.garage=garage;

    }

    house1=new House(4,100000,false);

    house2=new House(5,200000,true);

    with (house1) document.write(’House 1 has ‘+rooms+’ rooms, ‘+(garage?’a’:’no’)+’ garage, and costs £’+price+’<BR>’);

    with (house2) document.write(’House 2 has ‘+rooms+’ rooms, ‘+(garage?’a’:’no’)+’ garage, and costs £’+price+’<BR>’);

    </SCRIPT>

    </HEAD>

    </HTML>

     

    We define a House function that takes three parameters, rooms, price and garage. The function uses the this keyword to create an object.

     

    When we call the House function, we assign the result to our variable, which becomes an object.

     

    So, identical code would be:

     

    house1=new Object();

    house1.rooms=4;

    house1.price=100000;

    house1.garage=false;

     

    We would have to type this in for all houses, which would be very tedious and is why we use the class structure instead.

     

    When we display the details for a house, I have introduced the ternary operator, ‘?:’. The ternary operator is a compacted version of:

     

    if (garage) str=’a’; else str=’no’;

     

    (garage?’a’:’no’) means if garage is true, return ‘a’ else return ‘no’. Using the ternary operator removes a line of code, and avoids having to create a new variable.

    Class Methods

     

    The House class we have so far defined only contains object properties. We could add a method to replace the document.write() action we used before. (See example)

     

    <HTML>

    <HEAD>

    <TITLE>Estate Agent 2</TITLE>

    <SCRIPT>

    function House(name,rooms,price,garage) {

    this.name=name;

    this.rooms=rooms;

    this.price=price;

    this.garage=garage;

    this.view=view;

    }

    function view() {

    with (this) document.write(name+’ has ‘+rooms+’ rooms, ‘+(garage?’a’:’no’)+’ garage, and costs £’+price+’<BR>’);

    }

    house1=new House(’House 1′,4,100000,false);

    house2=new House(’Big House’,5,200000,true);

    house1.view();

    house2.view();

    </SCRIPT>

    </HEAD>

    </HTML>

     

    Much better!

     

    Note how we must add another property, name, so that we can identify the house in question. This offers more flexibility than re-using the variable name, and the variable name is inaccessible anyway, i.e. it is very difficult, if not impossible, to get the view() function to use the string ‘house1′.

        

    Q:85 Are namespaces are there in JavaScript?

    A:81 A namespace is a container and allows you to bundle up all your functionality using a unique name. In JavaScript, a namespace is really just an object that you’ve attached all further methods, properties and objects. But it is not always necessary to use namespace.

        

    Q:86 What is JSON? What are the notations used in JSON?

    A:86 JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

        

    Q:87 How to get Query String in PHP for http request?

    A:87 $_GET[] and $_REQUEST[]

        

    Q:88 How to get the http Request in PHP?

    A:88 When PHP is used on a Web server to handle a HTTP request, it converts information submitted in the HTTP request as predefined variables:

     

        * $_GET – Associate array of variables submitted with GET method.

        * $_POST – Associate array of variables submitted with POST method.

        * $_COOKIE – Associate array of variables submitted as cookies.

        * $_REQUEST – Associate array of variables from $_GET, $_POST, and $_COOKIE.

        * $_SERVER – Associate array of all information from the server and the HTTP request.

     

        

    Q:89 How you provide security for PHP application?

    A:89 There are many ways to accomplish the security tasks but the most common 7 ways are1. Validate Input. Never trust your user and always filter input before taking it to any operation.2. Provide access control.3. Session ID protection4. preventing Cross Site Scripting (XSS) flaws

     

    5. SQL injection vulnerabilities.

     

    6. Turning off error reporting and exposing to the site for hackers. Instead use log file to catch exceptions

     

    7. Effective Data handling

        

    Q:90 What is SQL Injection in PHP security?

    A:90 SQL injection attacks are extremely simple to defend against, but many applications are still vulnerable. Consider the following SQL statement:

     

    <?php

    $sql = “INSERT

            INTO   users (reg_username,

                          reg_password,

                          reg_email)

            VALUES (‘{$_POST['reg_username']}’,

                    ’$reg_password’,

                    ’{$_POST['reg_email']}’)”;

    ?>

     

    This query is constructed with $_POST, which should immediately look suspicious.

     

    Assume that this query is creating a new account. The user provides a desired username and an email address. The registration application generates a temporary password and emails it to the user to verify the email address. Imagine that the user enters the following as a username:

     

    bad_guy’, ‘mypass’, ”), (‘good_guy

     

    This certainly doesn’t look like a valid username, but with no data filtering in place, the application can’t tell. If a valid email address is given (shiflett@php.net, for example), and 1234 is what the application generates for the password, the SQL statement becomes the following:

     

    <?php

     

    $sql = “INSERT

            INTO   users (reg_username,

                          reg_password,

                          reg_email)

            VALUES (‘bad_guy’, ‘mypass’, ”),

              (‘good_guy’,

                    ’1234′,

                    ’shiflett@php.net’)”; ?>

     

    Rather than the intended action of creating a single account (good_guy) with a valid email address, the application has been tricked into creating two accounts, and the user supplied every detail of the bad_guy account.

     

    While this particular example might not seem so harmful, it should be clear that worse things could happen once an attacker can make modifications to your SQL statements.

     

    For example, depending on the database you are using, it might be possible to send multiple queries to the database server in a single call. Thus, a user can potentially terminate the existing query with a semicolon and follow this with a query of the user’s choosing.

     

    MySQL, until recently, does not allow multiple queries, so this particular risk is mitigated. Newer versions of MySQL allow multiple queries, but the corresponding PHP extension (ext/mysqli) requires that you use a separate function if you want to send multiple queries (mysqli_multi_query() instead of mysqli_query()). Only allowing a single query is safer, because it limits what an attacker can potentially do.

     

    Protecting against SQL injection is easy:

     

        * Filter your data.This cannot be overstressed. With good data filtering in place, most security concerns are mitigated, and some are practically eliminated.

        * Quote your data.If your database allows it (MySQL does), put single quotes around all values in your SQL statements, regardless of the data type.

        * Escape your data.Sometimes valid data can unintentionally interfere with the format of the SQL statement itself. Use mysql_escape_string() or an escaping function native to your particular database. If there isn’t a specific one, addslashes() is a good last resort.

     

        

    Q:91 What is cross site Scripting?

    A:91 To understand what Cross Site Scripting is, let’s see a usual situation, common to many sites. Let’s say we are taking some information passed in on a querystring (the string after the (?) character within a URL), with the purpose of displaying the content of a variable, for example, the visitor’s name:

     

    http://www.yourdomain.com/welcomedir/welcomepage.php?name=John

    As we can see in this simple querystring, we are passing the visitor’s name as a parameter in the URL, and then displaying it on our “welcomepage.php” page with the following PHP code:

     

    <?php

     

    echo ‘Welcome to our site ’ . stripslashes($_GET[‘name’]);

     

    ?>

    The result of this snippet is shown below:

     

    Welcome to our site John

    This is pretty simple and straightforward. We’re displaying the content of the “name” variable, by using the $_GET superglobal PHP array, as we have done probably hundreds of times. Everything seems to be fine. Now, what’s wrong with this code? Nothing really. But let’s modify the querystring by replacing our visitor’s name passed in the URL:

     

    http://www.yourdomain.com/welcomedir/

    welcomepage.php?name=John

    with something like this:

     

    http://www.yourdomain.com/welcomedir/

    welcomepage.php?name=

    <script language=javascript>alert

    (‘Hey, you are going to be hijacked!’);</script>

    Do you remember the PHP code included in our “welcome.php” page? Yes, you’re correct. When we modify the querystring, the following code is executed:

     

    <?php

     

    echo ‘Welcome to our site ‘ .

    <script language=javascript> alert(‘Hey, you are going

    to be hijacked!’);</script>

     

    ?>

    The output of this code is an alert JavaScript box telling you “Hey, you are going be hijacked!” after the “Welcome to our site” phrase.

     

    Very ugly stuff, right? That’s a simple example of the Cross Site Scripting vulnerability. This means that any pasted JavaScript code into the URL will be executed happily with no complaints at all.

     

        

    Q:92 Which method do you follow to get a record from a million records? (Searching, …. not from database, from an array in php)

    A:92 use array_search(), array_keys(), array_values(), array_key_exists(), and in_array().

        

    Q:93 Which sorting method is lowest time consumable?

    A:93 HeapSort, Merge sort are the lowest time consumable sorting algorithm.

        

    Q:94 Which sorting method is lowest memory consumable?

    A:9412341

    HTML, CSS & JavaScript Web Designer or Web Developer Interview Questions

    HTML, CSS & JavaScript Web Designer or web Developer Interview Questions

    HTML Web Standards Interview Question

     

    What is a DTD? What DTD do you generally use? Why? Pros and cons.

    A DTD is a Document Type Definition, also know as DOCTYPE. In a document served as text/html, the DOCTYPE informs the browswer how to interpret the content of the page. If the the doctype is not declared, the browser assumes you don’t know how to code, and goes into “quirks mode”. If you know what you are doing and include a correct XHTML DOCTYPE, your page will be rendered in “standards mode”.

    Accessibility Interview Question

    Importance in selecting font size for a web page?

    Font sizes should be declared using relative measurement values, such as ems, via a style sheet, without the use of the term !important. There are issues with browser font size enlarging which can be rectified via CSS.

    CSS Interview Question

    a) What are the possible values for the display attribute that are supported by all browsers?

    b) What is the default value for the display attribute for the image element? (what is the difference between inline and block level elements)
    c)What does display: run-in do?
    d) Difference between “visibility:hidden” and “display:none”? What are the pros and cons of using display:none?

    Answer

    main values: none, block, inline, list-item, run-in
    all values: inline | block | list-item | run-in | compact | marker | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | none | inherit
    default value: inline, block or list-item, depending on the element. The <img> is an inline element.
    Run-in should make the run-in element be the first line of the next sibling block level element, if it is before a block level element that is not floated or absolutely positioned. If the next sibling is positioned or floated, then the run-in element will be a block level element instead of appearing in-line.
    PPK’s Quirksmode explains it well. The w3schools lists table display values.
    When visibility is set to hidden, the element being hidden still occupies its same place in the layout of the page. If the display is set to none, the element does not occupy any space on the page — as if it didn’t exist..

     

    CSS Interview Question

    Question

    a) What are the five possible values for “position”?
    b) What is the default/initial value for “position”?
    c) How does the browser determine where to place positioned elements
    d) What are the pros and cons of using absolute positioning?
    e) if they are really advanced, ask about IE z-index issues with positioned elements.

    Answer

    a) Values for position: static, relative, absolute, fixed, inherit
    b) Static
    c) They are placed relative to the next parent element that has absolute or relative value declared
    d) Absolutely positioned elements are removed from the document flow. The positioned element does not flow around the content of other elements, nor does their content flow around the positioned element. An absolutely positioned element may overlap other elements, or be overlapped by them.
    e) IE treats a position like a z-index reset, so you have to declare position of static on the parent element containing the z-indexed elements to have them responsd to z-index correctly.

     

    CSS Interview Question

    Question:

    Write a snippet of CSS that will display a paragraph in blue in older browsers, red in newer browsers, green in IE6 and black in IE7

    Possible Answer:

    #content p{color:blue}
    html>body #content p {color:red}
    * html #content p{color:green}
    html>body #content p {*color:black;}

     

    Basic Javascript Interview Question

    Question:

    What is the correct way to include JavaScript into your HTML?

    Answer:

    correct explanation using inline event handlers or inline code

    Basic Javascript Array / XHTML Form Interview Question

    Question

    Are the following all equal, and, if so, what would your code look like to make the following all equal the same thing:

      alert(document.forms["myform"].elements["field"].value);
      alert(document.forms[1].elements[1].value);
      alert(document.myform.field.value);

    answer:

    <form name="myform" method="post" action="something">
    <input name="anything" value="anything" type="something" />
    <input name="field" value="something" type="something" />
    </form>

    Answer includes knowing that the form is the second form on the page, and that the field input element is the second element within that form.

     

    JavaScript Interview Question

    Question:

    How do you dynamically add a paragraph with stylized content to a page?

    Possible Answer:

    newParagraph = document.createElement('p');
    newParagraph.setAttribute('class', 'myClass');
    newText = document.createTextNode('this is a new paragraph');
    newParagraph.appendChild(newText);
    myLocation = document.getElementById('parent_of_new_paragraph);
    myLocation.appendChild(newParagraph);

     

    Other questions ideas:

    Q: How do you organize your CSS? How do you come up with id and class names (what naming conventions do you use)?
    A: While there are no right answers, there are best practices. Issues to look for are not having div mania, no inline CSS, no presentational markup, minimal use of classes, understanding the CSS cascade.

    Q: What do you think of hacks? When should you use them? If you use them, how do you maintain them? What can be done to avoid needing to use box-model hacks? (if they aren’t pros, you can ask them what is the issue with x-browsers and the box model)

    Q: What are the pros and cons of using tables for layout? Do you use tables? What are the pros and cons of tableless design? How do you generally layout your pages?
    A: check for them NOT using tables

    Q: What are some deprecated elements and attributes that you use, and in what instances do you use them?

    A: List of deprecated elements and attributes.

    Q: What is involved in making a website accessible? What are arguments you use to convince others to invest in making their web site accessible.
    A:  Making sites accessible also makes them more search engine friendly (saves money), makes your pages accessible to the 20% of the population that has some type of disability (so you can make more money) and it’s the law in many places.

    Q: Define what web standards mean to you? How do you implement web standards?

    Standardized specifications for Internet markup languages such as HTML, CSS, and XML. Formulated by the W3 organisation, these standards enable people to create websites that will work in almost any browser or internet-enabled device, instead of being specific to certain versions of Internet Explorer or Netscape Navigator.

    Q: In CSS, how can you make a form elments background-color change when the user is entering text? will this work in all browsers?

    It’s possible to change the default look of form elements by styling their html tags: inputselect and textarea.

    but it won’t work in all browsers

    Q: How can you target an element in your HTML using the DOM?

    by using the nodes of the DOm elements we can target any element on any event in HTML

    var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.” : “http://www.”);
    document.write(unescape(“%3Cscript src=’” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));

    try {
    var pageTracker = _gat._getTracker(“UA-1855756-5″);
    pageTracker._trackPageview();
    } catch(err) {}

    PHP OOPS Interview Questions & Answers

    PHP OOPS Interview Questions & Answers

    1) Explain what is object oriented programming language?
    Object oriented programming language allows concepts such as modularity, encapsulation, polymorphism and inheritance.  Objects are said to be the most important part of object oriented language. Concept revolves around making simulation programs around an object. Organize a program around its data (object)& set well define interface to that data. i.e. objects and a set of well defined interfaces to that data. OOP is the common abbreviation for Object-Oriented Programming.  OOps have many properties such as DataHiding,Inheritence,Data Absraction,Data Encapsulation and many more.

    2) Name some languages which have object oriented language and characteristics?
    Some of the languages which have object oriented languages present in them are ABAP, ECMA Script, C++, Perl, LISP, C#, Tcl, VB, Ruby, Python, PHP, etc. Popularity of these languages has increased considerably as they can solve complex problems with ease.
    3) Explain about UML?
    UML or unified modeling language is regarded to implement complete specifications and features of object oriented language. Abstract design can be implemented in object oriented programming languages. It lacks implementation of polymorphism on message arguments which is a OOPs feature.
    4) Explain the meaning of object in object oriented programming?
    Languages which are called as object oriented almost implement everything in them as objects such as punctuations, characters, prototypes, classes, modules, blocks, etc. They were designed to facilitate and implement object oriented methods.
    5) Explain about message passing in object oriented programming?
    Message passing is a method by which an object sends data to another object or requests other object to invoke method. This is also known as interfacing. It acts like a messenger from one object to other object to convey specific instructions.
    6) State about Java and its relation to Object oriented programming?
    Java is widely used and its share is increasing considerably which is partly due to its close resemblance to object oriented languages such as C++. Code written in Java can be transported to many different platforms without changing it. It implements virtual machine.
    7) What are the problems faced by the developer using object oriented programming language?

    These are some of the problems faced by the developer using object oriented language they are: -

    a) Object oriented uses design patterns which can be referred to as anything in general.
    b) Repeatable solution to a problem can cause concern and disagreements and it is one of the major problems in software design.
    8 ) State some of the advantages of object oriented programming?
    Some of the advantages of object oriented programming are as follows: -
    a) A clear modular structure can be obtained which can be used as a prototype and it will not reveal the mechanism behind the design. It does have a clear interface.
    b) Ease of maintenance and modification to the existing objects can be done with ease.
    c) A good framework is provided which facilitates in creating rich GUI applications.
    9 ) Explain about inheritance in OOPS?
    Objects in one class can acquire properties of the objects in other classes by way of inheritance. Reusability which is a major factor is provided in object oriented programming which adds features to a class without modifying it. New class can be obtained from a class which is already present.
    10) Explain about the relationship between object oriented programming and databases?
    Object oriented programming and relational database programming are almost similar in software engineering. RDBMS will not store objects directly and that’s where object oriented programming comes into play. Object relational mapping is one such solution.
    11) Explain about a class in OOP?
    In Object oriented programming usage of class often occurs. A class defines the characteristics of an object and its behaviors. This defines the nature and functioning of a specified object to which it is assigned. Code for a class should be encapsulated.

    12) Explain the usage of encapsulation?
    Encapsulation specifies the different classes which can use the members of an object. The main goal of encapsulation is to provide an interface to clients which decrease the dependency on those features and parts which are likely to change in future. This facilitates easy changes to the code and features.
    13) Explain about abstraction?
    Abstraction can also be achieved through composition. It solves a complex problem by defining only those classes which are relevant to the problem and not involving the whole complex code into play.
    14) Explain what a method is?
    A method will affect only a particular object to which it is specified. Methods are verbs meaning they define actions which a particular object will perform. It also defines various other characteristics of a particular object.
    15) Name the different Creational patterns in OO design?
    There are three patterns of design out of which Creational patterns play an important role the various patterns described underneath this are: -
    a) Factory pattern
    b) Single ton pattern
    c) Prototype pattern
    d) Abstract factory pattern
    e) Builder pattern
    16) Explain about realistic modeling?
    As we live in a world of objects, it logically follows that the object oriented approach models the real world accurately. The object oriented approach allows you to identify entities as objects having attributes and behavior.
    17) Explain about the analysis phase?
    The anlaysis or the object oriented analysis phase considers the system as a solution to a problem in its environment or domain. Developer concentrates on obtaining as much information as possible about the problem. Critical requirements needs to be identified.

    ************************************************************************************************************

    1) Explain the rationale behind Object Oriented concepts?

    Object oriented concepts form the base of all modern programming languages. Understanding the basic concepts of object-orientation helps a developer to use various modern day programming languages, more effectively.
    2) Explain about Object oriented programming?
    Object oriented programming is one of the most popular methodologies in software development. It offers a powerful model for creating computer programs. It speeds the program development process, improves maintenance and enhances reusability of programs.
    3) Explain what is an object?
    An object is a combination of messages and data. Objects can receive and send messages and use messages to interact with each other. The messages contain information that is to be passed to the recipient object.
    4) Explain the implementation phase with respect to OOP?
    The design phase is followed by OOP, which is the implementation phase. OOP provides specifications for writing programs in a programming language. During the implementation phase, programming is done as per the requirements gathered during the analysis and design phases.
    5) Explain about the Design Phase?
    In the design phase, the developers of the system document their understanding of the system. Design generates the blue print of the system that is to be implemented. The first step in creating an object oriented design is the identification of classes and their relationships.
    6) Explain about a class?
    Class describes the nature of a particular thing. Structure and modularity is provided by a Class in object oriented programming environment. Characteristics of the class should be understandable by an ordinary non programmer and it should also convey the meaning of the problem statement to him. Class acts like a blue print.

    7) Explain about instance in object oriented programming?
    Every class and an object have an instance. Instance of a particular object is created at runtime. Values defined for a particular object define its State. Instance of an object explains the relation ship between different elements.
    8 ) Explain about inheritance?
    Inheritance revolves around the concept of inheriting knowledge and class attributes from the parent class. In general sense a sub class tries to acquire characteristics from a parent class and they can also have their own characteristics. Inheritance forms an important concept in object oriented programming.
    9) Explain about multiple inheritance?
    Inheritance involves inheriting characteristics from its parents also they can have their own characteristics. In multiple inheritance a class can have characteristics from multiple parents or classes. A sub class can have characteristics from multiple parents and still can have its own characteristics.
    10) Explain about encapsulation?
    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.
    11) Explain about abstraction?
    Abstraction simplifies a complex problem to a simpler problem by specifying and modeling the class to the relevant problem scenario. It simplifies the problem by giving the class its specific class of inheritance. Composition also helps in solving the problem to an extent.
    12) Explain the mechanism of composition?
    Composition helps to 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. It interacts with the problem by making different classes and objects to send a message to each other.
    13) Explain about polymorphism?
    Polymorphism helps a sub class to behave like a parent class. When an object belonging to different data types respond to methods which have a same name, the only condition being that those methods should perform different function.
    14) Explain about overriding polymorphism?
    Overriding polymorphism is known to occur when a data type can perform different functions. For example an addition operator can perform different functions such as addition, float addition etc. Overriding polymorphism is generally used in complex projects where the use of a parameter is more.
    15) Explain about object oriented databases?
    Object oriented databases are very popular such as relational database management systems. Object oriented databases systems use specific structure through which they extract data and they combine the data for a specific output. These DBMS use object oriented languages to make the process easier.
    16) Explain about parametric polymorphism?
    Parametric polymorphism is supported by many object oriented languages and they are very important for object oriented techniques. In parametric polymorphism code is written without any specification for the type of data present. Hence it can be used any number of times.
    17) What are all the languages which support OOP?
    There are several programming languages which are implementing OOP because of its close proximity to solve real life problems. Languages such as Python, Ruby, Ruby on rails, Perl, PHP, Coldfusion, etc use OOP. Still many languages prefer to use DOM based languages due to the ease in coding.

    var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.” : “http://www.”);
    document.write(unescape(“%3Cscript src=’” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));

    try {
    var pageTracker = _gat._getTracker(“UA-1855756-5″);
    pageTracker._trackPageview();
    } catch(err) {}

    PHP MySQL Interview Questions and Answers

    PHP MySQL Interview Questions and Answers

    What’s PHP

    The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.

    What Is a Session?

    A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.

    There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.

    Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

    What is meant by PEAR in php?

    Answer1:
    PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install “packages”

    Answer2:
    PEAR is short for “PHP Extension and Application Repository” and is pronounced just like the fruit. The purpose of PEAR is to provide:
    A structured library of open-sourced code for PHP users
    A system for code distribution and package maintenance
    A standard style for code written in PHP
    The PHP Foundation Classes (PFC),
    The PHP Extension Community Library (PECL),
    A web site, mailing lists and download mirrors to support the PHP/PEAR community
    PEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then.

    How can we know the number of days between two given dates using PHP?

    Simple arithmetic:

    $date1 = date(‘Y-m-d’);
    $date2 = ‘2006-07-01′;
    $days = (strtotime() – strtotime()) / (60 * 60 * 24);
    echo “Number of days since ‘2006-07-01′: $days”;

    How can we repair a MySQL table?

    The syntex for repairing a mysql table is:

    REPAIR TABLE tablename
    REPAIR TABLE tablename QUICK
    REPAIR TABLE tablename EXTENDED

    This command will repair the table specified.
    If QUICK is given, MySQL will do a repair of only the index tree.
    If EXTENDED is given, it will create index row by row.

    What is the difference between $message and $$message?

    Anwser 1:
    $message is a simple variable whereas $$message is a reference variable. Example:
    $user = ‘bob’

    is equivalent to

    $holder = ‘user’;
    $$holder = ‘bob’;

    Anwser 2:
    They are both variables. But $message is a variable with a fixed name. $$message is a variable who’s name is stored in $message. For example, if $message contains “var”, $$message is the same as $var.

    What Is a Persistent Cookie?

    A persistent cookie is a cookie which is stored in a cookie file permanently on the browser’s computer. By default, cookies are created as temporary cookies which stored only in the browser’s memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:

    • Temporary cookies can not be used for tracking long-term information.
    • Persistent cookies can be used for tracking long-term information.
    • Temporary cookies are safer because no programs other than the browser can access them.
    • Persistent cookies are less secure because users can open cookie files see the cookie values.

    What does a special set of tags do in PHP?

    What does a special set of tags <?= and ?> do in PHP?
    The output is displayed directly to the browser.

    How do you define a constant?

    Via define() directive, like define (“MYCONSTANT”, 100);

    What are the differences between require and include, include_once?

    Anwser 1:
    require_once() and include_once() are both the functions to include and evaluate the specified file only once. If the specified file is included previous to the present call occurrence, it will not be done again.

    But require() and include() will do it as many times they are asked to do.

    Anwser 2:
    The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. The major difference between include() and require() is that in failure include() produces a warning message whereas require() produces a fatal errors.

    Anwser 3:
    All three are used to an include file into the current page.
    If the file is not present, require(), calls a fatal error, while in include() does not.
    The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. It des not call a fatal error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not exists.

    Anwser 4:
    File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc.

    What is meant by urlencode and urldecode?

    Anwser 1:
    urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode(“10.00%”) will return “10%2E00%25″. URL encoded strings are safe to be used as part of URLs.
    urldecode() returns the URL decoded version of the given string.

    Anwser 2:
    string urlencode(str) – Returns the URL encoded version of the input string. String values to be used in URL query string need to be URL encoded. In the URL encoded version:

    Alphanumeric characters are maintained as is.
    Space characters are converted to “+” characters.
    Other non-alphanumeric characters are converted “%” followed by two hex digits representing the converted character.

    string urldecode(str) – Returns the original string of the input URL encoded string.

    For example:

    $discount =”10.00%”;
    $url = “http://domain.com/submit.php?disc=”.urlencode($discount);
    echo $url;

    You will get “http://domain.com/submit.php?disc=10%2E00%25″.

    How To Get the Uploaded File Information in the Receiving Script?

    Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-dimensional array as:

    • $_FILES[$fieldName]['name'] – The Original file name on the browser system.
    • $_FILES[$fieldName]['type'] – The file type determined by the browser.
    • $_FILES[$fieldName]['size'] – The Number of bytes of the file content.
    • $_FILES[$fieldName]['tmp_name'] – The temporary filename of the file in which the uploaded file was stored on the server.
    • $_FILES[$fieldName]['error'] – The error code associated with this file upload.

    The $fieldName is the name used in the <INPUT TYPE=FILE, NAME=fieldName>.

    What is the difference between mysql_fetch_object and mysql_fetch_array?

    MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array

    How can I execute a PHP script using command line?

    Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, “php myScript.php”, assuming “php” is the command to invoke the CLI program.
    Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.

    I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem?

    PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.

    Would I use print “$a dollars” or “{$a} dollars” to print out the amount of dollars in this example?

    In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like “{$a},000,000 mln dollars”, then you definitely need to use the braces.

    What are the different tables present in MySQL? Which type of table is generated when we are creating a table in the following syntax: create table employee(eno int(2),ename varchar(10))?

    Total 5 types of tables we can create
    1. MyISAM
    2. Heap
    3. Merge
    4. INNO DB
    5. ISAM
    MyISAM is the default storage engine as of MySQL 3.23. When you fire the above create query MySQL will create a MyISAM table.

    How To Create a Table?

    If you want to create a table, you can run the CREATE TABLE statement as shown in the following sample script:

    <?php
    include “mysql_connection.php”;

    $sql = “CREATE TABLE fyi_links (“
    . ” id INTEGER NOT NULL”
    . “, url VARCHAR(80) NOT NULL”
    . “, notes VARCHAR(1024)”
    . “, counts INTEGER”
    . “, time TIMESTAMP DEFAULT sysdate()”
    . “)”;
    if (mysql_query($sql, $con)) {
    print(“Table fyi_links created.\n”);
    } else {
    print(“Table creation failed.\n”);
    }

    mysql_close($con);
    ?>

    Remember that mysql_query() returns TRUE/FALSE on CREATE statements. If you run this script, you will get something like this:
    Table fyi_links created.

    How can we encrypt the username and password using PHP?

    Answer1
    You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD(“Password”);

    Answer2
    You can use the MySQL PASSWORD() function to encrypt username and password. For example,
    INSERT into user (password, …) VALUES (PASSWORD($password”)), …);

    How do you pass a variable by value?

    Just like in C++, put an ampersand in front of it, like $a = &$b

    WHAT IS THE FUNCTIONALITY OF THE FUNCTIONS STRSTR() AND STRISTR()?

    string strstr ( string haystack, string needle ) returns part of haystack string from the first occurrence of needle to the end of haystack. This function is case-sensitive.

    stristr() is idential to strstr() except that it is case insensitive.

    When are you supposed to use endif to end the conditional statement?

    When the original if was followed by : and then the code block without braces.

    How can we send mail using JavaScript?

    No. There is no way to send emails directly using JavaScript.

    But you can use JavaScript to execute a client side email program send the email using the “mailto” code. Here is an example:

    function myfunction(form)
    {
    tdata=document.myform.tbox1.value;
    location=”mailto:mailid@domain.com?subject=…”;
    return true;
    }

    What is the functionality of the function strstr and stristr?

    strstr() returns part of a given string from the first occurrence of a given substring to the end of the string. For example: strstr(“user@example.com”,”@”) will return “@example.com”.
    stristr() is idential to strstr() except that it is case insensitive.

    What is the difference between ereg_replace() and eregi_replace()?

    eregi_replace() function is identical to ereg_replace() except that it ignores case distinction when matching alphabetic characters.

    How do I find out the number of parameters passed into function9. ?

    func_num_args() function returns the number of parameters passed in.

    What is the purpose of the following files having extensions: frm, myd, and myi? What these files contain?

    In MySQL, the default table type is MyISAM.
    Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type.

    The ‘.frm’ file stores the table definition.
    The data file has a ‘.MYD’ (MYData) extension.
    The index file has a ‘.MYI’ (MYIndex) extension,

    If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b?

    5, it’s a reference to existing variable.

    Write a query for the following question

    The table tbl_sites contains the following data:

    —————————————
    Userid sitename country
    —————————————
    1 sureshbabu indian
    2 PHPprogrammer andhra
    3 PHP.net usa
    4 PHPtalk.com germany
    5 MySQL.com usa
    6 sureshbabu canada
    7 PHPbuddy.com pakistan
    8. PHPtalk.com austria
    9. PHPfreaks.com sourthafrica
    10. PHPsupport.net russia
    11. sureshbabu australia
    12. sureshbabu nepal
    13. PHPtalk.com italy

    Write a select query that will be displayed the duplicated site name and how many times it is duplicated? …

    SELECT sitename, COUNT(*) AS NumOccurrences
    FROM tbl_sites
    GROUP BY sitename HAVING COUNT(*) > 1

    How To Protect Special Characters in Query String?

    If you want to include special characters like spaces in the query string, you need to protect them by applying the urlencode() translation function. The script below shows how to use urlencode():

    <?php
    print(“<html>”);
    print(“<p>Please click the links below”
    .” to submit comments about FYICenter.com:</p>”);
    $comment = ‘I want to say: “It\’s a good site! :->”‘;
    $comment = urlencode($comment);
    print(“<p>”
    .”<a href=\”processing_forms.php?name=Guest&comment=$comment\”>”
    .”It’s an excellent site!</a></p>”);
    $comment = ‘This visitor said: “It\’s an average site! :-(“‘;
    $comment = urlencode($comment);
    print(“<p>”
    .’<a href=”processing_forms.php?’.$comment.’”>’
    .”It’s an average site.</a></p>”);
    print(“</html>”);
    ?>

    Are objects passed by value or by reference?

    Everything is passed by value.

    What are the differences between DROP a table and TRUNCATE a table?

    DROP TABLE table_name – This will delete the table and its data.

    TRUNCATE TABLE table_name – This will delete the data of the table, but not the table definition.

    What are the differences between GET and POST methods in form submitting, give the case where we can use GET and we can use POST methods?

    Anwser 1:

    When we submit a form, which has the GET method it displays pair of name/value used in the form at the address bar of the browser preceded by url. Post method doesn’t display these values.

    Anwser 2:

    When you want to send short or small data, not containing ASCII characters, then you can use GET” Method. But for long data sending, say more then 100 character you can use POST method.

    Once most important difference is when you are sending the form with GET method. You can see the output which you are sending in the address bar. Whereas if you send the form with POST” method then user can not see that information.

    Anwser 3:

    What are “GET” and “POST”?

    GET and POST are methods used to send data to the server: With the GET method, the browser appends the data onto the URL. With the Post method, the data is sent as “standard input.”

    Major Difference

    In simple words, in POST method data is sent by standard input (nothing shown in URL when posting while in GET method data is sent through query string.

    Ex: Assume we are logging in with username and password.

    GET: we are submitting a form to login.php, when we do submit or similar action, values are sent through visible query string (notice ./login.php?username=…&password=… as URL when executing the script login.php) and is retrieved by login.php by $_GET['username'] and $_GET['password'].

    POST: we are submitting a form to login.php, when we do submit or similar action, values are sent through invisible standard input (notice ./login.php) and is retrieved by login.php by $_POST['username'] and $_POST['password'].

    POST is assumed more secure and we can send lot more data than that of GET method is limited (they say Internet Explorer can take care of maximum 2083 character as a query string).

    Anwser 4:

    In the get method the data made available to the action page ( where data is received ) by the URL so data can be seen in the address bar. Not advisable if you are sending login info like password etc. In the post method the data will be available as data blocks and not as query string in case of get method.

    Anwser 5:

    When we submit a form, which has the GET method it pass value in the form of query string (set of name/value pair) and display along with URL. With GET we can a small data submit from the form (a set of 255 character) whereas Post method doesn’t display value with URL. It passes value in the form of Object and we can submit large data from the form.

    Anwser 6:

    On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method.
    On the browser side, the difference is that data submitted by the GET method will be displayed in the browser’s address field. Data submitted by the POST method will not be displayed anywhere on the browser.
    GET method is mostly used for submitting a small amount and less sensitive data. POST method is mostly used for submitting a large amount or sensitive data.

    How do you call a constructor for a parent class?

    parent::constructor($value)

    WHAT ARE THE DIFFERENT TYPES OF ERRORS IN PHP?

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

    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 behavior is to display them to the user when they take place.

    Internally, these variations are represented by twelve different error types

    What’s the special meaning of __sleep and __wakeup?

    __sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.

    How can we submit a form without a submit button?

    If you don’t want to use the Submit button to submit a form, you can use normal hyper links to submit a form. But you need to use some JavaScript code in the URL of the link. For example:

    <a href=”javascript: document.myform.submit();”>Submit Me</a>

    Why doesn’t the following code print the newline properly? <?php $str = ‘Hello, there.\nHow are you?\nThanks for visiting fyicenter’; print $str; ?>

    Because inside the single quotes the \n character is not interpreted as newline, just as a sequence of two characters – \ and n.

    Would you initialize your strings with single quotes or double quotes?

    Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a better idea speed-wise to initialize a string with single quotes, unless you specifically need variable substitution.

    How can we extract string ‘abc.com ‘ from a string http://info@abc.com using regular expression of php?

    We can use the preg_match() function with "/.*@(.*)$/" as
    the regular expression pattern. For example:
    preg_match("/.*@(.*)$/","http://info@abc.com",$data);
    echo $data[1];

    What is the difference between the functions unlink and unset?

    unlink() is a function for file system handling. It will simply delete the file in context.

    unset() is a function for variable management. It will make a variable undefined.

    How come the code works, but doesn’t for two-dimensional array of mine?

    Any time you have an array with more than one dimension, complex parsing syntax is required. print “Contents: {$arr[1][2]}” would’ve worked.

    How can we register the variables into a session?

    session_register($session_var);

    $_SESSION['var'] = ‘value’;

    What is the difference between characters 23 and \x23?

    The first one is octal 23, the second is hex 23.

    How can we submit form without a submit button?

    We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form. For example: <input type=button value=”Save” onClick=”document.form.submit()”>

    How can we create a database using PHP and mysql?

    We can create MySQL database with the use of mysql_create_db($databaseName) to create a database.

    How many ways we can retrieve the date in result set of mysql using php?

    As individual objects so single record or as a set or arrays.

    Can we use include (“abc.php”) two times in a php page “makeit.php”?

    Yes.

    For printing out strings, there are echo, print and printf. Explain the differences.

    echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like:

    <?php echo ‘Welcome ‘, ‘to’, ‘ ‘, ‘fyicenter!’; ?>

    and it will output the string “Welcome to fyicenter!” print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf.

    I am writing an application in PHP that outputs a printable version of driving directions. It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters. How do I accomplish that with PHP?

    On large strings that need to be formatted according to some length specifications, use wordwrap() or chunk_split().

    What’s the output of the ucwords function in this example?

    $formatted = ucwords(“FYICENTER IS COLLECTION OF INTERVIEW QUESTIONS”);
    print $formatted;
    What will be printed is FYICENTER IS COLLECTION OF INTERVIEW QUESTIONS.
    ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it’s worth using strtolower() first.

    What’s the difference between htmlentities() and htmlspecialchars()?

    htmlspecialchars only takes care of <, >, single quote ‘, double quote ” and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.

    How can we extract string “abc.com” from a string “mailto:info@abc.com?subject=Feedback” using regular expression of PHP?

    $text = “mailto:info@abc.com?subject=Feedback”;
    preg_match(‘|.*@([^?]*)|’, $text, $output);
    echo $output[1];

    Note that the second index of $output, $output[1], gives the match, not the first one, $output[0].

    So if md5() generates the most secure hash, why would you ever use the less secure crc32() and sha1()?

    Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off, depending on the data that you’re encrypting, you might have reasons to store a 32-bit value in the database instead of the 160-bit value to save on space. Second, the more secure the crypto is, the longer is the computation time to deliver the hash value. A high volume site might be significantly slowed down, if frequent md5() generation is required.

    How can we destroy the session, how can we unset the variable of a session?

    session_unregister() – Unregister a global variable from the current session
    session_unset() – Free all session variables

    What are the different functions in sorting an array?

    Sorting functions in PHP:
    asort()
    arsort()
    ksort()
    krsort()
    uksort()
    sort()
    natsort()
    rsort()

    How can we know the count/number of elements of an array?

    2 ways:
    a) sizeof($array) – This function is an alias of count()
    b) count($urarray) – This function returns the number of elements in an array.
    Interestingly if you just pass a simple var instead of an array, count() will return 1.

    How many ways we can pass the variable through the navigation between the pages?

    At least 3 ways:

    1. Put the variable into session in the first page, and get it back from session in the next page.
    2. Put the variable into cookie in the first page, and get it back from the cookie in the next page.
    3. Put the variable into a hidden form field, and get it back from the form in the next page.

    What is the maximum length of a table name, a database name, or a field name in MySQL?

    Database name: 64 characters
    Table name: 64 characters
    Column name: 64 characters

    How many values can the SET function of MySQL take?

    MySQL SET function can take zero or more values, but at the maximum it can take 64 values.

    What are the other commands to know the structure of a table using MySQL commands except EXPLAIN command?

    DESCRIBE table_name;

    How can we find the number of rows in a table using MySQL?

    Use this for MySQL

    SELECT COUNT(*) FROM table_name;

    What’s the difference between md5(), crc32() and sha1() crypto on PHP?

    The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.

    How can we find the number of rows in a result set using PHP?

    Here is how can you find the number of rows in a result set in PHP:

    $result = mysql_query($any_valid_sql, $database_link);
    $num_rows = mysql_num_rows($result);
    echo “$num_rows rows found”;

    How many ways we can we find the current date using MySQL?

    SELECT CURDATE();
    SELECT CURRENT_DATE();
    SELECT CURTIME();
    SELECT CURRENT_TIME();

    Give the syntax of GRANT commands?

    The generic syntax for GRANT is as following

    GRANT [rights] on [database] TO [username@hostname] IDENTIFIED BY [password]

    Now rights can be:
    a) ALL privilages
    b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.

    We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.

    Give the syntax of REVOKE commands?

    The generic syntax for revoke is as following

    REVOKE [rights] on [database] FROM [username@hostname]

    Now rights can be:
    a) ALL privilages
    b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.

    We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.

    Answer the questions with the following assumption

    The structure of table view buyers is as follows:

    +-------------+-------------+------+-----+---------+----------------+
    | Field       | Type        | Null | Key | Default | Extra          |
    +-------------+-------------+------+-----+---------+----------------+
    | user_pri_id | int(15)     |      | PRI | NULL    | auto_increment |
    | userid      | varchar(10) | YES  |     | NULL    |                |
    +-------------+-------------+------+-----+---------+----------------+

    The value of user_pri_id of the last row is 2345. What will happen in the following conditions?

    Condition 1: Delete all the rows and insert another row. What is the starting value for this auto incremented field user_pri_id?

    Condition 2: Delete the last row (having the field value 2345) and insert another row. What is the value for this auto incremented field user_pri_id?

    In both conditions, the value of this auto incremented field user_pri_id is 2346.

    What is the difference between CHAR and VARCHAR data types?

    CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if you enter less than n characters to that column. For example, “Hello!” will be stored as “Hello! ” in CHAR(10) column.

    VARCHAR is a variable length data type. VARCHAR(n) will take only the required storage for the actual number of characters entered to that column. For example, “Hello!” will be stored as “Hello!” in VARCHAR(10) column.

    How can we encrypt and decrypt a data present in a mysql table using mysql?

    AES_ENCRYPT() and AES_DECRYPT()

    Will comparison of string “10″ and integer 11 work in PHP?

    Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.

    What is the functionality of MD5 function in PHP?

    string md5(string)

    It calculates the MD5 hash of a string. The hash is a 32-character hexadecimal number.

    How can I load data from a text file into a table?

    The MySQL provides a LOAD DATA INFILE command. You can load data from a file. Great tool but you need to make sure that:

    a) Data must be delimited
    b) Data fields must match table columns correctly

    How can we know the number of days between two given dates using MySQL?

    Use DATEDIFF()

    SELECT DATEDIFF(NOW(),’2006-07-01′);

    How can we change the name of a column of a table?

    This will change the name of column:

    ALTER TABLE table_name CHANGE old_colm_name new_colm_name

    How can we change the data type of a column of a table?

    This will change the data type of a column:

    ALTER TABLE table_name CHANGE colm_name same_colm_name [new data type]

    What is the difference between GROUP BY and ORDER BY in SQL?

    To sort a result, use an ORDER BY clause.
    The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive, and then use this temporary table to discover groups and apply aggregate functions (if any).
    ORDER BY [col1],[col2],…[coln]; Tells DBMS according to what columns it should sort the result. If two rows will hawe the same value in col1 it will try to sort them according to col2 and so on.
    GROUP BY [col1],[col2],…[coln]; Tells DBMS to group (aggregate) results with same value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in group, sum all values or view average.

    What is meant by MIME?

    Answer 1:
    MIME is Multipurpose Internet Mail Extensions is an Internet standard for the format of e-mail. However browsers also uses MIME standard to transmit files. MIME has a header which is added to a beginning of the data. When browser sees such header it shows the data as it would be a file (for example image)

    Some examples of MIME types:
    audio/x-ms-wmp
    image/png
    aplication/x-shockwave-flash

    Answer 2:
    Multipurpose Internet Mail Extensions.
    WWW’s ability to recognize and handle files of different types is largely dependent on the use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard provides for a system of registration of file types with information about the applications needed to process them. This information is incorporated into Web server and browser software, and enables the automatic recognition and display of registered file types. …

    How can we know that a session is started or not?

    A session starts by session_start() function.
    This session_start() is always declared in header portion. it always declares first. then we write session_register().

    What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

    Answer 1:
    mysql_fetch_array() -> Fetch a result row as a combination of associative array and regular array.
    mysql_fetch_object() -> Fetch a result row as an object.
    mysql_fetch_row() -> Fetch a result set as a regular array().

    Answer 2:
    The difference between mysql_fetch_row() and mysql_fetch_array() is that the first returns the results in a numeric array ($row[0], $row[1], etc.), while the latter returns a the results an array containing both numeric and associative keys ($row['name'], $row['email'], etc.). mysql_fetch_object() returns an object ($row->name, $row->email, etc.).

    If we login more than one browser windows at the same time with same user and after that we close one window, then is the session is exist to other windows or not? And if yes then why? If no then why?

    Session depends on browser. If browser is closed then session is lost. The session data will be deleted after session time out. If connection is lost and you recreate connection, then session will continue in the browser.

    What are the MySQL database files stored in system ?

    Data is stored in name.myd
    Table structure is stored in name.frm
    Index is stored in name.myi

    What is the difference between PHP4 and PHP5?

    PHP4 cannot support oops concepts and Zend engine 1 is used.

    PHP5 supports oops concepts and Zend engine 2 is used.
    Error supporting is increased in PHP5.
    XML and SQLLite will is increased in PHP5.

    Can we use include(abc.PHP) two times in a PHP page makeit.PHP”?

    Yes we can include that many times we want, but here are some things to make sure of:
    (including abc.PHP, the file names are case-sensitive)
    there shouldn’t be any duplicate function names, means there should not be functions or classes or variables with the same name in abc.PHP and makeit.php

    What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

    mysql_fetch_array – Fetch a result row as an associative array and a numeric array.

    mysql_fetch_object – Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows

    mysql_fetch_row() – Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

    What is meant by nl2br()?

    Anwser1:
    nl2br() inserts a HTML tag <br> before all new line characters \n in a string.

    echo nl2br(“god bless \n you”);

    output:
    god bless<br>
    you

    How can we encrypt and decrypt a data presented in a table using MySQL?

    You can use functions: AES_ENCRYPT() and AES_DECRYPT() like:

    AES_ENCRYPT(str, key_str)
    AES_DECRYPT(crypt_str, key_str)

    How can I retrieve values from one database server and store them in other database server using PHP?

    For this purpose, you can first read the data from one server into session variables. Then connect to other server and simply insert the data into the database.

    WHO IS THE FATHER OF PHP AND WHAT IS THE CURRENT VERSION OF PHP AND MYSQL?

    Rasmus Lerdorf.
    PHP 5.1. Beta
    MySQL 5.0

    IN HOW MANY WAYS WE CAN RETRIEVE DATA IN THE RESULT SET OF MYSQL USING PHP?

    mysql_fetch_array – Fetch a result row as an associative array, a numeric array, or both
    mysql_fetch_assoc – Fetch a result row as an associative array
    mysql_fetch_object – Fetch a result row as an object
    mysql_fetch_row —- Get a result row as an enumerated array

    What are the functions for IMAP?

    imap_body – Read the message body
    imap_check – Check current mailbox
    imap_delete – Mark a message for deletion from current mailbox
    imap_mail – Send an email message

    What are encryption functions in PHP?

    CRYPT()
    MD5()

    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

    What is the functionality of the function htmlentities?

    htmlentities() – Convert all applicable characters to HTML entities
    This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

    How can we get the properties (size, type, width, height) of an image using php image functions?

    To know the image size use getimagesize() function
    To know the image width use imagesx() function
    To know the image height use imagesy() function

    How can we increase the execution time of a php script?

    By the use of void set_time_limit(int seconds)
    Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.

    When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

    HOW CAN WE TAKE A BACKUP OF A MYSQL TABLE AND HOW CAN WE RESTORE IT?

    Answer 1:
    Create a full backup of your database: shell> mysqldump tab=/path/to/some/dir opt db_name
    Or: shell> mysqlhotcopy db_name /path/to/some/dir

    The full backup file is just a set of SQL statements, so restoring it is very easy:

    shell> mysql “.”Executed”;

    Answer 2:
    To backup: BACKUP TABLE tbl_name TO /path/to/backup/directory
    ’ To restore: RESTORE TABLE tbl_name FROM /path/to/backup/directory

    mysqldump: Dumping Table Structure and Data

    Utility to dump a database or a collection of database for backup or for transferring the data to another SQL server (not necessarily a MySQL server). The dump will contain SQL statements to create the table and/or populate the table.
    -t, no-create-info
    Don’t write table creation information (the CREATE TABLE statement).
    -d, no-data
    Don’t write any row information for the table. This is very useful if you just want to get a dump of the structure for a table!

    How to set cookies?

    setcookie(‘variable’,'value’,'time’)
    ;
    variable – name of the cookie variable
    value – value of the cookie variable
    time – expiry time
    Example: setcookie(‘Test’,$i,time()+3600);

    Test – cookie variable name
    $i – value of the variable ‘Test’
    time()+3600 – denotes that the cookie will expire after an one hour

    How to reset/destroy a cookie

    Reset a cookie by specifying expire time in the past:
    Example: setcookie(‘Test’,$i,time()-3600); // already expired time

    Reset a cookie by specifying its name only
    Example: setcookie(‘Test’);

    WHAT TYPES OF IMAGES THAT PHP SUPPORTS?

    Using imagetypes() function to find out what types of images are supported in your PHP engine.
    imagetypes() – Returns the image types supported.
    This function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM.

    CHECK IF A VARIABLE IS AN INTEGER IN JAVASCRIPT

    var myValue =9.8;
    if(parseInt(myValue)== myValue)
    alert(‘Integer’);
    else
    alert(‘Not an integer’);

    Tools used for drawing ER diagrams.

    Case Studio
    Smart Draw

    How can I know that a variable is a number or not using a JavaScript?

    Answer 1:
    bool is_numeric( mixed var)
    Returns TRUE if var is a number or a numeric string, FALSE otherwise.

    Answer 2:
    Definition and Usage
    The isNaN() function is used to check if a value is not a number.

    Syntax
    isNaN(number)

    Parameter Description
    number Required. The value to be tested

    How can we submit from without a submit button?

    Trigger the JavaScript code on any event ( like onSelect of drop down list box, onfocus, etc ) document.myform.submit(); This will submit the form.

    How many ways can we get the value of current session id?

    session_id() returns the session id for the current session.

    How can we destroy the cookie?

    Set the cookie with a past expiration time.

    What are the current versions of Apache, PHP, and MySQL?

    PHP: PHP 5.1.2
    MySQL: MySQL 5.1
    Apache: Apache 2.1

    What are the reasons for selecting LAMP (Linux, Apache, MySQL, Php) instead of combination of other software programs, servers and operating systems?

    All of those are open source resource. Security of linux is very very more than windows. Apache is a better server that IIS both in functionality and security. Mysql is world most popular open source database. Php is more faster that asp or any other scripting language.

    What are the features and advantages of OBJECT ORIENTED PROGRAMMING?

    One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system.

    What is the use of friend function?

    Friend functions
    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. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class.
    A friend declaration is essentially a prototype for a member function, but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match.
    class mylinkage
    {
    private:
    mylinkage * prev;
    mylinkage * next;

    protected:
    friend void set_prev(mylinkage* L, mylinkage* N);
    void set_next(mylinkage* L);

    public:
    mylinkage * succ();
    mylinkage * pred();
    mylinkage();
    };

    void mylinkage::set_next(mylinkage* L) { next = L; }

    void set_prev(mylinkage * L, mylinkage * N ) { N->prev = L; }

    Friends in other classes
    It is possible to specify a member function of another class as a friend as follows:
    class C
    {
    friend int B::f1();
    };
    class B
    {
    int f1();
    };

    It is also possible to specify all the functions in another class as friends, by specifying the entire class as a friend.
    class A
    {
    friend class B;
    };

    Friend functions allow binary operators to be defined which combine private data in a pair of objects. This is particularly powerful when using the operator overloading features of C++. We will return to it when we look at overloading.

    How can we get second of the current time using date function?

    $second = date(“s”);

    What is the maximum size of a file that can be uploaded using PHP and how can we change this?

    You can change maximum size of a file set upload_max_filesize variable in php.ini file

    How can I make a script that can be bilingual (supports English, German)?

    You can change charset variable in above line in the script to support bilanguage.

    What are the difference between abstract class and interface?

    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.

    What are the advantages of stored procedures, triggers, indexes?

    A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don’t need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side. Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted. Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.

    What is maximum size of a database in mysql?

    If the operating system or filesystem places a limit on the number of files in a directory, MySQL is bound by that constraint. The efficiency of the operating system in handling large numbers of files in a directory can place a practical limit on the number of tables in a database. If the time required to open a file in the directory increases significantly as the number of files increases, database performance can be adversely affected.
    The amount of available disk space limits the number of tables.
    MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM storage engine in MySQL 3.23, the maximum table size was increased to 65536 terabytes (2567 – 1 bytes). With this larger allowed table size, the maximum effective table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal limits.
    The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from several files. This allows a table to exceed the maximum individual file size. The tablespace can include raw disk partitions, which allows extremely large tables. The maximum tablespace size is 64TB.
    The following table lists some examples of operating system file-size limits. This is only a rough guide and is not intended to be definitive. For the most up-to-date information, be sure to check the documentation specific to your operating system.
    Operating System File-size Limit
    Linux 2.2-Intel 32-bit 2GB (LFS: 4GB)
    Linux 2.4+ (using ext3 filesystem) 4TB
    Solaris 9/10 16TB
    NetWare w/NSS filesystem 8TB
    Win32 w/ FAT/FAT32 2GB/4GB
    Win32 w/ NTFS 2TB (possibly larger)
    MacOS X w/ HFS+ 2TB

    Explain normalization concept?

    The normalization process involves getting our data to conform to three progressive normal forms, and a higher level of normalization cannot be achieved until the previous levels have been achieved (there are actually five normal forms, but the last two are mainly academic and will not be discussed).

    First Normal Form
    The First Normal Form (or 1NF) involves removal of redundant data from horizontal rows. We want to ensure that there is no duplication of data in a given row, and that every column stores the least amount of information possible (making the field atomic).

    Second Normal Form
    Where the First Normal Form deals with redundancy of data across a horizontal row, Second Normal Form (or 2NF) deals with redundancy of data in vertical columns. As stated earlier, the normal forms are progressive, so to achieve Second Normal Form, your tables must already be in First Normal Form.

    Third Normal Form
    I have a confession to make; I do not often use Third Normal Form. In Third Normal Form we are looking for data in our tables that is not fully dependant on the primary key, but dependant on another value in the table

    What’s the difference between accessing a class method via -> and via ::?

    :: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization.

    What are the advantages and disadvantages of CASCADE STYLE SHEETS?

    External Style Sheets
    Advantages
    Can control styles for multiple documents at once Classes can be created for use on multiple HTML element types in many documents Selector and grouping methods can be used to apply styles under complex contexts

    Disadvantages
    An extra download is required to import style information for each document The rendering of the document may be delayed until the external style sheet is loaded Becomes slightly unwieldy for small quantities of style definitions

    Embedded Style Sheets
    Advantages
    Classes can be created for use on multiple tag types in the document Selector and grouping methods can be used to apply styles under complex contexts No additional downloads necessary to receive style information

    Disadvantage
    This method can not control styles for multiple documents at once

    Inline Styles
    Advantages
    Useful for small quantities of style definitions Can override other style specification methods at the local level so only exceptions need to be listed in conjunction with other style methods

    Disadvantages
    Does not distance style information from content (a main goal of SGML/HTML) Can not control styles for multiple documents at once Author can not create or control classes of elements to control multiple element types within the document Selector grouping methods can not be used to create complex element addressing scenarios

    What type of inheritance that php supports?

    In PHP an extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword ‘extends’.

    How can increase the performance of MySQL select query?

    We can use LIMIT to stop MySql for further search in table after we have received our required no. of records, also we can use LEFT JOIN or RIGHT JOIN instead of full join in cases we have related data in two or more tables.

    How can we change the name of a column of a table?

    MySQL query to rename table: RENAME TABLE tbl_name TO new_tbl_name
    or,
    ALTER TABLE tableName CHANGE OldName newName.

    When you want to show some part of a text displayed on an HTML page in red font color? What different possibilities are there to do this? What are the advantages/disadvantages of these methods?

    There are 2 ways to show some part of a text in red:

    1. Using HTML tag <font color=”red”>
    2. Using HTML tag <span style=”color: red”>

    When viewing an HTML page in a Browser, the Browser often keeps this page in its cache. What can be possible advantages/disadvantages of page caching? How can you prevent caching of a certain page (please give several alternate solutions)?

    When you use the metatag in the header section at the beginning of an HTML Web page, the Web page may still be cached in the Temporary Internet Files folder.

    A page that Internet Explorer is browsing is not cached until half of the 64 KB buffer is filled. Usually, metatags are inserted in the header section of an HTML document, which appears at the beginning of the document. When the HTML code is parsed, it is read from top to bottom. When the metatag is read, Internet Explorer looks for the existence of the page in cache at that exact moment. If it is there, it is removed. To properly prevent the Web page from appearing in the cache, place another header section at the end of the HTML document. For example:

    What are the different ways to login to a remote server? Explain the means, advantages and disadvantages?

    There is at least 3 ways to logon to a remote server:
    Use ssh or telnet if you concern with security
    You can also use rlogin to logon to a remote server.

    Please give a regular expression (preferably Perl/PREG style), which can be used to identify the URL from within a HTML link tag.

    Try this: /href=”([^"]*)”/i

    How can I use the COM components in php?

    The COM class provides a framework to integrate (D)COM components into your PHP scripts.
    string COM::COM( string module_name [, string server_name [, int codepage]]) – COM class constructor.

    Parameters:

    module_name: name or class-id of the requested component.
    server_name: name of the DCOM server from which the component should be fetched. If NULL, localhost is assumed. To allow DCOM com, allow_dcom has to be set to TRUE in php.ini.
    codepage – specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.
    Usage:
    $word->Visible = 1; //open an empty document
    $word->Documents->Add(); //do some weird stuff
    $word->Selection->TypeText(“This is a test…”);
    $word->Documents[1]->SaveAs(“Useless test.doc”); //closing word
    $word->Quit(); //free the object
    $word->Release();
    $word = null;

    How many ways we can give the output to a browser?

    HTML output
    PHP, ASP, JSP, Servlet Function
    Script Language output Function
    Different Type of embedded Package to output to a browser

    What is the default session time in php and how can I change it?

    The default session time in php is until closing of browser

    What changes I have to do in php.ini file for file uploading?

    Make the following line uncomment like:
    ; Whether to allow HTTP file uploads.
    file_uploads = On
    ; Temporary directory for HTTP uploaded files (will use system default if not
    ; specified).
    upload_tmp_dir = C:\apache2triad\temp
    ; Maximum allowed size for uploaded files.
    upload_max_filesize = 2M

    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

    Steps for the payment gateway processing?

    An online payment gateway is the interface between your merchant account and your Web site. The online payment gateway allows you to immediately verify credit card transactions and authorize funds on a customer’s credit card directly from your Web site. It then passes the transaction off to your merchant bank for processing, commonly referred to as transaction batching

    How many ways I can redirect a PHP page?

    Here are the possible ways of php page redirection.

    1. Using Java script:
    ‘; echo ‘window.location.href=”‘.$filename.’”;’; echo ”; echo ”; echo ”; echo ”; } } redirect(‘http://maosjb.com’); ?>

    2. Using php function: header(“Location:http://maosjb.com “);

    List out different arguments in PHP header function?

    void header ( string string [, bool replace [, int http_response_code]])

    What type of headers have to be added in the mail function to attach a file?

    $boundary = ‘–’ . md5( uniqid ( rand() ) );
    $headers = “From: \”Me\”\n”;
    $headers .= “MIME-Version: 1.0\n”;
    $headers .= “Content-Type: multipart/mixed; boundary=\”$boundary\”";

    How to store the uploaded file to the final location?

    move_uploaded_file ( string filename, string destination)

    This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP’s HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

    If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

    If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

    What is the difference between Reply-to and Return-path in the headers of a mail function?

    Reply-to: Reply-to is where to delivery the reply of the mail.

    Return-path: Return path is when there is a mail delivery failure occurs then where to delivery the failure notification.

    Explain about Type Juggling in php?

    PHP does not require (or support) explicit type definition in variable declaration; a variable’s type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.

    An example of PHP’s automatic type conversion is the addition operator ‘+’. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.

    $foo += 2; // $foo is now an integer (2)
    $foo = $foo + 1.3; // $foo is now a float (3.3)
    $foo = 5 + “10 Little Piggies”; // $foo is integer (15)
    $foo = 5 + “10 Small Pigs”; // $foo is integer (15)

    If the last two examples above seem odd, see String conversion to numbers.
    If you wish to change the type of a variable, see settype().
    If you would like to test any of the examples in this section, you can use the var_dump() function.
    Note: The behavior of an automatic conversion to array is currently undefined.

    Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being “f”, or should “f” become the first character of the string $a? The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes “f”, the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above:

    How can I embed a java programme in php file and what changes have to be done in php.ini file?

    There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.
    The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.

    Example Code:

    getProperty(‘java.version’) . ”; echo ‘Java vendor=’ . $system->getProperty(‘java.vendor’) . ”; echo ‘OS=’ . $system->getProperty(‘os.name’) . ‘ ‘ . $system->getProperty(‘os.version’) . ‘ on ‘ . $system->getProperty(‘os.arch’) . ‘ ‘; // java.util.Date example $formatter = new Java(‘java.text.SimpleDateFormat’, “EEEE, MMMM dd, yyyy ‘at’ h:mm:ss a zzzz”); echo $formatter->format(new Java(‘java.util.Date’)); ?>

    The behaviour of these functions is affected by settings in php.ini.
    Table 1. Java configuration options
    Name
    Default
    Changeable
    java.class.path
    NULL
    PHP_INI_ALL
    Name Default Changeable
    java.home
    NULL
    PHP_INI_ALL
    java.library.path
    NULL
    PHP_INI_ALL
    java.library
    JAVALIB
    PHP_INI_ALL

    How To Turn On the Session Support?

    The session support can be turned on automatically at the site level, or manually in each PHP page script:

    • Turning on session support automatically at the site level: Set session.auto_start = 1 in php.ini.
    • Turning on session support manually in each page script: Call session_start() funtion.

    Explain the ternary conditional operator in PHP?

    Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.

    What’s the difference between include and require?

    It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

    How many ways can we get the value of current session id?

    session_id() returns the session id for the current session.

    How can we destroy the cookie?

    Set the cookie in past.

    How To Read the Entire File into a Single String?

    If you have a file, and you want to read the entire file into a single string, you can use the file_get_contents() function. It opens the specified file, reads all characters in the file, and returns them in a single string. Here is a PHP script example on how to file_get_contents():

    <?php
    $file = file_get_contents(“/windows/system32/drivers/etc/services”);
    print(“Size of the file: “.strlen($file).”\n”);
    ?>

    This script will print:

    Size of the file: 7116

    PHP Advanced Questions and Answers part one

    PHP Advanced Questions and Answers part one

    1.Is it possible to set a time expire page in PHP.?

    Yes it is

    Using header(“Expires: fri, 07 mar 2007 05:00:00 GMT”);

    <?php
    header(“Expires: fri, 07 mar 2007 05:00:00 GMT”);
    ?>

    2.How can we SAVE an image from a remote
    web Server to my web server using PHP?

    <?php
    $file_rimg = fopen(“http://w3answers /image23.jpg”,’rb’);
    $newfile_name_img = “/tmp/tutorial.file”;
    $file_wnew = fopen($newfile_name_img,’wb’);
    while (!feof($file_rimg)) {
    $chunk_rd = fread($file_rimg,1024);
    fwrite($file_wnew,$chunk_rd);
    }
    fclose($file_wnew);
    fclose(file_rimg);
    ?>
    3.What is the output of 2^2 in php ?

    The answer is 0 (Zero)
    Important note
    Everyone expected answer would be 4.   But answer is zero.  How it happened only in php ?

    The ^ operator is different in each language.In PHP ^ means the bitwise exlusive or of the two numbers.

    4.What is the output of below script?

    <?php
    $x = 3;
    switch ($x) {
    case 2: echo ‘line 1′; break;
    case 3:
    case 4: echo ‘line 2′; break;
    default: echo ‘line 3′;
    }
    ?>

    a. echo ‘line 3′;
    b. echo ‘line 2′;
    c. Error
    d. None of the above

    Ans: b (Answer is line2)
    5.What is the output here?

    <?php
    $x = ‘raj’;
    echo ‘Hello $x’;

    ?>

    a. helloravj
    b. Parse error
    c. hello $x
    d. syntax error

    ANS: c

    6.What output do you get here?

    <?php
    $list = array(“block”,”cut”,”pens”,”dogs”);
    $list[] = “elephant”;
    $list[] = “dragon”;
    print “$list[4]“;
    ?>

    a. Error
    b. elephant
    c. dragon
    d. nothing
    e. dogs

    ANS: b (elephant)

    7.what is the output for following code?

    <?php
    echo 12+FALSE;
    ?>

    a. 12
    b. no
    c. parse error
    d. T_ECHO error
    e. FALSE

    ANS: 12

    8.What is the output ?

    <?php
    $x=7;
    if ($x < 2) { echo “11″; }
    elseif ($x < 16) { echo “12″; }
    elseif ($x < 14) { echo “13″; }
    elseif ($x > 14) { echo “14″; }
    elseif ($x < 10) { echo “15″; }
    else { echo “16″; }

    ?>

    a.16
    b.15
    c.12
    d.13

    ANS:12

    9.What is the result here?

    <?php
    echo “test”;
    $x = ”;
    switch ($x) {
    case “0″: echo “String”; br;
    case 0: echo “”; break;
    case NULL: echo “NULL”; br;
    case FALSE: echo “heeder”; br;
    case “”: echo “no string”; br;
    default: echo “nothing else”; br;
    }

    ?>

    a. Something else
    b. Empty string
    c. Integer
    d. String

    ANS: Integer

    10.What is the output?

    <?php
    function x ($y) {
    function y ($z) {
    return ($z*2); }
    return($y+3); }
    $y = 4;
    $y = x($y)*y($y);
    echo “$y”;
    ?>

    a. None
    b. 54
    c. 56
    d. 58

    ANS:56