You are on page 1of 98

Q.1 How does a Web work at a fundamental level ?

Ans. When a typical HTTP client visit a URL through the web browser, the browser sends an
HTTP request to the web server. The web server responses to this request with the resource that
is desired. When the browser receives this response, it will render the web page.

Q.2 What is the code to instruct PHP to use your own session-handling functions? (For
opening, closing, reading, writing, deleting and garbage collection.)

Ans .session_set_save_handler (‘myopen’, ‘myclose’, ‘myread’, ‘mywrite’, ‘mydelete’,


‘mygarbage’) ;

Q.3 In PHP, how is “serialization” of Arrays takes place?

Ans. In PHP, serialization is done by two functions:

1. Serialize () renders the array in a format that can be safely saved to any container (such as a
database field or a file) capable of handling textual content.

2. Unserialize() takes a serialized input and rebuilds the array in memory.

Q.4 What will be the following script output?

10, ‘test’ => ‘a test string’, 200 ); echo “Sorting in ascending order: \n”; ksort ($array,
SORT_STRING); var_dump($array); ?>
Ans. array(3) { [1] => int(10) [2] => int(200) ["test"] => string(13) “a test string” }

Q.5 What is the code to grab the local part of an email address (the part before the @
character)?

Ans. $local_part = substr($email, 0, strpos($email, ‘@’));

Q.6 What do you understand by Inheritance?

Ans. Inheritance is the capability to derive new classes from existing ones. A derived class
inherits the instance variables and methods from the base class(or a “superclass”) and could add
new instance variables and methods. If the new methods are defined with the same name as
those in the base class,the new methods will override those defined in the superclass.

Q.7 What do you understand by Session?

Ans. Session is a mechanism for persisting information between page requests from a particular
user.After calling session_start(), data stored in the $_SESSION superglobal will continue to be
accessiblein future page requests from a client identified by a cookie, POST variable or GET
parameter.

Q.8 What is ternary operator?

Ans. The ternary operator is a shorthand version of an if/then/else statement. Three expressions
are grouped as (condition) ? (if-true) : (if-false).If the first expression is true, the second
condition will be evaluated;if it is false,the third will be evaluated instead.

Q.9 What is ZEND?

Ans. ZEND is a PHP language engine, named for its co-creators Zeev Suraski and Andi
Gutmans,which handles the compilation and execution of PHP scripts as well as management
of the PHP API.

Q.10 What is Polymorphism?

Ans. Polymorphism is a property of object inheritance that enables methods of the same name
to performdifferent actions through successive generations of a class definition.

Q.11 What do you understand by aggregate functions?

Ans. Aggregate functions are special SQL functions that take the values from multiple rows of
data to produce a single result per grouping. Examples of aggregate functions include MIN(),
MAX(), COUNT(), SUM(), and AVG().

Q.12 What do you understand by clone?

Ans. Clone creates a copy of an object. In most cases, this simply means copying property
values from the original object to the new object; however, cloning may require performing
alteration or seperation logic so that the new object does not create a resource conflict. In PHP
4, objects are cloned by default. In PHP 5, objects are implicitly referenced and only cloned by
explicit request.

Q.13 What does @ operator do?

Ans. @ is an error control operator which prevents the error from being printed out(but not
from occurring):

Q.14 What is the use of “variable variables”?

Ans. It allows to use the value of a variable as the name of a variable. For example: When this
script is executed and the interpreter encounters the $$b expression,it first determines thevalue
of $b,which is the string a. It then reevaluates the expression with a substituted for $b as $a,thus
returning the value of the $a variable.

Q.15 What is the use of “variable functions”?

Ans. It allows to use the value of a variable as the name of a function. For example:

function even_number ($x) { echo “$x is even”; }

$n = 13; $a = ($n % 2 ? ‘odd_number’ : ‘even_number’); $a($n);?>

At the end of the script,$a will contain either odd_number or even_number. The expression
$a($n) will then be evaluated as a call to either odd_number() or even_number().

Q.16 Describe the operation of a cookie ?

Ans. The operation of a cookie is described by the following series of events: 1. Client sends an
HTTP request to server. 2. Server sends an HTTP response with Set-Cookie: foo=bar to client.
3. Client sends an HTTP request with Cookie: foo=bar to server. 4. Server sends an HTTP
response to client.

Q.17 Explain the use of var_dump ($array)?

Ans. Dumps information about a variable. e.g.

Output:array(1) { [1]=> int(1)}

Q.18 What do you understand by radomizing arrays?

Ans. This means to extract a random value from an array. This can be accomplished by using
the array_rand() function, which returns the index of one or more elements picked at random:

In this case as we specified only one element should be returned; therefore we’ll receive a
single value. (It was 2 in my case, corresponding to the “Nains” element.) If we specified more
than one element, the result would be returned as an array of keys.

Q.19 What is the difference between ‘==’ and ‘===’ operators?

Ans. ‘==’ operator tests the equivalence of two entities whereas ‘===’ operator also tests data
type.

Q.20 Describe regular expressions and their types?


Ans. Regular expressions(regexps) are the most powerful tools in the string manipulation
toolbox.They provide a robust language for specifying patterns in strings and extracting or
replacing identified portions of text. Regular expressions in PHP are of two types: PCRE and
POSIX. PCRE Regular expressions are so named because they use the Perl Compatible
Regular Expression library to provide regexps with the same syntax and semantics as those in
Perl. POSIX regular expressions support standard POSIX-extended regular expression syntax.

Q.21 What is the Basic PCRE Syntax?

Ans. A regular expression pattern is a string consisting of plain text and pattern
metacharacters.The regexps metacharacters define the type and number of characters that can
match a particular part of a pattern.The most basic set of metacharacters are the character
classes, which allow a pattern to match multiple characters simultaneously.The basic character
classes are shown in table: PCRE Base Character Classes

Metacharacter Characters Matched \d Digits 0-9 \D Anything not a digit \w Any alphanumeric
character or an underscore (_) \W Anything not an alphanumeric character or an underscore \s
Any whitespace (spaces,tabs,newlines) \S Any nonwhitespace character . Any character except
for a newline The basic character class metacharacters each match a single character. Thus, to
make them useful in patterns, it can be specified how many times they must match with the
help of PCRE Enumerators.

Q.22 How PHP handles dates and times?

Ans. PHP handles dates and times in three basic formats:1. UNIX time stamps2. Date arrays3.
String- formatted dates Internally PHP stores all its dates as UNIX time stamps, which are
defined as the number of seconds since the UNIX epoch, January 1, 1970 00:00:00 UTC.

Q.23 For how long are the PHP date functions guaranteed to work on 32-bit systems?

Ans. On 32-bit systems, the PHP date functions are only guaranteed to work until January 19,
2038.

Q.24 Name the function which will return the current UNIX time stamp?

Ans. time().

Q.25 Write any two functions which will output the current time as 11:26 pm?

Ans. print date(‘g:i a’); and print strftime(‘%I:%M %p’);

Q.26 What is Mail Transport Agent?


Ans. When email is sent from organization to organization, it is sent from email server to email
server. The software that runs on our email server and handles sending and receiving email
from around the Internet is called the Mail Transport Agent(MTA). Examples of MTA are:-
sendmail- postfix- qmail- Microsoft Exchange- Lotus NotesMail transport agents talk to each
other using the SMTP network protocol.

Q.27 What is Simple Mail Transport Protocol?

Ans. The Simple Mail Transport Protocol(SMTP) is the standard network-layer protocol for
transmitting an email message across the Internet. Servers normally listen for incoming SMTP
connections on port 25.

Q.28 What do you understand by MX Records?

Ans. When an MTA has an email message to send to another MTA, it has to convert the
address in the To:, Cc:, or Bcc: line into an IP address. Everything after the @ sign in the
address is taken to be the email domain. The email domain is not the real name of a server, it’s
actually a special kind of DNS alias. To receive email for our email domain we have to add an
MX record for that email domain to our DNS server.

Q.29 What is Mail User Agent? Ans. The Mail User Agent(MUA) is the jargon name for
an email client.Examples of Mail User Agents are:- Outlook Express- Evolution – KMail-
pine- mutt- HotmailA PHP scripts that sends email is also a type of Mail User Agent.

Mail User Agents read email directly from files on disk, via network protocols such as POP3 or
IMAP, or via proprietary network protocols(as used by Microsoft Exchange). Mail User
Agents normally send their email by connecting to a Mail Transport Agent over the network
via the SMTP network protocol.Some UNIX-based Mail User Agents may send their email
instead by executing a sendmail wrapper program.When a Mail User Agent connects to an
MTA via SMTP to send email, it may use SASL to authenticate the user.

Q.30 What is SASL?

Ans. The Simple Authentication and Security Layer(SASL) is a tried and trusted way to bolt
user-Authentication onto existing network protocols. SMTP has been extended (via the SMTP
AUTH command) to support SASL.

Q.31 How would you attach a file to an email message?

Ans. To attach a file to an email message, we have to create a multipart MIME message. -Pass
these headers as the fourth parameter to mail(): MIME-Version: 1.0 Content-Type:
multipart/mixed; boundary=”php-12345″ Note the boundary on the end of the Content-
Type.The boundary is an arbitrary US-ASCII string that tells MUAs when the end of a MIME
block has been reached. -The first part of the message string should be a plain text
message.Note the boundary marker after the message which tells MIME that we’ve reached the
end of this particular part of the email message. -The second part of the “message string ”
should be the message itself.We need to add Content-Type and Content-Transfer-Encoding
headers to the message, followed by the message itself. We have to put the boundary marker
after at the end of each part of the message. -Next come the attachments. Each attachment gets
added to the “message” string as well. We need to add Content-Type and Content-Transfer-
Encoding headers, and then the attachment.

Q.32 How would you attach images for HTML emails?

Ans. HTML emails will attampt to download their images and stylesheets from our web server.
Because of security and privacy reason, many MUAs will refuse to attempt these
downloads.We can add images as attachments to the email, and then point HTML at the
attached images.- Change the first Content type of email to be multipart/related.Boundary
definition must be included.- When we add an image as an attachment, include this additional
header: Content-Location: URL URL is the “URL” that we use inside the tag to include the
image.

Q.33 How do you open a socket?

Ans. We can create a socket using the fsockopen() and pfsockopen() functions.We tell PHP
what type of network transport we want to use by prefixing the transport to the name or IP
address of the server we want to connect to. Sockets created using fsockopen() are
automatically closed by PHP when our script ends while sockets created using pfsockopen()
are persistent.

Q.34 What is SQL Injection?

Ans. It is a form of exploit attack, similar to Command Injection, used against scripts that do
not adequately validate or filter user supplied data. When unfiltered and unvalidated data is
passed to a SQL query, it can potentially allow a malicious user to execute arbitrary SQL
commands enabling him to steal and/or destroy important information.

Q.35 What is the use of database indexing?

Ans. A database index enables our RDBMS to more quickly find data based on identifying
fields. For example, if we plan to allow searching by name, creating an index on the name field
in our database will yield faster lookup results.

Q.36 What is the use of Debuggers?

Ans. Debugger applications and extensions allow a developer to track the runtime execution of
a script highlighting variable values and logic flow. Examples of debugging tools include
DBG, APD, and XDebug.
Q.37 Why error logging is required for a site?

Ans. Error logging (usually to a file) allows us as the site maintainer to keep a track on error
conditions in our script. At the same time, this hides errors from our users who at best will not
know what to do with the messages, or at worst will use those errors to compromise our site.

Q.38 What is MIME Encoding?

Ans. MIME(Multipart Internet Message Extensions) Encoding is originally defined by RFC


1341, it extends basic email encapsulation(which is limited to a single text body section) to
allow for an arbitrary number of attachments – each of which may use a distinct content type
and encoding.

Q.39 What is Open Basedir?

Ans.The php.ini setting open_basedir is a technique used on many Shared Hosting


providers(along with safe_mode) to limit the ability of one user to read another user’s files.
When This setting is used, any running script is restricted from using fopen() or other
filesystem access functions on files that resides outside the directory specified.

Q.40 What is the use of Output buffering?

Ans. Output buffering, controlled by settings in our php.ini or use of the ob_ start () function,
causes generated output to be temporary stored in memory. While generally streamlining the
output pipeline, this process also enables an executing script to cancel, modify, or inject content
even after”output” has already started. This also means that the header() command can be used
after contant has been output(normally not allowed).

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

1) What is the difference between strstr & stristr?

For strstr, the syntax is: string strstr(string $string,string $str ); The function strstr will search
$str in $string. If it finds the string means it will return string from where it finds the $str upto
end of $string.

For Example:

$string = "http://yahoomail.com";
$str="yahoomail";
The output is "yahoomail.com". The main difference between strstr and stristr is of case
sensitivity. The former consider the case difference and later ignore the case difference.

2) What is the difference between explode and split?

Split function splits string into array by regular expression. Explode splits a string into array by
string.

For Example:

explode(" and", "India and Pakistan and Srilanka");


split(" :", "India : Pakistan : Srilanka");

Both of these functions will return an array that contains India, Pakistan, and Srilanka.

3) How can you avoid execution time out error while fetching record from MySQL?

set_time_limit -- Limits the maximum execution time

For Example:

set_time_limit(0);

If you set to 0 you say that there is not limit.

4) Write a SQL query that displays the difference between the highest and lowest salaries of a
database table "employees". Label the column as DIFFERENCE.

Select max(sal)-min(sal) as Difference from employees;

5) What is the difference between require() and include()?

Both of these constructs includes and evaluates the specific file. The two functions are identical
in every way except how they handle failure. If filepath not found, require() terminates the
program and gives fatal error, but include() does not terminate the program; It gives warning
message and continues to program.

include() produces a Warning while require() results in a Fatal Error if the filepath is not
correct.

6) What is the difference between echo and print?


Main difference between echo() and print() is that echo is just an statement not a function and
doesn't return's value or it just prints a value whereas print() is an function which prints a value
and also it returns value.

We cannot pass arguments to echo since it is just a statement whereas print is a function and we
can pass arguments to it and it returns true or false. print can be used as part of a more complex
expression whereas echo cannot. echo is marginally faster since it doesn't set a return value.

7) An examiner awards the highest mark 75 and the lowest mark 25, the pass marks being 40.
The moderator wants to change the highest mark to 250 and the lowest marks to 100 using the
linear formula y=ax+b. The revised pass marks will be:

A. 145
B. 150
C. 160
D. 400/3

Give the correct option.

y=ax+b

100=25a+b
250=75a+b

Solve it get and b and then put

y=40a+b

Answer: 145

8) A and B are shooters and having their exam. A and B fall short of 10 and 2 shots
respectively to the qualifying mark. If each of them fired at least one shot and even by adding
their total score together, they fall short of the qualifying mark, what is the qualifying mark?

Answer: 11

As A is short by 10 - he has shot 1

As B is short by 2 - he has shot 9

9+1=10 and 10 < 11

9) In objective test a correct answer score 4 marks and on a wrong answer 2 marks. A student
scores 480 marks from 150 questions. How many answers were correct?
A. 120
B. 130
C. 110
D. 150

Answer: B i.e. 130

4x-2y=480
x+y=150

Then X is 130 so 130 is correct answer.

10) An INK bug starts jumping 1 meter to each direction north, south, east and west
respectively. It marks a point in the new locations. It comes back to its original point after
jumping in all directions. It again starts the same process from the newly drawn unique points.
Totally how many points did the bug mark?

11) A guy walks at 4 mph from a point. After 4 hrs a cyclist starts from the same point at 10
mph. At what distance will they meet from the starting point?

Answer: 26.66 m

Explanation: We have, s=vt where s=distance. Since both meet at same point, both travels
same distance=s km. Now, equating, 10(t+4) = 4t ------> t=20/3

sub. t=20/3 in s=4t---------> s = 26.66km

12) What's the difference between COPY OF A FILE & MOVE_UPLOAD_FILE in file
uploading?

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

Copy: Makes a copy of a file. Returns TRUE if the copy succeeded, FALSE otherwise.

13) How do you insert single & double quotes in MySQL db without using PHP?

&amp; / &quote;
Alternately, escape single quote using forward slash ' . In double quote you don't need to escape
quotes. Insert double quotes as "".

14) What do you need to do to improve the performance of the script you have written?

If your script is to retrieve data from Database, you should use "Limit" syntax. Break down the
non dynamic sections of website which need not be repeated over a period of time as include
files.

15) How do you capture audio/video in PHP?

You need a module installed - FFMPEG. FFmpeg is a complete solution to record, convert and
stream audio and video. It includes libavcodec, the leading audio/video codec library. FFmpeg
is developed under Linux, but it can be compiled under most operating systems, including
Windows.

16) How do you know whether the recipient of your mail had opened the mail i.e. read the
mail?

Embed an URL in a say 0-byte image tag may be the better way to go. In other word, you
embed an invisible image on you html email and when the src URL is being rendered by the
server, you can track whether your recipients have view the emails or not.

17) What is random number?

A random number is a number generated by a process, whose outcome is unpredictable, and


which cannot be sub sequentially reliably reproduced.

18) What is difference between srand & shuffle?

The srand function seeds the random number generator with seed and shuffle is used for
shuffling the array values.

shuffle - This function shuffles (randomizes the order of the elements in) an array. This
function assigns new keys for the elements in array. It will remove any existing keys you may
have assigned, rather than just reordering the keys.

srand - Seed the random number generator

19) How can we remove duplicate values from an array?

array_unique() funciton can be used for the purpose.

20) How do I find out weather a number is odd or even?


if (number%2==0 ) then even else odd.

21) How can we get the ID generated from the previous insert operation?

SELECT MAX(ID) from tablename;

22) How to limit the number of rows to 5 that I get out of my database?

Select * from tablename LIMIT 0, 5;

23) How to store binary data in MySQL?

Use BLOB data type for the database field.

24) How can we submit a form without a submit button?

We can submit a form using the JavaScript. Example: document.formname.submit();

PHP Questions for Interview with Answers

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

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

2. Who is the father of PHP and explain the changes in php versions?

Rasmus Lerdorf is the father of PHP. For version changes go to http://php.net

3. How can we submit from 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
document.form.submit() function to submit the form.

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

5. What is the difference between mysql_fetch_object and mysql_fetch_array?

mysql_fetch_object will collect first single matching record where as mysql_fetch_array will collect all matching
from the table in an array.

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

They are both variables. But $message is a variable with a fixed name. $$message is a variable whose name is st
$message. For example, if $message contains “var”, $$message is the same as $var.

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

8. How can we create a database using PHP and MySQL?

In PHP, we can use mysql_create_db() function to create a database. In MySQL, we can use CREATE DATA
command.

9. What are the differences between require and include, include_once?

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

10. Can we use include('abc.php') two-times in a php page “test.php”?

Yes we can include file more than once in a PHP script.

11. What are the different tables present in mysql, which type of table is generated when we are creating a table
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. InnoDB
5. ISAM
6. BDB

MyISAM is the default storage engine as of MySQL 3.23.

12. Functions in IMAP, POP3 AND LDAP?

Please visit http://php.net/imap for details of IMAP functions in PHP and http://php.net/ldap for LDAP functions in

13. 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 comma
argument. For example, “php myScript.php”, assuming “php” is the command to invoke the CLI progr
aware that if your PHP script was written for the Web CGI interface, it may not execute properly in comma
environment.

14. Suppose your ZEND engine supports the mode then how can you configure your php ZEND engine to
mode?

If you change the line: short_open_tag = off in php.ini file. Then your php ZEND engine support only mode.

15. What is meant by nl2br()?

nl2br — Inserts HTML line breaks before all newlines in a string $string. Syntax is nl2br($string); Returns strin
‘<br />’ inserted before all newlines.

For example: echo nl2br(“god bless you”) will output “god bless you” to your browser.

16. What are the reasons for selecting lamp (Linux, apache, mysql, php) instead of combination of other s
programs, servers and operating systems?

All of those are open source resources. Security of linux is more than windows. Apache is a better server that IIS
functionality and security. MySQL is world most popular open source database. PHP is more faster that ASP, ASP
any other scripting language.

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

AES_ENCRYPT() and AES_DECRYPT()


18. How can we encrypt the username and password using php?

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

In PHP, We can encode data using base64_encode($string) and can decode using base64_decode($string);

19. 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 a
a system there by reducing maintenance costs. OO programming is also considered to be better at modeling
world than is procedural programming. It allows for more complicated and flexible interactions. OO systems a
easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancem
a system because it appeals to natural human cognition patterns. For some systems, an OO approach can
development time since many objects are standard across systems and can be reused. Components that manage
shipping, shopping carts, etc. can be purchased and easily modified for a specific system.

20. What are the differences between PROCEDURE ORIENTED LANGUAGES and OBJECT ORIE
LANGUAGES?

Traditional programming has the following characteristics:

• Functions are written sequentially, so that a change in programming can affect any code that follows
function is used multiple times in a system (i.e., a piece of code that manages the date), it is often simply
pasted into each program (i.e., a change log, order function, fulfillment system, etc). If a date change is
(i.e., Y2K when the code needed to be changed to handle four numerical digits instead of two), all these pi
code must be found, modified, and tested.
• Code (sequences of computer instructions) and data (information on which the instructions operates on) a
separate. Multiple sets of code can access and modify one set of data. One set of code may rely on
multiple places. Multiple sets of code and data are required to work together. Changes made to any of th
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 be
to describe an object.) An object is an abstraction of a set of real-world things (for example, an object
created around “date”) The object would contain all information and functionality for that th
dateobject it may contain labels like January, February, Tuesday, Wednesday. It may contain functional
manages leap years, determines if it is a business day or a holiday, etc., See Fig. 1). Ideally, information
particular thing should reside in only one place in a system. The information within an object is encapsula
hidden) from the rest of the system. A system is composed of multiple objects (i.e., date function, report
processing, etc.). When one object needs information from another object, a request is sent asking for s
information. (for example, a report object may need to know what today’s date is and will send a reques
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â€
“polymorphism” that increase the power and flexibility of an object.

21. What is the use of friend function?

Friend Functions - Sometimes a function is best shared among a number of different classes. Such functions
declared either as member functions of one class or as global functions. In either case they can be set to be fri
other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes
class whichnames them as a friend, as if they were themselves members of that class.

22. What are the different types of errors in PHP?

Three are three types of errors:

1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script. For ex
accessing a variable that has not yet been defined. By default, such errors are not displayed to the user
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 ex
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
existent function. These errors cause the immediate termination of the script, and PHP’s default behavio
display them to the user when they take place.

23. How can we convert ASP Scripts to PHP Scripts?

You can download asp2php application from the site http://asp2php.naken.cc to convert ASP scripts to PHP.

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

$second = date(“s”);

25. What is the difference between the functions unlink and unset?

unlink() deletes the given file from the file system. unset() makes a variable undefined.

26. How can we register the variables into a session in PHP?

We can use the $_SESSION[$variable] to register the $variable as a session.


27. What is the difference between char and varchar data types?

char(M) M bytes 0<=M<=255

varchar(M) L+1 bytes where L<=M & 0<=M<=255

i.e. char data type allocate memory statically and varchar data type allocate memory dynamically

28. What is the functionality of md5() function in PHP?

md5() function is used in PHP to calculate the md5 hash of a string. The hash is a 32-character hexadecimal numb
can use it to generate keys, which we use to identify users etc. If we add random number techniques to it th
generated now will be totally different for the same string we are using.

29. How can we know the number of days between two given dates using mysql?

SELECT DIFFDATE(NOW(),‘yyyy-mm-dd’);

30. What are the differences between DROP TABLE and TRUNCATE TABLE statements in MySQL?

DROP TABLE statment is used to delete a table (the table structure, attributes, and indexes will also be delete
TRUNCATE TABLE command deletes only the data inside the table. It is used if we only want to get rid of t
inside a table, and not the table itself.

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

There are 3 ways to logon to a remote server:

1. Use ssh
2. Use telnet if you are concerned with security
3. You can also use rlogin to logon to a remote server

32. How would you backup and restore a big MySQL database? What are the advantages of the approach whi
have taken over the others?

Use the mysqldump command. If you have Telnet/SSH access to your MySQL server, log in and issue the fo
command for each database you want to back up:

shell> mysqldump -u user -ppassword –opt -full database_name > backupfile.sql

Then move the resulting file(s) to your preferred backup areas. If you require more information on the mysq
command, then simply check out this URL www.mysql.com/documentation/mysql

Copy all the relevant table files.

If the server isn’t updating anything (or you’ve deliberately killed mysqld for this purpose) then you can copy all t
with the following extensions in your MySQL data directory:

• *.frm
• *.myd
• *.myi

Make sure you restart the MySQL daemon once you finish copying and downloading the files to your preferred
areas.

TIP: once you’ve completed the backup, restart MySQL with the –log-update switch. This will allow you to kee
of all modifications done in the MySQL tables since your last ‘dump’. To restore your dumps, you should either
to an existing database or create a new database using

shell> mysqladmin create database_name

then issue the following command

shell> mysql -u user -ppassword database_name < backup-file.sql

If you don’t have access to Telnet/SSH and you’re unable to do backups using the methods described above, you
ask your host if it is possible for them to do a backup for you and put the backups in a separate directory so that y
easily FTP your backups to your selected backup areas. Otherwise, if you have access to phpMyAdmin, you can
following procedure:

Access phpMyAdmin, and select the database you wish to ‘dump’ (backup). Scroll down and you will see a b
point saying: “View dump (schema) of database” along with some radio and check boxes. Choose ‘Structu
data’, then click on ‘Add Drop Table’ and ‘Send’ and click ‘Go’. This will save the ‘dump’ to your hard drive. To
a dump using phpMyAdmin, simply insert the file in the correct place once you have chosen the correct datab
doing the following:

Choose the database you will insert your data into, or create a new database. Insert the appropriate SQL quer
already have, or just paste the name of the .sql file you have on your hard drive into the text box under ‘Location
textfile’, and fire away.

Tip: Use a cronjob to schedule backups periodically. The advantages of this approach is the backup is only
consisting of SQL query. So that needs minimum spaces to backup a large database.

33. For the database from the previous question, please give an SQL query which returns the invoice numbe
invoices which contain the article with the number "1234". The query should be able to run under a MySQL 4.0 da

SELECT invoice_no FROM invoice WHERE article_id=1234;

34. What is meant by PEAR in php?

PEAR is short for “PHP Extension and Application Repository” and is pronounced just like the fruit. The p
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 li
download mirrors to support the PHP/PEAR community. PEAR is a community-driven project with the PEAR G
the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joi
project since then.

http://pear.php.net/manual/en/introduction.php

35. How can we know that a session is started in PHP or not?

A session starts by session_start()function. This session_start() is always declared in header portion. It always d
first then we register sessions variables using $_SESSION['variable_name']

PHP Quiz Questions and Answers

Some PHP quiz questions with answers

1) What will be the output of PHP code below?

PHP Code
<?php
$x=array("aaa","ttt","www","ttt","yyy","tttt");
$y=array_count_values($x);
echo $y[ttt];
?>
a)2
b)3
c)1
d)4

2) How do you get information from a form that is submitted using the "get" method?

a )$_GET[];
b) Request.Form;
c) Request.QueryString;
d) $_POST[];

3) What's the best way to copy a file from within a piece of PHP?

a) Print out a message asking your user to "telnet" in to the server and copy the file for you
b) Open the input and output files, and use read() and write() to copy the data block by block until read() returns a z
c) Use the built in copy() function
d) Use "exec" to run an operating system command such as cp (Unix, Linux) or copy (Windows)

4) PHP code is embedded directly into XHTML document?

a) False
b) True

5) Is it possible to submit a form with out a submit button?

a) Yes
b) No

6) What is the full form of PHP?

a) Pre Hypertext Processor


b) Hypertext Preprocessor
c) Hypertext Postprocessor
d) Post Hypertext Processor

7) What is the expansion of LAMP?

a) Linux And MySql PHP


b) Linux Apache MySql PHP

8) In PHP, Which method is used to getting browser properties?


a) $_SERVER['HTTP_USER_AGENT'];
b) $_SERVER['PHP_SELF']
c) $_SERVER['SERVER_NAME']
d) $_SERVER['HTTP_VARIENT']

9) Which of the following function is used to pick one or more random values from PHP Array?

a) array_rand()
b) array_random()
c) Random_array()
d) Rand_array()

10) What will be the output of PHP code below?

PHP Code
<?php
$x=array(1,3,2,3,7,8,9,7,3);
$y=array_count_values($x);
echo $y[8];
?>
a) 43
b) 1
c) 8
d) 6

11) Assume that your php file 'index.php' in location c:/apache/htdocs/phptutor/index.php. If you
$_SERVER['PHP_SELF'] function in your page, then what is the return value of this function?

a) phptutor/index.php
b) /phptutor/index.php
c) c:/apache/htdocs/phptutor/index.php
d) index.php

12) Which operator is used to concatenate two strings in php?

a) dot operator (.)


b) plus operator (+)

13) Are there regular expressions in PHP?

a) Yes - regular expressions use Perl-like conventions


b) Yes - PHP supports two different types of regular expressions: POSIX-extended and Perl-Compatible R
Expressions (PCRE).
c) Yes - regular expressions use the POSIX standard
d) No - PHP uses "glob" style matching only

14) In PHP, which of the following function is used to insert content of one php file into another php file before
executes it

a) include[]
b) #include()
c) include()
d) #include{}

15) Assume that today is 2009-5-19:2:45:32 pm. What will be the output of PHP code below?

PHP Code
<?php
$today = date("F j, Y, g:i a");
?>
a) may 19,09,2:45:32 PM
b) May 19, 2009, 2:45 pm
c) May 19,2009,14:45:32 pm
d) May 19,2009,14:45:32 PM

16) Which of the following function is used for terminate the script execution in PHP?

a) break()
b) quit()
c) die()

17) What function used to print statement in PHP?

a) echo();
b) printf
c) ""

18) What will be the output of PHP code below?

PHP Code
<?php
define("x","5");
$x=x+10;
echo x;
?>
a) Error
b) 15
c) 10
d) 5

19) What will be the output of below mentioned PHP code?

PHP Code
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56;
$arr["x"] = 42;
unset($arr);
echo var_dump($arr);
?>
a) 42
b) 56
c) Null
d) x=42

20) PHP variables are

a) Multitype variables
b) Double type variables
c) Single type variable
d) Trible type variables

21) Which of these statements is true?

a) PHP interfaces to the MySQL database,and you should transfer any data in Oracle or Sybase to MySQL if you
use PHP on the data.
b) PHP interfaces to a number of relational databases such as MySQL, Oracle and Sybase. A wrapper layer is pr
so that code written for one database can easily be transferred to another if you later switch your database engine.
c) PHP interfaces to a number of relational databases such as MySQL, Oracle and Sybase but the interface differs
case.
d) There's little code in PHP to help you interface to databases, but there's no reason why you can't write such code
want to.

22) Can PHP support multiple inheritance?

a) No
b) Yes

23) How would you add 1 to the variable $count?

a) incr count;
b) $count++;
c) $count =+1
d) incr $count;

24) Which of the following is used to check if a function has already been defined?

a) bool function_exists(functionname)
b) bool f_exists(functionname)
c) bool func_exist(functioname)

25) What is the return value of this substr function?

PHP Code
<?php
$rest = substr("abcdef", -1);
$rest = substr("abcdef", 0, -1);
?>
a) f,abcde
b) a,fedcb
c) b,abcdef
d) a,abcde

26) Assume that your php file 'index.php' in location c:/apache/htdocs/phptutor/index.php. If you
basename($_SERVER['PHP_SELF']) function in your page, then what is the return value of this function?

a) phptutor
b) phptutor/index.php
c) index.php
d) /index.php

27) Program below will call the function display_result(). True or False?

PHP Code
<?php
$x="display";
${$x.'_result'} ();
?>
a) False
b) True
c) Parser Error
d) None of the above

28) All variables in PHP start with which symbol?

a) !
b) $
c) &
d) %

29) Who is known as the father of PHP?

a) Larry Wall
b) Rasmus Lerdorf
c) James Gosling
d) Guido Van Rossum

30) In PHP the error control operator is _______

a) .
b) *
c) @
d) &

31) What will be the output of PHP code below?

PHP Code
<?php
$str = "3dollars";
$a = 20;
$a += $str;
print($a);
?>
a) 23 dollars
b) 203 dollars
c) 320 dollars
d) 23

32) What will be the output of PHP code below?


PHP Code
<?php
function zz(& $x)
{
$x=$x+5;
}

$x=10;
zz($x);
echo $x;
?>
a) 5
b) 0
c) 15
d) 10

33) What will be the output of PHP code below?

a) Shows the IP address of the local system


b) Shows the IP address of the visitor
c) Shows the IP address of the webserver
d) None of the above

34) What will be the output of PHP code below?

PHP Code
<?php
$x=dir(".");
while($y=$x->read())
{
echo $y."
"
}
$y->close();
?>
a) display all folder names
b) display a folder content
c) display content of the all drives
d) Parse error

35) What will be the output of PHP code below?


PHP Code
<?php
$qpt = 'QualityPointTechnologies';
echo preg_match("/^Quality/", $qpt);
?>
a) 1
b) 0
c) Quality
d) Null

36) What will be the output of PHP code below?

PHP Code
<?php
$test="3.5seconds";
settype($test,"double");
settype($test,"integer");
settype($test,"string");
print($test);
?>
a) 3.5
b) 3.5 seconds
c) 3
d) 3 seconds

37) What will be the output of PHP code below?

PHP Code
<?php
$x=array(2=>"mouse",7=>"keyboard");
$y=array_keys($x);
echo $y[1];
?>
a) keyboard
b) mouse
c) 7
d) 2

38) What will be the output of PHP code below?

PHP Code
<?php
$data="98.8degrees";
(double)$data;
(int)$data;
(string)$string;
echo $data;
?>
a) 98
b) 98.8
c) 98.8 degrees
d) degrees

39) PHP is _____________

a) Partially cross-platform
b) Truly cross-platform
c) None of above

40) What will be the output of PHP code below?

PHP Code
<?php
$x="101.5degrees";
(double)$x;
(int)$x;
echo (string)$x;
?>
a) 101.5
b) degrees
c) 101
d) 101.5degrees

41) Whether one-line comment begin with hash sign(#) in php?

a) True
b) False
c) None of above

42) In PHP, during error handling include() generates ____________

a) A fatal error, and the script will stop


b) A warning, but the script will continue execution
c) None of the above
43) What will be the output of PHP code below?

PHP Code
<?php
$qpt = 'Eat to live, but not live to eat';
echo preg_match("/^to/", $qpt);
?>
a) 0
b) 1
c) to
d) Null

44) What will be the output of PHP code below?

PHP Code
<?php
$x=array("aaa","","ccc","ddd","");
$y=array_unique($x);
echo count($x) . "," . count($y);
?>
a) 3,1
b) 3,3
c) 5,5
d) 5,4

45) PHP is a __________. It means you do not have to tell PHP which data type the variable is. PHP autom
converts the variable to the correct data type, depending on its value.

a) client side language


b) local language
c) global language
d) loosely typed language

46) Which of the following is not a valid variable name?

a) $number-in-class
b) $nic
c) $NumberInClass
d) $number_in_class

47) Which of the following function is used to change the root directory in PHP?
a) chroot()
b) change_root()
c) cd_root()
d) cd_r()

48) PHP is a __________

a) client side script language


b) server side script language
c) event-driven language

49) What will be the output of PHP code below?

PHP Code
<?php
$father = "mother";
$mother = "son";
echo $$father;
?>
a) son
b) mother
c) motherson
d) error

50) What will be the output of PHP code below?

PHP Code
<?php
$x=array(4,2,5,1,4,5,3,4);
$y=array_count_values($x);
echo count($y);
?>
a) 8
b) 5
c) 7
d) 28

51) The PHP syntax is most similar to:


a) PERL and C
b) Java script
c) VB Script
d) Visual Basic

52) What will be the output of PHP code below?

PHP Code
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56;
$arr["x"] = 42;
echo var_dump($arr);
?>
a) 42
b) array(3) { [12]=> int(2) [13]=> int(56) ["x"]=> int(42) }
c) array(4) { [5]=>int(1) [12]=> int(2) [13]=> int(56) ["x"]=> int(42) }
d) 1,2,56,42

53) What will the ouptut of date() function in PHP code below?

PHP Code
<?php
$date="2009-5-19";
$time="14:31:38";
$datetime=$date.$time;
echo date("Y-m-d:H:i:s",strtotime($datetime));
?>
a) 2009-5-19:14:31:38
b) 2009-5-19:2:31:38
c) 19-5-2009:2:31:38
d) 19/5/2009:14:31:38

54) What will be the output of PHP code below?

PHP Code
<?php
$color=array("red","yellow","white");
$x=in_array("black",$color);
if($x==0)
echo "good bye";
if($x==1) echo "Hello";
?>
a) Hello
b) Error
c) good bye
d) None of the above

PHP Quiz - Answers

(1) a(2) a(3) c(4) b(5) a(6) b(7) b(8) a(9) a(10) b
(11) b(12) a(13) b(14) c(15) b(16) c(17) a(18) d(19) c(20) a
(21) c(22) a(23) b(24) a(25) a(26) c(27) b(28) b(29) b(30) c
(31) d(32) c(33) b(34) b(35) a(36) c(37) c(38) c(39) b(40) d
(41) a(42) b(43) a(44) d(45) d(46) a(47) a(48) b(49) a(50) b
(51) a(52) c(53) a(54) c

New Tags Introduced in HTML5

HTML 5 reduces development costs by making precise rules on how to handle all HTML elements, and how to
from errors. HTML5 is being developed as the next major revision of HTML (HyperText Markup Language), t
markup language of the World Wide Web. HTML 5 is a new version of HTML and XHTML. The HTML
specification defines a single language that can be written in HTML and XML. It aims to reduce the need for pro
plug-in-based rich internet application (RIA) technologies such as Flash, Silverlight, Pivot, and Sun JavaFX. Here
of some of the newly introduced tags in HTML 5.

List of New Tags in HTML 5

1. Article Tag - HTML 5

<article></article>

Defines an article block

2. Aside Tag - HTML 5

<aside></aside>

Defines sidebar from the page content

3. Audio Tag - HTML 5

<audio></audio>

Defines sound content


4. Canvas Tag - HTML 5

<canvas></canvas>

Define Graphics

5. Command Tag - HTML 5

<command></command>

Defines a command

6. Datagrid Tag - HTML 5

<datagrid></datagrid>

Defines data in a tree-list

7. Datalist Tag - HTML 5

<datalist></datalist>

Defines an autocomplete dropdown list

8. Details Tag - HTML 5

<details></details>

Defines details of an element

9. Dialog Tag - HTML 5

<dialog></dialog>

Defines a dialog or conversation

10. Eventsource Tag - HTML 5

<eventsource></eventsource>

Defines a target for events sent by a server


11. Figure Tag - HTML 5

<figure></figure>

Defines a group of media content, and their caption

12. Footer Tag - HTML 5

<footer></footer>

Defines a footer for a section or page

13. Header Tag - HTML 5

<header></header>

Defines a header for a section or page

14. Mark Tag - HTML 5

<mark></mark>

Defines marked text

15. Meter Tag - HTML 5

<meter></meter>

Defines measurement within a predefined range

16. Nav Tag - HTML 5

<nav></nav>

Defines navigation links

17. Output Tag - HTML 5

<output></output>

Defines some types of output


18. Progress Tag - HTML 5

<progress></progress>

Defines progress of a task of any kind

19. Section Tag - HTML 5

<section></section>

Defines a section

20. Source Tag - HTML 5

<source></source>

Defines media resources

21. Time Tag - HTML 5

<time></time>

Defines a date/time

22. Video Tag - HTML 5

<video></video>

Defines a video.

How to redirect an old domain to a new domain using htaccess?

You can redirect an old domain name to the new domain using htaccess file. This uses the 301 redirection
SEO friendly. # redirect from old domain to new domain

RewriteEngine
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]

Put this code in your .htaccess file to redirect an old domain name to new domain name.
How to protect specific folder or disable directory browsing using htaccess?

Use the following htaccess code to protect a specific folder on your website or disabling directory browsing.
useful if your folder doesn’t have a default index page and all files within that directory can be easily se
downloaded by visitors. It is particularly useful if you are selling digital downloads such as zip files in a direct
avoid that use the following code in the .htaccess file.
# disable directory browsing

Options All -Indexes

How to restrict access to your .htaccess file?

By adding the following code to your htaccess file will prevent hacker's attempt to access your htaccess file.
display a 403 error message on their browser if they try to access .htaccess file.
# secure htaccess file
<files .htaccess>
order allow,deny
deny from all
</files>

1. What industry sites and blogs do you read regularly? This


question can give you an idea of how in-tune they are with the latest industry trends
and technologies, as well as how passionate they are about webdev. It'll help separate
the people who do it as a career AS WELL as a hobby from those who might simply be
in it for the big developer paychecks
2. Do you prefer to work alone or on a team? This is an
important question to ask depending on the work environment. If your project is going
to require close interaction with other developers it's very handy to have someone who
has had that kind of experience. On the other hand, many developers thrive while going
solo. Try to find a developer that fits your needs.
3. How comfortable are you with writing HTML entirely by hand? (+exercise)
Although their resume may state that they're an HTML expert, often times many
developers can't actually write an HTML document from top to bottom. They rely on
an external publisher or have to constantly flip back to a reference manual. Any
developer worth a damn should at least be able to write a simple HTML document
without relying on external resources. A possible exercise is to draw up a fake website
and ask them to write the HTML for it. Keep it simple and just make sure they have the
basics down - watch for mistakes like forgetting the <head> </head> tags or serious
misuse of certain elements. If they write something like: <image
src="/some/image.gif">, it might be a good hint to wrap things up and call the next
interviewee.
_
4. What is the w3c? Standards compliance in web development is where
everything is (hopefully?) going. Don't ask them to recite the w3c's mission statement
or anything, but they should at least have a general idea of who they are.
_
5. Can you write table-less XHTML? Do you validate your code? Weed out the
old-school table-driven design junkies! Find a developer who uses HTML elements for
what they were actually intended. Also, many developers will say they can go table-
less, but when actually building sites they still use tables out of habit and/or
convenience. Possibly draw up a quick navigation menu or article and have them write
the markup for it. To be tricky, you could draw up tabular data - give them bonus
points if they point out that a table should be used in that scenario :)
_
6. What are a few of your favorite development tools and why? If they
say notepad you've obviously got the wrong person for the job. Not only can this help
you gauge their level of competence, but it'll also see if they match the tools everyone
else uses in-house.
7. Describe/demonstrate your level of competence in a *nix shell environment
See how well they work without their precious GUI. Ask some basic questions like
how they would recursively copy a directory from one place to another, or how you'd
make a file only readable by the owner. Find out what OSs they have experience with.
_
8. What skills and technologies are you the most interested in improving upon or
learning?
Find out if their future interests match the direction of the position (or the company in
general).
_
9. Show me your portfolio!

A portfolio can say a lot about a developer. Do they have an eye for aesthetics? Are they
more creatively or logically oriented? The most important thing is to look for is solid,
extensive, COMPLETED projects. A half dozen mockups and/or hacked-out scripts is a
sign of inexperience or incompetence.

What sized websites have you worked on in the past? Find a developer that
has experience similar in size to the project you're putting together. Developers with high
traffic, large scale site expertise may offer skills that smaller-sized developers don't, such as
fine tuning apache or optimizing heavily hit SQL queries. On the other hand, developers
who typically build smaller sites may have an eye for things that large scale developers
don't, such as offering a greater level of visual creativity.

Show me your code!


Whether it's plain old HTML or freakishly advanced ruby on rails, ask for code samples.
Source code can say more about a persons work habits than you think. Clean, elegant code
can often be indicative of a methodical, capable developer. A resume may say 7+ years of
perl experience, but that could mean 7 years of bad, unreadable perl. Also, make sure you
ask for a lot of source code, not just a few isolated functions or pieces of HTML. Anyone
can clean up 20-30 lines of code for an interview, you want to see the whole shebang. Don't
ask for a full, functional app, but make sure it's enough that you can tell it's really what their
code is like.

What are a few sites you admire and why? (from a webdev perspective)
Find out what inspires them. While it doesn't necessarily "take one to know one," a great
developer should always have a few impressive favorites.

Fix this code, please. Give them some broken code written in the development language
they are expected to know for the position. Have them go through it line by line and point
out all the mistakes.

I just pulled up the website you built and the browser is displaying a blank page.
Walk me through the steps you'd take to troubleshoot the problem.
This is a great question to determine how well rounded their abilites are. It tests everything
from basic support skills all the way up to troubleshooting the webserver itself.

What's your favorite development language and why? What other features (if any)
do you wish you could add to this language Asking about feature additions is a
particularly valuable question - it can reveal if they're skilled in programming in general or
if their skillset is pigeonholed into their language of choice.

Do you find any particular languages or technologies intimidating?

I've often felt that the more I learn, the less I feel like I know. Solving one mystery opens
up ten others. Having the interviewee tell you their faults can reveal a lot about what they
know.

Acronym time (oh boy!)

Some might argue that knowing what acronyms actually stand for is trivial, but there are
certain acronyms that a developer should have hard-wired into their head ( HTML or CSS,
for example). This is the kind of question that might be better reserved for the phone
interview to weed out those who are very unqualified.

What web browser do you use?

There is a right answer to this question: all of them. A competent developer should be
familiar with testing cross-browser compatibility by using all the major web browsers.
Obviously they'll have a primary browser they use for surfing, but their answer to this
question might be a good way for you to segue to asking how extensively they test cross-
browser issues. Also, if it's some kind of css/html position seeing what toolbars they have
installed can be a good metric of their skillset (I personally find the web developer toolbar
for firefox to be invaluable)
_

10. Rank your interest in these development tasks from 1 to 5 (1 being not interested
at all, 5 being extremely interested) Write up a list of tasks the job requires. Having
them rank these items according to their interest level can help you find who is the best
suited for the position. I know debugging uncommented perl code from 1997 sounds
seriously awesome to me.
_
11. What are a few personal web projects you've got going on?
Almost all developers have personal web projects they like to plug away at in their
spare time. This is another question that can help differentiate the passionate developers
from the clock-punchers. It's also a good question to end an interview with, as it's
usually easy (and fun) for them to answer.

Any more great questions you can think of?

What is meant by nl2br()? A:16 Inserts HTML line breaks (<BR />) 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 <br /> 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: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
<?php
// 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 '<p>', date(DATE_RFC1123, $stamp) ,'</p>';?>

Q:33 What is meant by urlencode and urldocode? 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: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: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.
Maximum Length
Identifier
(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);

Mysql interview questions and answers are below


'
Question
how to do login in mysql with unix shell
s:1
Answers By below method if password is pass and user name is root
:1 # [mysql dir]/bin/mysql -h hostname -u root -p pass

Question
how you will Create a database on the mysql server with unix shell
s:2
Answers
mysql> create database databasename;
:2

Question
how to list or view all databases from the mysql server.
s:3
Answers
mysql> show databases;
:3

Question
How Switch (select or use) to a database.
s:4
Answers
mysql> use databasename;
:4

Question
How To see all the tables from a database of mysql server.
s:5
Answers
mysql> show tables;
:5

Question
How to see table's field formats or description of table .
s:6
Answers
mysql> describe tablename;
:6

Question
How to delete a database from mysql server.
s:7
Answers
mysql> drop database databasename;
:7

Question
How we get Sum of column
s:8
Answers
mysql> SELECT SUM(*) FROM [table name];
:8

Question
How to delete a table
s:9
Answers
mysql> drop table tablename;
:9

Question
How you will Show all data from a table.
s : 10
Answers
mysql> SELECT * FROM tablename;
: 10

Question How to returns the columns and column information pertaining to the
s : 11 designated table
Answers
mysql> show columns from tablename;
: 11

Question
How to Show certain selected rows with the value "pcds"
s : 12
Answers
mysql> SELECT * FROM tablename WHERE fieldname = "pcds";
: 12

Question How will Show all records containing the name "sonia" AND the phone
s : 13 number '9876543210'
Answers mysql> SELECT * FROM tablename WHERE name = "sonia" AND
: 13 phone_number = '9876543210';
Question How you will Show all records not containing the name "sonia" AND the
s : 14 phone number '9876543210' order by the phone_number field.
Answer : mysql> SELECT * FROM tablename WHERE name != "sonia" AND
14 phone_number = '9876543210' order by phone_number;

Question How to Show all records starting with the letters 'sonia' AND the phone
s : 15 number '9876543210'
Answers mysql> SELECT * FROM tablename WHERE name like "sonia%" AND
: 15 phone_number = '9876543210';

Question How to show all records starting with the letters 'sonia' AND the phone
s : 16 number '9876543210' limit to records 1 through 5.
Answers mysql> SELECT * FROM tablename WHERE name like "sonia%" AND
: 16 phone_number = '9876543210' limit 1,5;

Question Use a regular expression to find records. Use "REGEXP BINARY" to force
s : 16 case-sensitivity. This finds any record beginning with r.
Answer :
mysql> SELECT * FROM tablename WHERE rec RLIKE "^r";
16

Question
How you will Show unique records.
s : 17
Answer :
mysql> SELECT DISTINCT columnname FROM tablename;
17

Question how we will Show selected records sorted in an ascending (asc) or descending
s : 18 (desc)
Answer : mysql> SELECT col1,col2 FROM tablename ORDER BY col2 DESC;
18
mysql> SELECT col1,col2 FROM tablename ORDER BY col2 ASC;

Question
how to Return total number of rows.
s : 19
Answers
mysql> SELECT COUNT(*) FROM tablename;
: 19
Question
How to Join tables on common columns.
s : 20
Answer : mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup
20 left join person on lookup.personid=person.personid=statement to join birthday in
person table with primary illustration id

Question How to Creating a new user. Login as root. Switch to the MySQL db. Make
s : 21 the user. Update privs.
Answer : # mysql -u root –p mysql> use mysql;
21 mysql> INSERT INTO user (Host,User,Password)
VALUES('%','username',PASSWORD('password'));
mysql> flush privileges;

Question
How to Change a users password from unix shell.
s : 22
Answers # [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password 'new-
: 22 password'

Question How to Change a users password from MySQL prompt. Login as root. Set the
s : 23 password. Update privs.
Answer : # mysql -u root –p mysql> SET PASSWORD FOR 'user'@'hostname' =
23 PASSWORD('passwordhere');
mysql> flush privileges;

Question How to Recover a MySQL root password. Stop the MySQL server process.
s : 24 Start again with no grant tables. Login to MySQL as root. Set new password.
Exit MySQL and restart MySQL server.
Answer : # /etc/init.d/mysql stop
24 # mysqld_safe --skip-grant-tables &
# mysql -u root mysql> use mysql; mysql> update user set
password=PASSWORD("newrootpassword") where User='root'; mysql> flush
privileges; mysql> quit # /etc/init.d/mysql stop # /etc/init.d/mysql start

Question
How to Set a root password if there is on root password.
s : 25
Answer :
# mysqladmin -u root password newpassword
25
Question
How to Update a root password.
s : 26
Answer :
# mysqladmin -u root -p oldpassword newpassword
26

Question How to allow the user "sonia" to connect to the server from localhost using the
s : 27 password "passwd". Login as root. Switch to the MySQL db. Give privs.
Update privs.
Answers # mysql -u root -p
: 27 mysql> use mysql; mysql> grant usage on *.* to sonia@localhost identified by
'passwd'; mysql> flush privileges;

Question How to give user privilages for a db. Login as root. Switch to the MySQL db.
s : 28 Grant privs. Update privs.
Answers # mysql -u root -p
: 28 mysql> use mysql;
mysql> INSERT INTO user
(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_
priv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N'); mysql> flush
privileges; or mysql> grant all privileges on databasename.* to
username@localhost;
mysql> flush privileges;

Question
How To update info already in a table and Delete a row(s) from a table.
s : 29
Answer : mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv
29 = 'Y' where [field name] = 'user';
mysql> DELETE from [table name] where [field name] = 'whatever';

Question
How to Update database permissions/privilages.
s : 30
Answer :
mysql> flush privileges;
30

Question
How to Delete a column and Add a new column to database
s : 31
Answer : mysql> alter table [table name] drop column [column name];
31 mysql> alter table [table name] add column [new column name] varchar (20);

Question
Change column name and Make a unique column so we get no dupes.
s : 32
Answer : mysql> alter table [table name] change [old column name] [new column name]
32 varchar (50);
mysql> alter table [table name] add unique ([column name]);

Question
How to make a column bigger and Delete unique from table.
s : 33
Answer : mysql> alter table [table name] modify [column name] VARCHAR(3);
33 mysql> alter table [table name] drop index [colmn name];

Question
How to Load a CSV file into a table
s : 34
Answer : mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table
34 name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'
(field1,field2,field3);

Question How to dump all databases for backup. Backup file is sql commands to
s : 35 recreate all db's.
Answer :
# [mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql
35

Question
How to dump one database for backup.
s : 36
Answer : # [mysql dir]/bin/mysqldump -u username -ppassword --databases databasename
36 >/tmp/databasename.sql

Question
How to dump a table from a database.
s : 37
Answer : # [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename
37 > /tmp/databasename.tablename.sql

Question
Restore database (or database table) from backup.
s : 38
Answer : # [mysql dir]/bin/mysql -u username -ppassword databasename <
38 /tmp/databasename.sql

Question
How to Create Table show Example
s : 39
Answer : mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial
39 VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid
VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email
VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp
DATE,timestamp time,pgpemail VARCHAR(255));
Question How to search second maximum(second highest) salary value(integer)from
s : 40 table employee (field salary)in the manner so that mysql gets less load?
Answers By below query we will get second maximum(second highest) salary
: 40 value(integer)from table employee (field salary)in the manner so that mysql gets
less load?
SELECT DISTINCT(salary) FROM employee order by salary desc limit 1 ,
1 ;
(This way we will able to find out 3rd highest , 4th highest salary so on just need to
change limit condtion like LIMIT 2,1 for 3rd highest and LIMIT 3,1 for 4th
some one may finding this way useing below query that taken more time as
compare to above query SELECT salary FROM employee where salary < (select
max(salary) from employe) order by salary DESC limit 1 ;

What is meant by Session Clustering?

The Session Manager session support allows multiple server instances to share a common pool
of sessions, known as a session cluster

Session clustering setting up methods :

#1)First methods, is to have a NFS shared where session will be store. Setting this is quite easy,
just a little modification on php.ini file to change the “session.save_path ? directive to point to
the NFS share. The main problem with NFS is on high traffic, NFS share is really slow. So
synchronisation and data corruption can arrive and this can be very frustrating.
#2) The Second method is to use a Database to store session datas. This solution suppose to
write custom session handler. The only real problem of this method is that will generate a very
big amount of the number of connections and database query. And this required a dedicated
server and a cron job to clean all unused session datas.
#3)The third method is to use the MCache. MCache is a daemon (a server) that deal with
session storing only. It support from RAM storage to data serialization in file/fatabase. It is said
that MCache access is native as a session handler in PHP, so it’s just about configuration via
php.ini … but I did not investigate yet on how to make it work.
#4)The fourth method is Memcache, another daemon for “distributed memory object caching
system ?. Advantage to Memcache, as it’s integrated in PHP as PECL (look at the
documentation on how to install). This method can be very interesting as it provide great
performance but this will require a single or couple dedicate server of it use.
#5)The last method is commercialized by Zend. The product is the Zend Platform and integrate
many component of some previous Zend products (Zend Server, etc.) and some new products
(Zend Core…). The Zend Core is a Cluster manager that can handle multiple server. It can be
use to remote debugging (from Zend Server), performance monitoring and sessions replication.
As described, there are many advantage using Zend Platform so I could only to advise you to
use it simply first to profile your application and for session clustering ! But there are a little
probleme, session are replicated from a server to the other servers. So if a server crash maybe
the Platform could not have the time to replicate session data. It can result to session
destruction. But be sure that Zend know the problem and will surely fix this soon or later.

How does Database handle Sessions?

As you should be aware the HTTP protocol, as used for serving web pages, is completely
stateless. This means that after the server has received a request, processed it and sent a
response, the process which dealt with that request dies. Anything that the process had in its
memory therefore dies with it, so when a subsequent request is received from the same client it
is unable to refer to its memory about anything that happened previously.

Fortunately PHP provides a standard method of maintaining memory (state) between requests
in the form of Session Handling functions. This allows the programmer to maintain a set of
variables in the $_SESSION array which is automatically saved to persistent storage at the end
of each script, and then automatically loaded back into memory when a subsequent request is
received from a client which supplies the same session_id.

By default the medium used as persistent storage by the session handler will be a series of disk
files, one per session, where the file name is the session_id. A file is created khan a new session
starts, and is deleted when the session terminates (or has expired). This is perfectly adequate for
most circumstances, but it has the following drawbacks:

1. If you are using a shared server then other users of that server may be able to access your
session files, thus compromising the security of your site.
2. Each server will have its own directory where these session files are maintained, so if you are
employing load balancing across multiple servers there is no guarantee that a request for an
existing session will be given to the server which is maintaining the state for that session.
3. It would be difficult for a site administrator to perform such queries as "how many sessions
are currently active?" or "which users are currently logged in?"

The authors of PHP have provided the ability to store session data using a method other than
disk files by means of the session_set_save_handler function. we have used this function to
store all my session data in application database.

Tell me some thing about mod_rewrite and url rewriting?

mod_rewrite
*************
Simply, mod_rewrite is used for rewriting a URL at the server level, giving the user output for
that final page. So, for example, a user may ask for http://www.referads.com/example/blue/,
but will really be given http://www.referads.com/example.php?colour=blue by the server. Of
course, the user will be none the wiser to this little bit of chicanery.

What do I need to get mod_rewrite working? <?php phpinfo(); ?>

Load that page up in your web browser, and perform a search for “mod_rewrite”. All being
well, you’ll find it in the “Apache loaded modules” section of the page. If it isn’t there, you’ll
have to contact your hosting company and politely ask them to add it to the Apache
configuration.

Assuming the mod_rewrite module is loaded, then you’re good to go!


A simple mod_rewrite example

So, let’s write a simple mod_rewrite example. This isn’t going to be anything fancy; we’re just
going to redirect people who ask for alice.html to the page bob.html instead. First, let’s create
the Alice and Bob pages. Below is Alice’s webpage - create a similar one for Bob.

<html> <head> <title>Alice's webpage</title>

</head> <body> <p> This is Alice's webpage </p> </body> </html>

Upload both of these to your web server, and check that you can view both of them. Now
comes the fun - we’re going to add a couple of lines to your .htaccess file. The .htaccess file is a
text file which contains Apache directives. Any directives which you place in it will apply to
the directory which the .htaccess file sits in, and any below it. To ours, we’re going to add the
following:

RewriteEngine on
RewriteRule ^alice.html$ bob.html

Upload this .htaccess file to the same directory as alice.html and bob.html, and reload Alice’s
page. You should see Bob’s page being displayed, but Alice’s URL. If you still see Alice’s
page being displayed, then check you’ve followed the instructions correctly (you may have to
clear your cache). If things still aren’t working for you, then contact your technical support
people and ask them to enable mod_rewrite and the FileInfo override in their httpd.conf file for
you

The structure of a RewriteRule

RewriteRule Pattern Substitution [OptionalFlags]

The general structure of a RewriteRule is fairly simple if you already understand regular
expressions. This article isn’t intended to be a tutorial about regular expressions though - there
are already plenty of those available. RewriteRules are broken up as follows:

RewriteRule

This is just the name of the command. Pattern

A regular expression which will be applied to the “current” URL. If any RewriteRules have
already been performed on the requested URL, then that changed URL will be the current
URL.
Substitution

Substitution occurs in the same way as it does in Perl, PHP, etc.

You can include backreferences and server variable names (%{VARNAME}) in the
substitution. Backreferences to this RewriteRule should be written as $N, whereas
backreferences to the previous RewriteCond should be written as %N.

A special substitution is -. This substitution tells Apache to not perform any substitution. I
personally find that this is useful when using the F or G flags (see below), but there are other
uses as well. OptionalFlags

This is the only part of the RewriteRule which isn’t mandatory. Any flags which you use
should be surrounded in square brackets, and comma separated. The flags which I find to be
most useful are:

F - Forbidden. The user will receive a 403 error.

L - Last Rule. No more rules will be proccessed if this one was successful.
R[=code] - Redirect. The user’s web browser will be visibly redirected to the substituted URL.
If you use this flag, you must prefix the substitution with http://www.somesite.com/, thus
making it into a true URL. If no code is given, then a HTTP reponse of 302 (temporarily
moved) is sent.

A full list of flags is given in the Apache mod_rewrite manual.

A slightly more complicated mod_rewrite example

Let’s try a slightly more meaty example now. Suppose you have a web page which takes a
parameter. This parameter tells the page how to be displayed, and what content to pull into it.
Humans don’t tend to like remembering the additional syntax of query strings for URLs, and
neither do search engines. Both sets of people seem to much prefer a straight URL, with no
extra bits tacked onto the end.

In our example, you’ve created a main index page with takes a page parameter. So, a link like
index.php?page=software would take you to a software page, while a link to index.php?
page=interests would take you to an interests page. What we’ll do with mod_rewrite is to
silently redirect users from page/software/ to index.php?page=software etc.

The following is what needs to go into your .htaccess file to accomplish that:

RewriteEngine on
RewriteRule ^page/([^/\.]+)/?$ index.php?page=$1 [L]

Let’s walk through that RewriteRule, and work out exactly what’s going on:

^page/

Sees whether the requested page starts with page/. If it doesn’t, this rule will be ignored.
([^/.]+)

Here, the enclosing brackets signify that anything that is matched will be remembered by the
RewriteRule. Inside the brackets, it says “I’d like one or more characters that aren’t a forward
slash or a period, please”. Whatever is found here will be captured and remembered.
/?$

Makes sure that the only thing that is found after what was just matched is a possible forward
slash, and nothing else. If anything else is found, then this RewriteRule will be ignored.
index.php?page=$1

The actual page which will be loaded by Apache. $1 is magically replaced with the text which
was captured previously.

[L]
Tells Apache to not process any more RewriteRules if this one was successful.

Let’s write a quick page to test that this is working. The following test script will simply echo
the name of the page you asked for to the screen, so that you can check that the RewriteRule is
working.

<html><head><title>Second mod_rewrite example</title></head>

<body><p> The requested page was:<?php echo $_GET['page']; ?> </p> </body> </html>

Again, upload both the index.php page, and the .htaccess file to the same directory. Then, test
it! If you put the page in http://www.somesite.com/mime_test/, then try requesting
http://www.somesite.com/mime_test/page/software. The URL in your browser window will
show the name of the page which you requested, but the content of the page will be created by
the index.php script! This technique can obviously be extended to pass multiple query strings to
a page - all you’re limited by is your imagination. Conditional Statements and mod_rewrite

But what happens when you start getting people hotlinking to your images (or other files)? Hot
linking is the act of including an image, media file, etc from someone else’s server in one of
your own pages as if it were your own. Obviously, as a webmaster, there are plenty of times
when you don’t want people doing that. You’ll almost certainly have seen examples where
someone has linked to one image on a website, only for a completely different, “nasty” one to
be shown instead. So, how is this done?

It’s pretty simple really. All it takes are a couple of RewriteCond statements in your .htaccess
file.

RewriteCond statements are as they sound - conditional statements for RewriteRules. The basic
format for a RewriteCond is RewriteCond test_string cond_pattern. For our purpose, we will
set the test_string to be the HTTP_REFERER. If the test string is neither empty nor our own
server, then we will serve an alternative (low bandwidth) image, which tells the person who is
hotlinking off for stealing our bandwidth.

Here’s how we do that: RewriteEngine on

RewriteCond %{HTTP_REFERER} !^$


RewriteCond %{HTTP_REFERER} !^http://(www\.)?somesite.com/.*$ [NC]
RewriteRule \.(gif|jpg|png)$ http://www.somesite.com/nasty.gif [R,L]

Here, the RewriteRule will only be performed if all the preceeding RewriteConds are fulfilled.
In the second RewriteCond, [NC] simply means “No Case”, so it doesn’t matter whether the
domain name was written in upper case, lower case or a mixture of the two. So, any requests
for gif, jpg or png files from referers other than somesite.com will result in your “nasty” image
being shown instead.
The [R,L] in the RewriteRule simply means “Redirect, Last”. So, the RewriteRule will visibly
redirect output to “nasty.gif” and no more RewriteRules will be performed on this URL.

If you simply don’t want the hot linkers to see any image at all when they hot link to your
images, then simply change the final line to RewriteRule \.(gif|jpg|png)$ - [F]. The - means
“don’t rewrite the requested URL”, and the [F] means “Forbidden”. So, the hot linker will get a
“403 Forbidden message”, and you don’t end up wasting your bandwidth.

URL Rewriting

***********
Readable URLs are nice. A well designed website will have a logical file system layout, with
smart folder and file names, and as many implementation details left out as possible. In the best
designed sites, readers can guess at filenames with a high level of success.
However, there are some cases when the best possible information design can’t stop your site’s
URLs from being nigh-on impossible to use. For instance, you may be using a Content
Management System that serves out URLs that look something like
http://www.site.com/viewcatalog.asp?category=hats&prodID=53
This is a horrible URL, but it and its brethren are becoming increasingly prevalent in these days
of dynamically generated pages. There are a number of problems with an URL of this kind.
It exposes the underlying technology of the website (in this case ASP). This can give potential
hackers clues as to what type of data they should send along with the query string to perform a
‘front-door’ attack on the site. Information like this shouldn’t be given away if you can help it.
Even if you’re not overly concerned with the security of your site, the technology you’re using
is at best irrelevant — and at worst a source of confusion — to your readers, so it should be
hidden from them if possible.

Also, if at some point in the future you decide to change the language that your site is based on
(to » PHP, for instance); all your old URLs will stop working. This is a pretty serious problem,
as anyone who has tackled a full-on site rewrite will attest.
The URL is littered with awkward punctuation, like the question mark and ampersand. Those
& characters, in particular, are problematic because if another webmaster links to this page
using that URL, the unescaped ampersands will mess up their XHTML conformance.
Some search engines won’t index pages which they think are generated dynamically. They’ll
see that question mark in the URL and just turn their asses around.
Luckily, using rewriting, we can clean up this URL to something far more manageable. For

example, we could map it to http://www.site.com/catalog/hats/53/


Much better. This URL is more logical, readable and memorable, and will be picked up by all
search engines. The faux-directories are short and descriptive. Importantly, it looks more
permanent.
To use mod_rewrite, you supply it with the link text you want the server to match, and the real
URLs that these URLs will be redirected to. The URLs to be matched can be straight file
addresses, which will match one file, or they can be regular expressions, which will match
many files. Basic Rewriting Some servers will not have » mod_rewrite enabled by default. As
long as the » module is present in the installation, you can enable it simply by starting a
.htaccess file with the command RewriteEngine on Put this .htaccess file in your root so that
rewriting is enabled throughout your site. You only need to write this line once per .htaccess
file.

Basic Redirects

We’ll start off with a straight redirect; as if you had moved a file to a new location and want all
links to the old location to be forwarded to the new location. Though you shouldn’t really ever
» move a file once it has been placed on the web; at least when you simply have to, you can do
your best to stop any old links from breaking. RewriteEngine on RewriteRule ^old\.html$
new.html Though this is the simplest example possible, it may throw a few people off. The
structure of the ‘old’ URL is the only difficult part in this RewriteRule. There are three special
characters in there.

* The caret, ^, signifies the start of an URL, under the current directory. This directory is
whatever directory the .htaccess file is in. You’ll start almost all matches with a caret.

* The dollar sign, $, signifies the end of the string to be matched. You should add this in to stop
your rules matching the first part of longer URLs.

* The period or dot before the file extension is a special character in regular expressions, and
would mean something special if we didn’t escape it with the backslash, which tells Apache to
treat it as a normal character. So, this rule will make your server transparently redirect from
old.html to the new.html page. Your reader will have no idea that it happened, and it’s pretty
much instantaneous. Forcing New Requests Sometimes you do want your readers to know a
redirect has occurred, and can do this by forcing a new HTTP request for the new page. This
will make the browser load up the new page as if it was the page originally requested, and the
location bar will change to show the URL of the new page. All you need to do is turn on the
[R] flag, by appending it to the rule: RewriteRule ^old\.html$ new.html [R] Using Regular
Expressions Now we get on to the really useful stuff. The power of mod_rewrite comes at the
expense of complexity. If this is your first encounter with regular expressions, you may find
them to be a tough nut to crack, but the options they afford you are well worth the slog. I’ll be
providing plenty of examples to guide you through the basics here.
Using regular expressions you can have your rules matching a set of URLs at a time, and mass
redirect them to their actual pages. Take this rule; RewriteRule ^products/([0-9][0-9])/$
productinfo.php?prodID=$1
This will match any URLs that start with ‘products/’, followed by any two digits, followed by a
forward slash. For example, this rule will match an URL like products/12/ or products/99/, and
redirect it to the PHP page. The parts in square brackets are called ranges. In this case we’re
allowing anything in the range 0-9, which is any digit. Other ranges would be [A-Z], which is
any uppercase letter; [a-z], any lowercase letter; and [A-Za-z], any letter in either case.
We have encased the regular expression part of the URL in parentheses, because we want to
store whatever value was found here for later use. In this case we’re sending this value to a
PHP page as an argument. Once we have a value in parentheses we can use it through what’s
called a back-reference. Each of the parts you’ve placed in parentheses are given an index,
starting with one. So, the first back-reference is $1, the third is $3 etc.
Thus, once the redirect is done, the page loaded in the readers’ browser will be something like
productinfo.php?prodID=12 or something similar. Of course, we’re keeping this true URL
secret from the reader, because it likely ain’t the prettiest thing they’ll see all day. Adding
Trailing Slashes If your site visitor had entered something like products/12, the rule above
won’t do a redirect, as the slash at the end is missing. To promote good URL writing, we’ll take
care of this by doing a direct redirect to the same URL with the slash appended.
RewriteRule ^products/([0-9][0-9])$ products/$1/ [R]

Multiple redirects in the same .htaccess file can be applied in sequence, which is what we’re
doing here. This rule is added before the one we did above, like so:

RewriteRule ^products/([0-9][0-9])$ products/$1/ [R]


RewriteRule ^products/([0-9][0-9])/$ productinfo.php?prodID=$1

Thus, if the user types in the URL products/12, our first rule kicks in, rewriting the URL to
include the trailing slash, and doing a new request for products/12/ so the user can see that we
likes our trailing slashes around here. Then the second rule has something to match, and
transparently redirects this URL to productinfo.php?prodID=12. Slick. Match Modifiers

You can expand your regular expression patterns by adding some modifier characters, which
allow you to match URLs with an indefinite number of characters. In our examples above, we
were only allowing two numbers after products. This isn’t the most expandable solution, as if
the shop ever grew beyond these initial confines of 99 products and created the URL
productinfo.php?prodID=100, our rules would cease to match this URL.

So, instead of hard-coding a set number of digits to look for, we’ll work in some room to grow
by allowing any number of characters to be entered. The rule below does just that:

RewriteRule ^products/([0-9]+)$ products/$1/ [R]

Note the plus sign (+) that has snuck in there. This modifier changes whatever comes directly
before it, by saying ‘one or more of the preceding character or range.’ In this case it means that
the rule will match any URL that starts with products/ and ends with at least one digit. So this’ll
match both products/1 and products/1000.
Other match modifiers that can be used in the same way are the asterisk, *, which means ‘zero
or more of the preceding character or range’, and the question mark, ?, which means ‘zero or
only one of the preceding character or range.’

Adding Guessable URLs

Using these simple commands you can set up a slew of ‘shortcut URLs’ that you think visitors
will likely try to enter to get to pages they know exist on your site. For example, I’d imagine a
lot of visitors try jumping straight into our stylesheets section by typing the URL
http://www.yourhtmlsource.com/css/. We can catch these cases, and hopefully alert the reader
to the correct address by updating their location bar once the redirect is done with these lines:

RewriteRule ^css(/)?$ /stylesheets/ [R]

The simple regular expression in this rule allows it to match the css URL with or without a
trailing slash. The question mark means ‘zero or one of the preceding character or range’ — in
other words either yourhtmlsource.com/css or yourhtmlsource.com/css/ will both be taken care
of by this one rule.

This approach means less confusing 404 errors for your readers, and a site that seems to run a
whole lot smoother all ’round.

What are static methods?

Static Keyword

Declaring class members or methods as static makes them accessible without needing an
instantiation of the class. A member declared as static can not be accessed with an instantiated
class object (though a static method can).

The static declaration must be after the visibility declaration. For compatibility with PHP 4, if
no visibility declaration is used, then the member or method will be treated as if it was declared
as public.

Because static methods are callable without an instance of the object created, the pseudo
variable $this is not available inside the method declared as static.

In fact static method calls are resolved at compile time. When using an explicit class name the
method is already identified completely and no inheritance rules apply. If the call is done by
self then self is translated to the current class, that is the class the code belongs to. Here also no
inheritance rules apply.

Static properties cannot be accessed through the object using the arrow operator ->.
Calling non-static methods statically generates an E_STRICT level warning.

Example 19-13. Static member example

<?php
class Foo
{
public static $my_static = 'foo';

public function staticValue() {


return self::$my_static;
}
}

class Bar extends Foo


{
public function fooStatic() {
return parent::$my_static;
}
}

print Foo::$my_static . "\n";

$foo = new Foo();


print $foo->staticValue() . "\n";
print $foo->my_static . "\n"; // Undefined "Property" my_static

// $foo::my_static is not possible

print Bar::$my_static . "\n";


$bar = new Bar();
print $bar->fooStatic() . "\n";
?>

Example 19-14. Static method example


<?php
class Foo {
public static function aStaticMethod() {
// ...
}
}
Foo::aStaticMethod();
?>

Do you know about Cross site Scripting ?

Cross-site scripting (XSS) is a security exploit in which the attacker inserts malicious coding
into an link that appears to be from a trustworthy source. When someone clicks on the link, the
embedded programming is submitted as part of the client's Web request and can execute on the
user's computer, typically allowing the attacker to steal information.

Web forms that dynamically return an error message including user input data make it possible
for attackers to alter the HTML that controls the behavior of the form and/or the page.
Attackers do this in a number of ways, for example by inserting coding into a link in a forum
message or in a spam message. The attacker may use e-mail spoofing to pretend to be a trusted
source.

Like other Web-based exploits, such as SQL injection, much of the blame for cross-site
scripting is placed on the insecure applications that make it possible. Web server applications
that generate pages dynamically are vulnerable to a cross-site scripting exploit if they fail to
validate user input and to ensure that pages generated are properly encoded. A vulnerability
that enables cross-site scripting is sometimes referred to as an XSS hole.

To protect against cross-site scripting, experts recommend that Web applications should
include appropriate security mechanisms and servers should validate input as a matter of
course.

What is session hijacking?

Session hijacking, also known as TCP session hijacking, is a method of taking over a Web user
session by surreptitiously obtaining the session ID and masquerading as the authorized user.
Once the user's session ID has been accessed (through session prediction), the attacker can
masquerade as that user and do anything the user is authorized to do on the network.

The session ID is normally stored within a cookie or URL. For most communications,
authenticationprocedures are carried out at set up. Session hijacking takes advantage of that
practice by intruding in real time, during a session. The intrusion may or may not be detectable,
depending on the user's level of technical knowledge and the nature of the attack. If a Web site
does not respond in the normal or expected way to user input or stops responding altogether for
an unknown reason, session hijacking is a possible cause.

What is smarty?

Smarty is a template engine written in PHP. Typically, these templates will include variables
—such as {$variable}— and a range of logical and loop operators to allow adaptability within
of the template.

What is Model-view-controller (MVC)?


Model-view-controller (MVC) is a design pattern used in software engineering. In complex
computer applications that present lots of data to the user, one often wishes to separate data
(model) and user interface (view) concerns, so that changes to the user interface do not impact
the data handling, and that the data can be reorganized without changing the user interface. The
model-view-controller design pattern solves this problem by decoupling data access and
business logic from data presentation and user interaction, by introducing an intermediate
component: the controller.

Is it possible to pass data from JavaScript to PHP?

A. Yes, but not without sending another HTTP request.

B. Yes, because PHP executes before JavaScript.

C. No, because JavaScript is server-side, and PHP is client-side.

D. No, because JavaScript executes before PHP.

Answer A is correct.

Although your instincts might lead you to believe that you cannot pass data from JavaScript to
PHP, such a thing can be achieved with another HTTP request. Answer B is incorrect because
PHP executing before JavaScript is not what makes this possible.This is actually the
characteristic that might lead you to believe (incorrectly) that the answer is no. Answers C and
D are incorrect because the answer is yes, but also because the explanations given are false

what is session_start() ?

When a user first encounters a page in your application that call ssession start(),a sessionis
created for the user.PHP generates a random session identifier to identify the user,and then it
sends a set-Cookieheader to the client.By default,the name of this cookie is PHPSESSID,but it
is possible to change the cookiename in php.ini or by using the session name() function.On
subsequent visits,the client identifies the user with the cookie,and this is how thea application
maintains state.

What's foreign data in php?

* Anything from a form


* Anything from $_GET, $_POST, $_REQUEST
* Cookies ($_COOKIES)
* Web services data
* Files
* Some server variables (e.g. $_SERVER['SERVER_NAME'])
* Environment variables
* Database query results

Filter supports get, post, cookies, server and environment variables as well as defined variables
(server support may not work in all sapi, for filter 0.11.0 or php 5.2.0).

What is str_split function in php?

You are hereFind Your Answers / PHP Web Development Questions / What is str_split
function in php?

What is str_split function in php?


According to PHP official manual It is used to converts a string to an array.

If the optional split_length parameter is specified, the returned array will be broken down into
chunks with each being split_length in length, otherwise each chunk will be one character in
length. FALSE is returned if split_length is less than 1.

If the split_length length exceeds the length of string, the entire string is returned as the first
(and only) array element. Syntax: array str_split ( string string [, int split_length] );

Example

<?php
$strW3 = "Hello w3answers";

$arrW3 = str_split($strW3 );
$arrW3 = str_split($strW3 , 3);

print_r($arrW3);
print_r($arrW3);
?>

What is AJAX?

Asynchronous JavaScript and XML, is a web development technique for creating interactive
web applications. The intent is to make web pages feel more responsive by exchanging small
amounts of data with the server behind the scenes, so that the entire web page does not have to
be reloaded each time the user requests a change. This is meant to increase the web page's
interactivity, speed, and usability.

The Ajax technique uses a combination of:

* XHTML (or HTML) and CSS, for marking up and styling information.
* The DOM accessed with a client-side scripting language, especially ECMAScript
implementations such as JavaScript and JScript, to dynamically display and interact with the
information presented.
* The XMLHttpRequest object is used to exchange data asynchronously with the web server.
In some Ajax frameworks and in certain situations, an IFrame object is used instead of the
XMLHttpRequest object to exchange data with the web server, and in other implementations,
dynamically added <script> tags may be used.
* XML is sometimes used as the format for transferring data between the server and client,
although any format will work, including preformatted HTML, plain text, JSON and even
EBML. These files may be created dynamically by some form of server-side scripting.

Like DHTML, LAMP and SPA, Ajax is not a technology in itself, but a term that refers to the
use of a group of technologies.

Properties
************
Property Description

onreadystatechange Event handler that fires when the state of the request object changes.

readyState Returns values that indicate the current state of the object.

responseText String version of the response from the server.

responseXML DOM-compatible document object of the response from the server.

status Status code of the response from the server.

statusText Status message returned as a string.


Methods
***********

Method Description

Abort() Cancels the current HTTP request.

getAllResponseHeaders() Retrieves the values of all the HTTP headers.

getResponseHeader("headerLabel") Retrieves the value of an HTTP header from the response


body.

open("method", "URL"[, asyncFlag[, "userName"[, "password"]]]) Initializes an


MSXML2.XMLHTTP request, specifying the method, URL, and authentication information
for the request.

send(content) Sends an HTTP request to the server and receives a response.

setRequestHeader("label", "value") Specifies the name of an HTTP header.

Creating the Request Object


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

To create the request object, you must check whether the browser uses the XMLHttpRequest or
the ActiveXObject. The primary difference between the objects is the browsers that use them.
Windows IE 5 and above use the ActiveX object; Mozilla, Netscape 7, Opera, and Safari 1.2
and above use the XMLHttpRequest object. Another difference is the way in which you create
the objects: Opera, Mozilla, Netscape, and Safari allow you to simply call the objects'
constructor, but Windows IE requires the name of the object to be passed to the ActiveX
constructor. Following is an example of how to write the code to determine which object to use
and how to create it:

if(window.XMLHttpRequest)
{
request = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
request = new ActiveXObject("MSXML2.XMLHTTP");
}
What is meant by Exceptional Handling?

Exceptions PHP 5 has an exception model similar to that of other programming languages. An
exception can be thrown, try and caught within PHP. A Try block must include at least one
catch block. Multiple catch blocks can be used to catch different classtypes; execution will
continue after that last catch block defined in sequence.

Exceptions can be thrown within catch blocks. When an exception is thrown, code following
the statement will not be executed and PHP will attempt to find the first matching catch block.

If an exception is not caught a PHP Fatal Error will be issued with an Uncaught Exception
message, unless there has been a handler defined with set_exception_handler(). Throwing an
Exception

<?php
try {
$error = 'Always throw this error';
throw new Exception($error);

// Code following an exception is not executed.


echo 'Never executed';

} catch (Exception $e) {


echo 'Caught exception: ', $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>
Extending Exceptions A User defined Exception class can be defined by extending the built-in
Exception class.

The members and properties below, show what is accessible within the child class that derives
from the built-in Exception class. The Built in Exception class

<?php
class Exception
{
protected $message = 'Unknown exception'; // exception message
protected $code = 0; // user defined exception code
protected $file; // source filename of exception
protected $line; // source line of exception
function __construct($message = null, $code = 0);

final function getMessage(); // message of exception


final function getCode(); // code of exception
final function getFile(); // source filename
final function getLine(); // source line
final function getTrace(); // an array of the backtrace()
final function getTraceAsString(); // formated string of trace

/* Overrideable */
function __toString(); // formated string for display
}
?>
If a class extends the built-in Exception class and re-defines the constructor, it is highly
recomended that it also call parent::__construct() to ensure all available data has been properly
assigned.

The __toString() method can be overriden to provide a custom output when the object is
presented as a string. Extending the Exception class

<?php
/**
* Define a custom exception class
*/
class MyException extends Exception
{
// Redefine the exception so message isn't optional
public function __construct($message, $code = 0) {
// some code

// make sure everything is assigned properly


parent::__construct($message, $code);
}

// custom string representation of object */


public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}

public function customFunction() {


echo "A Custom function for this type of exception\n";
}
}

/**
* Create a class to test the exception
*/
class TestException
{
public $var;

const THROW_NONE = 0;
const THROW_CUSTOM = 1;
const THROW_DEFAULT = 2;

function __construct($avalue = self::THROW_NONE) {

switch ($avalue) {
case self::THROW_CUSTOM:
// throw custom exception
throw new MyException('1 is an invalid parameter', 5);
break;

case self::THROW_DEFAULT:
// throw default one.
throw new Exception('2 isnt allowed as a parameter', 6);
break;

default:
// No exception, object will be created.
$this->var = $avalue;
break;
}
}
}

// Example 1
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) { // Will be caught
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) { // Skipped
echo "Caught Default Exception\n", $e;
}
// Continue execution
var_dump($o);
echo "\n\n";

// Example 2
try {
$o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) { // Doesn't match this type
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) { // Will be caught
echo "Caught Default Exception\n", $e;
}

// Continue execution
var_dump($o);
echo "\n\n";

// Example 3
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (Exception $e) { // Will be caught
echo "Default Exception caught\n", $e;
}

// Continue execution
var_dump($o);
echo "\n\n";

// Example 4
try {
$o = new TestException();
} catch (Exception $e) { // Skipped, no exception
echo "Default Exception caught\n", $e;
}

// Continue execution
var_dump($o);
echo "\n\n";
?>
What is the difference between constructors in PHP4 & PHP5?

Constructors - PHP4 Constructors are functions in a class that are automatically called when
you create a new instance of a class with new. A function becomes a constructor, when it has
the same name as the class. If a class has no constructor, the constructor of the base class is
being called, if it exists.

<?php
class Auto_Cart extends Cart {
function Auto_Cart() {
$this->add_item("10", 1);
}
}
?>
This defines a class Auto_Cart that is a Cart plus a constructor which initializes the cart with
one item of article number "10" each time a new Auto_Cart is being made with "new".
Constructors can take arguments and these arguments can be optional, which makes them
much more useful. To be able to still use the class without parameters, all parameters to
constructors should be made optional by providing default values.
<?php
class Constructor_Cart extends Cart {
function Constructor_Cart($item = "10", $num = 1) {
$this->add_item ($item, $num);
}
}

// Shop the same old boring stuff.


$default_cart = new Constructor_Cart;

// Shop for real...


$different_cart = new Constructor_Cart("20", 17);
?>
You also can use the @ operator to mute errors occurring in the constructor, e.g. @new.
<?php
class A
{
function A()
{
echo "I am the constructor of A.<br />\n";
}

function B()
{
echo "I am a regular function named B in class A.<br />\n";
echo "I am not a constructor in A.<br />\n";
}
}

class B extends A
{
}

// This will call B() as a constructor


$b = new B;
?>
The function B() in class A will suddenly become a constructor in class B, although it was
never intended to be. PHP 4 does not care if the function is being defined in class B, or if it has
been inherited. PHP 4 doesn't call constructors of the base class automatically from a
constructor of a derived class. It is your responsibility to propagate the call to constructors
upstream where appropriate. Constructors - PHP5 void __construct ( [mixed args [, ...]] ) PHP
5 allows developers to declare constructor methods for classes.

Classes which have a constructor method call this method on each newly-created object, so it is
suitable for any initialization that the object may need before it is used.Parent constructors are
not called implicitly if the child class defines a constructor. In order to run a parent constructor,
a call to parent::__construct() within the child constructor is required. using new unified
constructors

<?php
class BaseClass {
function __construct() {
print "In BaseClass constructor\n";
}
}

class SubClass extends BaseClass {


function __construct() {
parent::__construct();
print "In SubClass constructor\n";
}
}

$obj = new BaseClass();


$obj = new SubClass();
?>
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it
will search for the old-style constructor function, by the name of the class.

Effectively, it means that the only case that would have compatibility issues is if the class had a
method named __construct() which was used for different semantics.

What is meant by Virtual hosting?

Virtual hosting

HTTP includes the concept of virtual hosting, where a single HTTP server can represent
multiple hosts at the same IP address.

A DNS server can allocate several different host names to the same IP address. When an HTTP
client makes a request to a particular host, it uses the DNS server to locate the IP address
corresponding to that host name, and sends the request to that IP address.

In HTTP/1.0 the host name did not appear in the HTTP message; it was lost after the IP address
had been resolved. This meant that if more than one set of resources was held on the server
represented by the IP address, the server would have difficulty distinguishing which resources
belonged to which host.

However, HTTP/1.1 requests provide the host name in the request (usually in a Host header).
The presence of the host name in the message enables the HTTP server to direct requests
containing different host names to the appropriate resources for each host. This feature of
HTTP is known as virtual hosting.

Where MyISAM table is stored ?

• Each MyISAM table is stored on disk in three files.


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

How many types of buffers does use MySQL?

You are hereFind Your Answers / MySQL Interview Questions / How many types of
buffers does use MySQL?

How many types of buffers does use MySQL?


global buffers and per-connection buffers
what is the use of –i-am-a-dummy flag in MySql?

You are hereFind Your Answers / MySQL Interview Questions / what is the use of –i-am-a-
dummy flag in MySql?

what is the use of –i-am-a-dummy flag in MySql?


It Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE
clause is not present.

what is database testing and what we test in database testing?

Database testing basically include the following.

1)Data validity testing.

2)Data Integritity testing

3)Performance related to data base.

4)Testing of Procedure,triggers and functions. for doing data validity testing you should be
good in SQL queries For data integrity testing you should know about referintial integrity and
different constraint. For performance related things you should have idea about the table
structure and design. for testing Procedure t

How can we take a backup of mysql table and restore it?

These are the simplest method to backup and restore the MySQl table

For taking the bakup of all the databases

mysqldump --user {user} --password {password} -A > {file name to dump}

To take the backup of a specific database

mysqldump --user {user} --password {password} dbname > {filename to dump}

To restore a SQL dump please use this

mysql --user {user} --password {password} dbName < {filename to restore}


Is it possible to set a time expire page in PHP.?

Yes it is

Using header("Expires: Mon, 26 Jul 2007 05:00:00 GMT");

<?php
header("Expires: Mon, 26 Jul 2007 05:00:00 GMT");
?>

www.w3answers.com

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.

www.w3answers.com

Tutoring Online - Cookies and Sessions

Hi my dear friends. Everybody knows what is cookie and session. But let me tell a truth, most
of the beginners don’t know properly what is happening in cookies and sessions and what is the
real use .I have taken so many Interviews but none of them given a good answer. I am very
much sure you are going to get a good idea about Sessions and Cookies. Let us start our
battle.:)

I am explaining only PHP syntax here. But the concept of Cookies and Sessions are same in all
Server Side Languages like ASP.NET, JSP,RUBYetc.except syntax and some rules

what is Cookie ?

“A cookie is a very small piece of data passed from a Webserver to visitors browser, where it is
saved to be sent back to the server whenever subsequent requests are made. When a Web
server sends data to a browser to be saved as a cookie, it’s said that the server is setting a
cookie” Cookies are stored either in the browser or in the Users hard disk (it creates a small text
file, if it is a Persistent Cookies. Ohh My God! what is Persistent Cookie’s. don’t worry we will
discuss later)

TIP-1

Setting Cookies in PHP First method-

header (); header ("Set-Cookie: W3answers=excellent; expires=$date; path=/");

header ("Set-Cookie: php=excellent; path=/; domain=$HTTP_HOST; expires=".gmstrftime


("%A, %d-%b-%Y %H:%M:%S GMT",time ()+100)); Second method-

Setcookie (); Send a cookie Both PHP4 and PHP5 supports

Third method-Setrawcookie ();

Send a cookie without urlencoding the cookie value (supports php5 only) You can use either
header or setcookie. But Security purpose PHP suggest to use setcookie

TIP-2

If we are passing anything before setcookie () or headers () we will be getting following


Warnings. Warning: Cannot add header information headers know with the message already
sent.

You can avoid this error message using

ob_start ();

Two Types of Cookies

1) Temporary Cookies

2) Persistent Cookies

Temporary Cookies –

these types of Cookies are stored in browser. If we close the browser Cookie deletes
automatically. How can we create Temporary Cookies in php setcookie (‘w3answers’,
‘phpqa’);
?> Here w3answers is the name of the Cookie and phpqa is the value.
Wow, you have created a Temporary Cookie. Where this Cookie creates and stores. This
Cookie is created by the server in your browser (remember it is not creating the file in the
user’s hard disk, which is the specialty of Temporary Cookies) .

So Temporary Cookies stores in your Browser.

Persistent Cookies Those cookies which are storing in users hardisk is called Persistent
Cookies. How can we create Persistent Cookies in php? To have a cookie expire 30 days from
the time its set, you take the time() and add 60 seconds in a current time stamp. The following
expire in 30 days: Setcookie (w3answers, phpqa, time() + 60*60*24*30); // sec/min * min/hr *
hrs/day * days

So what is the main difference between Temporary and Persistent Cookies?

If you want to create a Temporary Cookies avoid time ( ie don’t use expiry in setcookie
function) If you want to create a Persistent Cookies use expiry in the setcookie function (which
will be the third parameter of setcookie) setcookie(Session Active, true, time() + 60*15); //
secs*mins Notice that each time you set the cookie, the expiration value would Updated,
effectively allowing the session to stay active for as long as the user keeps accessing pages that
update the cookie with a new time Stamp. "In short, whenever you visit a Web site, your
browser checks to see if cookies are available in its cookie file that have been sent by that
server. If there are, the browser adds a note to the server in its request header say A cookie
called “user_id” was set with the value” someuser” in a a more technical way, of course. If
more than one cookie exists, they will all be sent back just like that". In the next part we will be
learning about “Keeping Cookies within Your Domain”,”Retriving Cookie” “Deleting
Cookies”, “ Cookie Myths”, “Sessions” and more.

Have a nice day

How we can pass data from PHP to ASP,ASP.net?

PHP to ASP

Let's first look at how you can pass data from PHP to ASP using WDDX.

You create a WDDX packet by first serializing data into a WDDX packet and then presenting
it.

WDDX can convert most variable types that applications use, such as strings, integers, and
arrays. After a variable has been converted to a WDDX variable type, it is ready for another
application to pick up.

PHP has WDDX support built in, so you don't need to modify your PHP.ini file to start using
WDDX.
A PHP Script to Serialize WDDX
<?php

//define PHP data to send


$ValueToSend = "Andrew";

//convert PHP data to WDDX data


$wddxvar = wddx_serialize_value("$ValueToSend");

//output WDDX data


print("$wddxvar");

?>
You first set the data you want to serialize into a WDDX packet:

$ValueToSend = "Andrew";
You then serialize that data:

$wddxvar = wddx_serialize_value("$ValueToSend");

Finally, you present that data as

print("$wddxvar");

********************************
O/P=Andrew
********************************

Internet Explorer just shows the data within the WDDX packet. It doesn't show the surrounding
XML structures. However, if you choose the view source option, you can see the WDDX
packet's XML structures

ASP Script to Deserialize WDDX Data

To receive the WDDX packet from the PHP script, you must load the packet

into a variable within the receiving ASP script. None of the WDDX implementations (the
WDDX COM component or PHP's WDDX functions) provides native ways of doing this. You
must add this functionality using separate code. After you receive the WDDX packet, you can
convert it into a data type native to the receiving application. This is called deserializing.

Using ASP, you can use a third-party COM component. A free COM component that allows
such functionality is ASP Tear from http://www.alphasier-rapapa.com/IisDev/Components/
(also included with the WDDX SDK). However, you can use any COM component that has
similar functionality.

<%

set aspget = Server.CreateObject("SOFTWING.AspTear")


set wddxob = Server.CreateObject("WDDX.Deserializer.1")

'get WDDX data


wddxdata = aspget.Retrieve("http://localhost/phpbook/Chapter5_Sessions/WDDX/PHP/
two_wddxserver.php", Request_POST, "", "", "")

'convert WDDX data to ASP data


wddxvar = wddxob.deserialize(wddxdata)

'output ASP data


response.write "Hello " & wddxvar

set wddxob = nothing


set aspget = nothing

%>

First, you must load the WDDX and ASP Tear COM objects into memory for use by ASP.
Don't worry too much if you are not familiar with using COM objects

set aspget = Server.CreateObject("SOFTWING.AspTear")


set wddxob = Server.CreateObject("WDDX.Deserializer.1")
Next you use ASP Tear to obtain the WDDX packet produced by the PHP

server and load it into a variable:

'get WDDX data


wddxdata = aspget.Retrieve("http://localhost/phpbook/Chapter5_Sessions/WDDX/PHP/
two_wddxserver.php", Request_POST, "", "", "")
You deserialize the WDDX packet into a native data type for ASP:

'convert WDDX data to ASP data


wddxvar = wddxob.deserialize(wddxdata)
You then output the value:

'output ASP data


response.write "Hello " & wddxvar
Finally, you unload the COM objects from memory:
set wddxob = nothing
set aspget = nothing
ASP to PHP
PHP can also receive WDDX packets. Here you will see a PHP script obtaining a WDDX
packet from an ASP script.

An ASP Script to Serialize WDDX


<%

'define ASP data to send


ValueToSend = "Andrew"

set wddxob = Server.CreateObject("WDDX.Serializer.1")

'convert ASP data to WDDX data


wddxvar = wddxob.serialize(ValueToSend)

'output WDDX data


response.write wddxvar

set wddxob = nothing

%>
This is very much the same as the serializing PHP script. First, you define the value you want
to serialize in WDDX:

'define ASP data to send


ValueToSend = "Andrew"
You then load the WDDX COM object into memory, ready for use by ASP:

set wddxob = Server.CreateObject("WDDX.Serializer.1")


You then serialize the value into a WDDX packet:

'convert ASP data to WDDX data


wddxvar = wddxob.serialize(ValueToSend)
You then display the WDDX packet:

'output WDDX data


response.write wddxvar
Finally, you unload the WDDX COM object from memory:

set wddxob = nothing

A PHP Script to Deserialize WDDX Data


The deserialize PHP script needs to do the same as the deserialize ASP script: It must convert
the WDDX packet back into a native variable type for our script (in this case, a native variable
type for PHP):

<?php
//get WDDX data
$wddxdata = join ('', file
('http://localhost/phpbook/Chapter5_Sessions/WDDX/ASP/one_wddxserver.asp'));

//convert WDDX data to PHP data


$wddxvar = wddx_deserialize("$wddxdata");
//output PHP data
print("Hello " . $wddxvar);
?>

You can obtain the WDDX packet from the ASP script using the PHP join function. To use the
function in this manner, you must make sure that HTTP transparency is enabled in the PHP.ini
settings file (the allow_url_fopen setting is enabled). (Note that HTTP transparency is enabled
by default.)

$wddxdata = join ('', file


('http://localhost/phpbook/Chapter5_Sessions/WDDX/ASP/one_wddxserver.asp'));
As before, you deserialize the WDDX packet into a native variable type:

$wddxvar = wddx_deserialize("$wddxdata");
You then display the WDDX packet:

print("Hello " . $wddxvar);

Which of the following represents the proper way to set a session variable?

A. $_SESSION[‘foo’] = ‘bar’;
B. session_start();
C. session_set_save_handler (‘myopen’, ‘myclose’, ‘myread’,
‘mywrite’, ‘mydelete’, ‘mygarbage’);
D. $foo = $_SESSION[‘foo’];

Answer A is correct.

Answer B is incorrect because session_start() only activates PHP sessions for the current script.
Answer C is incorrect because session_set_save_handler() allows you to override PHP’s
default session mechanism with your own custom functions. Answer D is incorrect; session
data is being used as the value of a regular variable and is not being manipulated in any
way.

PHP Functions for WDDX

PHP has a few other functions that can be useful when you're working with WDDX:

<?php

$names = array("Andrew", "Emma");


$name2 = "Terry";
$name3 = "Mary";
$name4 = "Thomas";
$wddxpack = wddx_packet_start("PHP-WDDX");

wddx_add_vars($wddxpack, "names");

wddx_add_vars($wddxpack, "name2");
wddx_add_vars($wddxpack, "name3");
wddx_add_vars($wddxpack, "name4");

$wddxvar = wddx_packet_end($wddxpack);

//output WDDX data


$wddx_out = wddx_deserialize($wddxvar);

//iterate through PHP array

while (list($key, $val) = each($wddx_out["names"])) {


print "$val\n<BR>";
}

print($wddx_out["name2"] . "<br>");
print($wddx_out["name3"] . "<br>");
print($wddx_out["name4"] . "<br>");

?>
PHP lets you modify the contents of a WDDX packet so that you can add and delete the
contents of a WDDX packet as you see fit. To show this, you first create a PHP array
containing the first two items in the packet:
$names = array("Andrew", "Emma");
You then create the other items that make up the WDDX packet:

$name2 = "Terry";
$name3 = "Mary";
$name4 = "Thomas";
You then create the WDDX packet:

$wddxpack = wddx_packet_start("PHP-WDDX");
You then add the items to the WDDX packet and close it:

wddx_add_vars($wddxpack, "names");

wddx_add_vars($wddxpack, "name2");
wddx_add_vars($wddxpack, "name3");
wddx_add_vars($wddxpack, "name4");

$wddxvar = wddx_packet_end($wddxpack);
If you look at the contents of the WDDX packet, you can see how PHP has built it:

<struct>
<var name='names'>
<array length='2'>
<string>Andrew</string>
<string>Emma</string>
</array>
</var>
<var name='name2'>
<string>Terry</string>
</var>
<var name='name3'>
<string>Mary</string>
</var>
<var name='name4'>
<string>Thomas</string>
</var>
</struct>
It's interesting to note that PHP adds each data type (the array and other elements) separately to
the WDDX packet. Also note that PHP uses named references for each data element added to
the WDDX packet, such as names for the array, name2 for "Terry", and so on.

$wddx_out = wddx_deserialize($wddxvar);
You deserialize the WDDX packet as normal. Because there are different data types within the
WDDX packet, PHP handles the deserialized data differently. For the array, you use the list
function that you used in the previous example:

while (list($key, $val) = each($wddx_out["names"])) {


print "$val\n<BR>";
}
For the other data types, you use the reference contained in the WDDX file:

print($wddx_out["name2"] . "<br>");
print($wddx_out["name3"] . "<br>");
print($wddx_out["name4"] . "<br>");
In effect, what is returned to PHP from the WDDX packet is a hash array (or named array).
Each element in the array takes its named value from the reference in the WDDX packet

How to capture content from the output buffer ? or Give me an example for Output
caching in php?
<?php
ob_start(); // start an output buffer
echo ‘This text is from the w3answers buffer*******<br />’; // output that will be stored in the
buffer
$w3buffer = ob_get_contents(); // store buffer content in $w3buffer variable
ob_end_clean(); // stop and clean the output buffer
echo ‘This is not from the w3answers buffer!!!!!!!!<br />’;
echo $w3buffer;
?>
How can we extract string "w3answers.com" from a string mailto:info@w3answers.com
using regular expression of PHP ?

Answer:
<?php
$w3 = "mailto:info@w3answers.com";
preg_match('|.*@([^?]*)|',$w3,$w3output);
echo $w3output[1];
?>

which is faster mysql_unbuffered_query or mysql_query ?

when we do the select queries that retrieve large data sets from MySQL,
mysql_unbuffered_query in PHP is likely to give better performance than mysql_query.

PHP manual says,


it “sends a SQL query query to MySQL, without fetching and buffering the result rows
automatically”

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 to determine the number of rows in the full result set and also restrict the number of
rows that a query returns,without running a second query ?

Most of the developers using 2 queries to find total number of rows and limit,when
we need pagination(1,2,3,4). why should we write 2 queries to find limit as well as total
number of rows in a table. we can achieve this in a single query.

eg:
SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
WHERE id > 567 LIMIT 10;

So SQL_CALC_FOUND_ROWS can be useful in situations when you want to restrict the


number of rows that a query returns, but also determine the number of rows in the full result set
without running the query again.

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

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

What are the 'function problems' you have met in php?

1)Call to undefined function we_w3answers()

PHP is trying to call the function we_w3answers(), which has not been because you misspelled
the name of a function (built-in or user-defined) simply omitted the function definition. If you
use include/require functions, make sure that you are loading the appropriate files.

2)Call to undefined function array()


This problem has a cause that is similar to the cause of the previous problem, although it still
baffled us completely the first time we ran into it. It can arise when you have code like the
following:

$my_w3answers= array();
$my_w3answers(5) = “the fifth”;

3)Cannot redeclare my_function()

This is a simple one—somewhere in your code you have two definitions of my_function(),
which PHP will not stand for. Make sure that you are not using include to pull in the same file
of function definitions more than once. Use include_once or require_once to avoid

4)Wrong parameter count

Explain Parse Errors ? what are the most common causes of parse errors ?
The most common category of error arises from mistyped or syntactically incorrect PHP code,
which confuses the PHP parsing engine.

what is the php solution to dynamic caching ?


PHP offers an extremely simple solution to dynamic caching in the form of output buffering.

what are the most common caching policy approaches ?

1)Time triggered caching (expiry timestamp).

2)Content change triggered caching (sensitive content has changed, so cache must be updated).

3)Manually triggered caching (manually inform the application that information is outdated,
and force a new cache creation).

Are php strings immutable ?

PHP strings can be changed, but the most common practice seems to be to treat strings as
immutable.Strings can be changed by treating them as character arrays and assigning directly
into them, like this:

<?php
$my_string = “abcdefg”;
$my_string[5] = “X”;
print($my_string . “<BR>”);
?>
which will give the browser output:abcdeXg
What is Memcache?
Memcache is a technology which caches objects in memory where your web application can
get to them really fast. It is used by sites such as Digg.com, Facebook.com and NowPublic.com
and is widely recognized as an essential ingredient in scaling any LAMP application to handle
enormous traffic.

How do I prevent Web browsers caching a page in php?


<?php
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Pragma: no-cache');
?>

What is the process that takes place when you upload a file in php?

There are two basic things covered here. The form that will be used to post the file data to and
the actual program that does the uploading. Further we will discuss the method that PHP itself
suggests for uploading files. Process 1 HTML PART

<form enctype="multipart/form-data" action="__URL__" method="POST">


<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Upload a file: <input name="smefile" type="file" />
<input type="submit" value="Upload" />
</form>

Note the enctype is set to "multipart/form-data". This is crucial to the working of the
application. If it is not specified here then the program will not work. Next you'll notice that
MAX_FILE_SIZE precedes the file input field. The MAX_FILE_SIZE for this demonstration
is limited to 30000 bytes, or about 29K, but can easily be modified for larger files. Finally you
have the input sections. The first is set to create an input box that allows the user to choose his
file and the second is the button that actually submits the file for upload. In the next section
you'll notice that the name of the input element for type="file" will be used to determine the
name to pull from the $_FILES array. Form Method must be POST Process 2 PHP PART
<?php
$imgdir = '/imgdir/';
$uploadfile = $imgdir. basename($_FILES['smefile']['name']);
if (move_uploaded_file($_FILES[ 'smefile']['tmp_name'], $uploadfile)) {
echo "File successfully uploaded";
} else {
echo "Upload failed";
}
?>

How to get the contents of a web page using php?

you can achieve this using curl in php

see the example below.

<?php
function curl_get_con_url($url, $user_agent = '', $referer = '') {
// create a new CURL resource
$ch = curl_init();

// set URL and other appropriate options


curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);

/* This lines will make sure that you can save the web page into a variable */
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);


curl_setopt($ch, CURLOPT_REFERER, $referer);

// grab URL
$page_content = curl_exec($ch);

if (curl_errno($ch)) {
$page_content = false;
}

// close CURL resource, and free up system resources


curl_close($ch);

return $page_content;
}

$referads_pc = curl_get_con_url('www.referads.com');
?>
what are the security tips you should know before developing php/mysql web pages ?

1. Do not trust user input.


2. Validate user input on the server side.
3. Do not use user input directly in your MySQL queries.
4. Don't put integers in quotes In your MySQL queries.
5. Always escape the output using php built in functions.
6. When uploading files, validate the file mime type using php.
7. If you are using 3rd party code libraries, be sure to keep them up to date.
8. Give your database users just enough permissions.
9. Do not allow hosts other than localhost to connect to your database.
10. Your library file extensions should be PHP.
11. Have register globals off or define your variables first
12. Keep PHP itself up to date (use latest version php5 or above)

what are the database space-saving functions available in php ?

# Use ip2long() and long2ip() to store the IP adresses as Integers instead of storing them as
strings, which will reduce the space from 15 bytes to 4 bytes. This will also increase search
speed and make it easy to see if a ip falls within a specified range.

# Use gzcompress() and gzuncompress() to reduce the strings before you store them in a
database. The gzcompress can compress plain-text up to 90%. The only reason why you
shouldn’t use it is when you need full-text indexing capabilities.

what are the advantages of storing sessions in database?

If you store a session in a database you have several advantages:

• @ Improving the security because on many hosting packages (shared host)


• PHP uses the same path for storing sessions for all the users,somewhere that is not in
your folders.
• @ You can track who is online etc.
• @ For application that are running on multiple servers, you can store
• all the session data in one database.

The real beauty of this approach is that you don't have to modify your code or the way you use
sessions in any way. $_SESSION still exists and behaves the same way, PHP still takes care of
generating and propagating the session identifier, and changes made to session configuration
directives still apply. All you have to do is call this one function.
You must call session_set_save_handler() prior to calling session_start(), but you can define
the functions themselves anywhere.

The function is called session_set_save_handler(), and it takes six arguments,

1. Opening the session data store


2. Closing the session data store
3. Reading session data
4. Writing session data
5. Destroying all session data
6. Cleaning out old session data

what you should know about cookies before start using in php?

There are a few things you should be aware of:

1. Since cookies are used to record information about your activities on a particular domain,
they can only be read by the domain that created them

2. A single domain cannot set more than twenty cookies, and each cookie is limited to a
maximum size of 4 KB

3. A cookie usually possesses six attributes, of which only the first is mandatory. Here they are:
* name: the name of the cookie
* value: the value of the cookie
* expires: the date and time at which the cookie expires
* path: the top-level directory on the domain from which cookie data can be accessed
* domain: the domain for which the cookie is valid
* secure: a Boolean flag indicating whether the cookie should be transmitted only over a secure
HTTP connection

It's important to remember that, since cookies are stored on the user's hard drive, you as the
developer have very little control over them. If a user decides to turn off cookie support in his
or her browser, your cookies will simply not be saved. Therefore, avoid writing code that
depends heavily on cookies; and have a backup plan ready in case cookie data cannot be
retrieved from the client.

Two types of cookies

1) temporary and
2) persistent cookies
what are the ways to check image mime types in php?

There are a few inbuilt options you can use however, for example getimagesize() can return the
mimetype, as does some of the new fileinfo functions. The mime type in getimagesize is stored
in 'mime', and can be accessed as shown below.
<?php
$parts = getimagesize($filename);
echo $parts['mime'];
?>
or
<?php
$parts = getimagesize($filename);
$allowedMimes = array('image/jpg', 'image/png', 'image/gif');
if(in_array($parts['mime'], $allowedMimes))
echo 'Valid Mimetype!';?>

other way

<?php
$filename = 'maliciousScript.jpg.php'; // filename to check
$parts = explode('.', $filename); // common (but wrong) method used
echo $parts[1];
echo strrchr($filename, '.'); // correct method
?>
<?php
echo system('file -ib '. $filename);
?>

How many HTTP headers will send to a web page(client side) from server when you use
sessions (session_start()) in php ?

There are three HTTP headers included in the response:

Expires: Thu, 19 Nov 1981 08:52:00 GMT

Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0

Pragma: no-cache

What API function provides the connection between the client and server?

ANS:XMLHttpRequest
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 idem potency recommendations and is highly recommended
for a consistent web application architecture.

what is ajax? when ajax was born?

"AJAX is an acronym for Asynchronous JavaScript and XML. If you think it doesn't say much,
we agree. Simply put, AJAX can be read "empowered JavaScript", because it essentially offers
a technique for client-side JavaScript to make background server calls(such as from
PHP,ASP.NET,JSP,RUby etc) and retrieve additional data as needed, updating certain portions
of the page without causing full page reloads".

The XMLHttpRequest object enables JavaScript to access the server asynchronously, so that
the user can continue working, while functionality is performed in the background.

The name AJAX was born in 2005, in Jesse James Garret's article at
http://www.adaptivepath.com/publications/essays/archives/ 000385.php,
and gained much popularity when used by Google in many of its applications.

You might also like