php interview questions and answers

43
PHP interview questions and answers By admin | December 12, 2005 1. What does a special set of tags <?= and ?> do in PHP? - The output is displayed directly to the browser. 2. What’s the difference between include and require? - It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue. 3. I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem? - PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems. 4. Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example? - In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like "{$a},000,000 mln dollars", then you definitely need to use the braces. 5. How do you define a constant? - Via define() directive, like define ("MYCONSTANT", 100); 6. How do you pass a variable by value? - Just like in C++, put an ampersand in front of it, like $a = &$b 7. Will comparison of string "10" and integer 11 work in PHP? - Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared. 8. When are you supposed to use endif to end the conditional statement? - When the original if was followed by : and then the code block without braces. 9. Explain the ternary conditional operator in PHP? - Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed. 10. How do I find out the number of parameters passed into function? - func_num_args() function returns the number of parameters passed in. 11. If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b? - 100, it’s a reference to existing variable. 12. What’s the difference between accessing a class method via - > and via ::? - :: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization.

Upload: dolphin-rajesh

Post on 06-Apr-2015

528 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: PHP Interview Questions and Answers

PHP interview questions and answersBy admin | December 12, 2005

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

2. What’s the difference between include and require? - It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

3. I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem? - PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.

4. Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example? - In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like "{$a},000,000 mln dollars", then you definitely need to use the braces.

5. How do you define a constant? - Via define() directive, like define ("MYCONSTANT", 100);

6. How do you pass a variable by value? - Just like in C++, put an ampersand in front of it, like $a = &$b

7. Will comparison of string "10" and integer 11 work in PHP? - Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.

8. When are you supposed to use endif to end the conditional statement? - When the original if was followed by : and then the code block without braces.

9. Explain the ternary conditional operator in PHP? - Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.

10.How do I find out the number of parameters passed into function? - func_num_args() function returns the number of parameters passed in.

11.If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b? - 100, it’s a reference to existing variable.

12.What’s the difference between accessing a class method via -> and via ::? - :: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization.

13.Are objects passed by value or by reference? - Everything is passed by value.

14.How do you call a constructor for a parent class? - parent::constructor($value)

15.What’s the special meaning of __sleep and __wakeup? - __sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.

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

Page 2: PHP Interview Questions and Answers

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

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

18.How come the code <?php print "Contents: $arr[1]"; ?> works, but <?php print "Contents: $arr[1][2]"; ?> doesn’t for two-dimensional array of mine? - Any time you have an array with more than one dimension, complex parsing syntax is required. print "Contents: {$arr[1][2]}" would’ve worked.

19.What is the difference between characters 23 and x23? - The first one is octal 23, the second is hex 23.

20.With a heredoc syntax, do I get variable substitution inside the heredoc contents? - Yes.

21.I want to combine two variables together:22. $var1 = 'Welcome to ';

23. $var2 = 'TechInterviews.com';

What will work faster? Code sample 1:$var 3 = $var1.$var2;

Or code sample 2:$var3 = "$var1$var2";

Both examples would provide the same result - $var3 equal to "Welcome to TechInterviews.com". However, Code Sample 1 will work significantly faster. Try it out with large sets of data (or via concatenating small sets a million times or so), and you will see that concatenation works significantly faster than variable substitution.

24.For printing out strings, there are echo, print and printf. Explain the differences. - echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like: <?php echo 'Welcome ', 'to', ' ', 'TechInterviews!'; ?>

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

Page 3: PHP Interview Questions and Answers

25.I am writing an application in PHP that outputs a printable version of driving directions. It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters. How do I accomplish that with PHP? - On large strings that need to be formatted according to some length specifications, use wordwrap() or chunk_split().

26.What’s the output of the ucwords function in this example?27. $formatted = ucwords("TECHINTERVIEWS IS COLLECTION OF

INTERVIEW QUESTIONS");

print $formatted;

What will be printed is TECHINTERVIEWS IS COLLECTION OF INTERVIEW QUESTIONS.ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it’s worth usingstrtolower() first.

28.What’s the difference between htmlentities() and htmlspecialchars()? - htmlspecialchars only takes care of <, >, single quote ‘, double quote " and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.

29.What’s the difference between md5(), crc32() and sha1() crypto on PHP? - The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.

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

31. How do you match the character ^ at the beginning of the string? - ^^

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}

Page 4: PHP Interview Questions and Answers

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}

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 triggers and functions you should be able to understand the same.

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,

Page 5: PHP Interview Questions and Answers

What is the difference between CHAR and VARCHAR data types?

Ans:

CHAR is a fixed length data type.

CHAR(n) will take n characters of storage even if you enter less than n characters to that column. For

example, "answers" will be stored as "answers " in CHAR(10) column.

VARCHAR is a variable length data type.

VARCHAR(n) will take only the required storage for the actual number of characters entered to that

column. For example, "answers" will be stored as "answers" in VARCHAR(10) column.

What is str_split function in php?

According to PHP official manual

 

It is used to converts a string to an array. If the optionalsplit_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_lengthlength 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);

?>

Page 6: PHP Interview Questions and Answers

OUT OUT:- Array ( [0] =>Submitted by Susanta (not verified) on Fri, 05/15/2009 - 06:09.

$variable = "MY NAME IS SUSANTA";

print_r(str_split($variable));

?>

OUT OUT:-

Array

(

[0] => M

[1] => Y

[2] =>

[3] => N

[4] => A

[5] => M

[6] => E

[7] =>

[8] => I

[9] => S

[10] =>

[11] => S

[12] => U

[13] => S

[14] => A

[15] => N

[16] => T

[17] => A

)

reply

OUT OUT:- Array ( [0] =>Submitted by Susanta (not verified) on Fri, 05/15/2009 - 06:08.

$variable = "MY NAME IS SUSANTA";

print_r(str_split($variable));

?>

OUT OUT:-

Array

(

[0] => M

[1] => Y

[2] =>

[3] => N

[4] => A

Page 7: PHP Interview Questions and Answers

[5] => M

[6] => E

[7] =>

[8] => I

[9] => S

[10] =>

[11] => S

[12] => U

[13] => S

[14] => A

[15] => N

[16] => T

[17] => A

)

What is the Use of "WITH ROLLUP" in Mysql?

www.w3answers.com

Adding a WITH ROLLUP modifier to the GROUP BY clause causes the query to produce another row.

eg:

mysql> SELECT year, SUM(profit) FROM sales GROUP BY year WITH ROLLUP;

+------+-------------+

| year | SUM(profit) |

+------+-------------+

| 2000 | 4525 |

| 2001 | 3010 |

| NULL | 7535 | <<<- Note here* 

+------+-------------+

So an extra row (<<<- Note here*) is created by mysql and also we get total profit

in the last column.

Is MySQL better than MSSQL ?

Mysql is the most popular open source database server right now. It is used by large enteprise level

companies and small, single websites. Is mysql actually better?

Page 8: PHP Interview Questions and Answers

---------------------------------

Mysql 5.0 vs. Microsoft SQL 2005

---------------------------------

Features

* Mysql 5.X now offers support for cursors, complete views, and stored procedures. However, Foreign

Key support is still in its early stages.

* SQL 2005 has native support for xml, multi-dimensional data querying, and Visual Studio .net

integration.

Cost

* Microsoft provides a free license for development use. $1400 for a commercial license.

* Mysql is free ($0) for commercial and non-commerical use. It is also possible to purchase a

commerical license (to get around the GPL license) for $400.

Performance

* Mysql: MyISAM database table type uses less space and memory. Innodb and NDB clusters also now

use 20% less space (new to 5.0).

* SQL 2005: needs more disk storage and memory requirements.

Replication

* Mysql: One way replication using a binary log, which can easily be replicated to multile machines.

* SQL 2005: Multiple forms of replication (snapshot,transactional, and merge), which are more complex

and offers a greater degrees of flexibility.

Recovery

* SQL 2005: Very robust. There are multiple failsafes in place to prevent data loss. New features in this

version also allow rapid restoration and data protection.

* Mysql: Falls very short in this respect. An unexpected shutdown of your server can cause data loss.

How many types of buffers does use MySQL?

global buffers and per-connection buffers

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

There are two methods

Page 9: PHP Interview Questions and Answers

AES_ENCRYPT () and AES_DECRYPT ()

How do you convert an old fashioned 10 digit ISBN to a new 13 digit ISBN using php ?

function isbn10_to_13($isbnold){

if (strlen($isbnold) != 10){ // Make sure we have a 10 digit string to start

return 'Invalid ISBN-10, must be 10 digits';

}

// prefix with 978 and drop old checksum (last digit)

$isbn = '978'.substr($isbnold,0,9);

for ($i = 0; $i <= 12; $i++){ // For each digit if new isbn

$weight = ($i%2 == 0)? 1 : 3; // Alternate between 1's and 3's

$check_sum_total = $check_sum_total + ($isbn{$i} * $weight); // multiply each digit by 1 or 3 and add

to $checksumtotal

}

$new_check_sum = 10 - ($check_sum_total%10); // Modulus 10 business

return ($isbn.$new_check_sum); //add checksum on to end and return

}

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

Page 10: PHP Interview Questions and Answers

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.

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 meant by PEAR in php?

PEAR PHP Extension and Application Repository

PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR

is a framework and distribution system for reusable PHP components. It eases installation by bringing

an automated wizard, and packing the strength and experience of PHP users into a nicely organised

OOP library.

What is the difference between GET and POST methods in form submitting? Give the cases where we can use GET and POST methods?

The main difference between GET and POST is how the form data is passing. Both are used for passing

form field values.

All the values which is submitted by the GET method will be appended to the URL.

Where as POST method send the data with out appending the URL(hidden)

In GET Method we can bookmark the URLs where as in POST method its not possible

In GET Method there is a limit for passing the data from one page to another(ie 256 characters

according to w3c standards)

But in POST we can send large amount of data

Compared to POST get is Faster

Page 11: PHP Interview Questions and Answers

POST is more secure than get method

If you refersh the page , POST method shows an annoying alert box

Some firewalls doesnt allow POST methods.

All the informations which is passed by GET method will be stored in webserver(log file) but in POST we

can not

How can we submit a form without a submit button?

We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code,

we can call the document.form.submit() function to submit the form

What is the difference between mysql_fetch_object and mysql_fetch_array?You can't request more than 20 challenges without solving them. Your previous challenges were

flushed.

Returns an object with properties that correspond to the fetched row and moves the internal data

pointer ahead.

mysql_fetch_object() example

<?php

mysql_connect("hostname", "user", "password");

mysql_select_db("mydb");

$result = mysql_query("select * from mytable");

while ($row = mysql_fetch_object($result)) {

echo $row->user_id;

echo $row->fullname;

}

mysql_free_result($result);

?>

mysql_fetch_object() example

<?php

$row = mysql_fetch_object($result);

/* this is valid */

echo $row->field;

Page 12: PHP Interview Questions and Answers

/* this is invalid */

// echo $row->0;

?>

mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both

Example

<?php

mysql_connect("localhost", "mysql_user", "mysql_password") or

die("Could not connect: " . mysql_error());

mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

printf("ID: %s Name: %s", $row["id"], $row["name"]);

}

mysql_free_result($result);

?> 

 

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

Page 13: PHP Interview Questions and Answers

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.

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.

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

Page 14: PHP Interview Questions and Answers

}

}

?>

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

{

}

Page 15: PHP Interview Questions and Answers

// 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 PHP?

Page 16: PHP Interview Questions and Answers

PHP: Hypertext Preprocessor, an open source, server-side, HTML embedded scripting language used to

create dynamic Web pages.

In an HTML document, PHP script (similar syntax to that of Perl or C ) is enclosed within special PHP

tags. Because PHP is embedded within tags, the author can jump between HTML and PHP (similar to

ASP and Cold Fusion) instead of having to rely on heavy amounts of code to output HTML. And,

because PHP is executed on the server, the client cannot view the PHP code.

PHP can perform any task that any CGI program can do, but its strength lies in its compatibility with

many types of databases. Also, PHP can talk across networks using IMAP, SNMP, NNTP, POP3, or HTTP.

PHP was created sometime in 1994 by Rasmus Lerdorf. During mid 1997, PHP development entered

the hands of other contributors. Two of them, Zeev Suraski and Andi Gutmans, rewrote the parser from

scratch to create PHP version 3 (PHP3).

What can PHP do?

Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI

program can do, such as collect form data, generate dynamic page content, or send and receive

cookies. But PHP can do much more.

There are three main areas where PHP scripts are used.

Server-side scripting. This is the most traditional and main target field for PHP. You need three things

to make this work. The PHP parser (CGI or server module), a webserver and a web browser. You need

to run the webserver, with a connected PHP installation. You can access the PHP program output with a

web browser, viewing the PHP page through the server. All these can run on your home machine if you

are just experimenting with PHP programming.

Command line scripting. You can make a PHP script to run it without any server or browser. You only

need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using

cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text

processing tasks.

Writing desktop applications. PHP is probably not the very best language to create a desktop

application with a graphical user interface, but if you know PHP very well, and would like to use some

advanced PHP features in your client-side applications you can also use PHP-GTK to write such

programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an

extension to PHP, not available in the main distribution.

PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX,

Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also

support for most of the web servers today. This includes Apache, Microsoft Internet Information Server,

Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami,

Page 17: PHP Interview Questions and Answers

OmniHTTPd, and many others. For the majority of the servers PHP has a module, for the others

supporting the CGI standard, PHP can work as a CGI processor.

So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore,

you also have the choice of using procedural programming or object oriented programming, or a

mixture of them. Although not every standard OOP feature is implemented in PHP 4, many code

libraries and large applications (including the PEAR library) are written only using OOP code. PHP 5

fixes the OOP related weaknesses of PHP 4, and introduces a complete object model.

With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and

even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text,

such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file

system, instead of printing it out, forming a server-side cache for your dynamic content.

One of the strongest and most significant features in PHP is its support for a wide range of databases.

Writing a database-enabled web page is incredibly simple. The following databases are currently

supported:

Adabas D InterBase PostgreSQL

dBase FrontBase SQLite

Empress mSQL Solid

FilePro (read-only) Direct MS-SQL Sybase

Hyperwave MySQL Velocis

IBM DB2 ODBC Unix dbm

Informix Oracle (OCI7 and OCI8)

Ingres Ovrimos

We also have a database abstraction extension (named PDO) allowing you to transparently use any

database supported by that extension. Additionally PHP supports ODBC, the Open Database

Connection standard, so you can connect to any other database supporting this world standard.

PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP,

POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and

interact using any other protocol. PHP has support for the WDDX complex data exchange between

virtually all Web programming languages. Talking about interconnection, PHP has support for

instantiation of Java objects and using them transparently as PHP objects. You can also use our CORBA

extension to access remote objects.

PHP has extremely useful text processing features, from the POSIX Extended or Perl regular

expressions to parsing XML documents. For parsing and accessing XML documents, PHP 4 supports the

SAX and DOM standards, and you can also use the XSLT extension to transform XML documents. PHP 5

standardizes all the XML extensions on the solid base of libxml2 and extends the feature set adding

SimpleXML and XMLReader support.

Page 18: PHP Interview Questions and Answers

At last but not least, we have many other interesting extensions, the mnoGoSearch search engine

functions, the IRC Gateway functions, many compression utilities (gzip, bz2, zip), calendar conversion,

translation...

PHP Interview Questions And Answers Set - 1 

What's PHP ?The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.What Is a Session?A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.

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

Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.What is meant by PEAR in php?Answer1:PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install "packages"

Answer2:PEAR is short for "PHP Extension and Application Repository" and is pronounced just like the fruit. The purpose of PEAR is to provide:A structured library of open-sourced code for PHP usersA system for code distribution and package maintenanceA standard style for code written in PHPThe PHP Foundation Classes (PFC),The PHP Extension Community Library (PECL),A web site, mailing lists and download mirrors to support the PHP/PEAR communityPEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then.How can we know the number of days between two given dates using PHP?Simple arithmetic:

$date1 = date('Y-m-d');$date2 = '2006-07-01';$days = (strtotime() - strtotime()) / (60 * 60 * 24);echo "Number of days since '2006-07-01': $days";What is the difference between $message and $$message?Anwser 1:$message is a simple variable whereas $$message is a reference variable. Example:

Page 19: PHP Interview Questions and Answers

$user = 'bob'

is equivalent to

$holder = 'user';$$holder = 'bob';

Anwser 2:They are both variables. But $message is a variable with a fixed name. $$message is a variable who's name is stored in $message. For example, if $message contains "var", $$message is the same as $var.What Is a Persistent Cookie?A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:*Temporary cookies can not be used for tracking long-term information.*Persistent cookies can be used for tracking long-term information.*Temporary cookies are safer because no programs other than the browser can access them.*Persistent cookies are less secure because users can open cookie files see the cookie values.What does a special set of tags <?= and ?> do in PHP?The output is displayed directly to the browser.  How do you define a constant?Via define() directive, like define ("MYCONSTANT", 100);What are the differences between require and include, include_once?Anwser 1:require_once() and include_once() are both the functions to include and evaluate the specified file only once. If the specified file is included previous to the present call occurrence, it will not be done again.

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

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

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

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

Page 20: PHP Interview Questions and Answers

What is the difference between mysql_fetch_object and mysql_fetch_array?MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an arrayHow can I execute a PHP script using command line?Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, "php myScript.php", assuming "php" is the command to invoke the CLI program.Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what?s the problem?PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example?In this example it wouldn?t matter, since the variable is all by itself, but if you were to print something like "{$a},000,000 mln dollars", then you definitely need to use the braces.What are the different tables present in MySQL? Which type of table is generated when we are creating a table in the following syntax: create table employee(eno int(2),ename varchar(10))?Total 5 types of tables we can create1. MyISAM2. Heap3. Merge4. INNO DB5. ISAMMyISAM is the default storage engine as of MySQL 3.23. When you fire the above create query MySQL will create a MyISAM table.

1. How do you access data submitted through GET or POST from a form?

To access data use $_GET and $_POST respectively. For instance if a form is submitted with a field named 'email' through post, then this becomes available as $_POST[email].

With GET, the information is posted in the URL so this is useful if you want to store or bookmark a URL that relies on parameterised data. However GET is less secure, and also has strict limits on the amount of data that can be sent.

2. Write a simple program to get a row of information from a database?

$myrow = mysql_query("SELECT name,email FROM visitors ORDER by name LIMIT 1");$data = mysql_fetch_row($myrow); $name = $data[0]; $email = $data[1]; echo "A row from the database is name $name and email $email";

Page 21: PHP Interview Questions and Answers

3. What is the difference between include and require?

If you require a file and it cannot be found, the script will terminate with a fatal error. If you use include then you will get an error but the script will continue to execute. Therefore when the information you wish to reference from another file is essential to the correct running of a page, use require.

4. How do you remove the last letter from a string?

There are many ways to do this. An interviewer will be looking for you to use a compact method. Here is probably the simplest method:

$data = "One too many letterss"; $newdata = substr($data,0,-1);// now 'one too many letters'

5. What do you need to use the image functions in PHP?

You need to have access to the GD Library in order to use the image functions in PHP.

PHP Interview questions

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

Page 22: PHP Interview Questions and Answers

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

Page 23: PHP Interview Questions and Answers

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

Page 24: PHP Interview Questions and Answers

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.

Page 25: PHP Interview Questions and Answers

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

MNC php interview questions and answersJanuary 5, 2009 — sharag

 

 

Rate This

1) what is session_set_save_handler in PHP? session_set_save_handler() sets the user-level

session storage functions which are used for storing and retrieving data associated with a session. This

is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e.

Storing the session data in a local database.

2) what is garbage collection? default time ? refresh time? Garbage Collection is an automated

part of PHP , If the Garbage Collection process runs, it then analyzes any files in the /tmp for any

session files that have not been accessed in a certain amount of time and physically deletes them.

Garbage Collection process only runs in the default session saves directory, which is /tmp. If you opt to

save your sessions in a different directory, the Garbage Collection process will ignore it. The Garbage

Collection process does not differentiate between which sessions belong to whom when run. This is

especially important note on shared web servers. If the process is run, it deletes ALL files that have not

been accessed in the directory.

Page 26: PHP Interview Questions and Answers

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

name                                          default

session.gc_maxlifetime     1440 seconds or 24 minutes

session.gc_probability      1

session.gc_divisor              100

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

can get read receipt.

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

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

var $readReceipt = null;

And then, at ‘createHeader’ function add:

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

>__formatAddress($this->readReceipt) . $this->_newLine; }

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

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

Loads the PHP extension given by the parameter library .

Use extension_loaded() to test whether a given extension is already available or not. This works on

both built-in extensions and dynamically loaded ones (either through php.ini or dl()).

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

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

5) what is XML-RPC ? XML-RPC is a remote procedure call protocol which uses XML to encode its

calls and HTTP as a transport mechanism. An XML-RPC message is an HTTP-POST request. The body of

the request is in XML. A procedure executes on the server and the value it returns is also formatted in

XML.

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

Page 27: PHP Interview Questions and Answers

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

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

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

htmlentities() – Convert ALL special characters to HTML entities

9) how to do session using DB?

bool session_set_save_handler ( callback $open , callback $close , callback $read , callback $write ,

callback $destroy , callback $gc ) using this function we can store sessions in DB.

PHP has a built-in ability to override its default session handling. The function

session_set_save_handler() lets the programmer specify which functions should actually be called

when it is time to read or write session information. by overriding the default functions using

session_set_save_handler handle we can store session in Db like below example

class SessionManager {

var $life_time;

function SessionManager() {

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

// Register this object as the session handler session_set_save_handler( array( &$this, “open” ),

array( &$this, “close” ), array( &$this, “read” ), array( &$this, “write”), array( &$this, “destroy”), array(

&$this, “gc” ) );

}

function open( $save_path, $session_name ) {

global $sess_save_path;

$sess_save_path = $save_path;

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

return true;

}

Page 28: PHP Interview Questions and Answers

function close() {

return true;

}

function read( $id ) {

// Set empty result $data = ”;

// Fetch session data from the selected database

$time = time();

$newid = mysql_real_escape_string($id); $sql = “SELECT `session_data` FROM `sessions` WHERE

`session_id` = ‘$newid’ AND `expires` > $time”;

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

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

}

return $data;

}

function write( $id, $data ) {

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

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

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

$time)”;

$rs = db_query($sql);

return TRUE;

}

function destroy( $id ) {

Page 29: PHP Interview Questions and Answers

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

`session_id` = ‘$newid’”;

db_query($sql);

return TRUE;

}

function gc() {

// Garbage Collection

// Build DELETE query. Delete all records who have passed the expiration time $sql = ‘DELETE FROM

`sessions` WHERE `expires` < UNIX_TIMESTAMP();’;

db_query($sql);

// Always return TRUE return true;

}

}

10) how to track user logged out or not? when user is idle ? By checking the session variable

exist or not while loading th page. As the session will exist longer as till browser closes.

The default behaviour for sessions is to keep a session open indefinitely and only to expire a session

when the browser is closed. This behaviour can be changed in the php.ini file by altering the line

session.cookie_lifetime = 0 to a value in seconds. If you wanted the session to finish in 5 minutes you

would set this to session.cookie_lifetime = 300 and restart your httpd server.

11) how to track no of user logged in ? whenever a user logs in track the IP, userID etc..and store

it in a DB with a active flag while log out or sesion expire make it inactive. At any time by counting the

no: of active records we can get the no: of visitors.

12) in PHP for pdf which library used?

The PDF functions in PHP can create PDF files using the PDFlib library With version 6, PDFlib offers an

object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. There is also the »

Panda module.

Page 30: PHP Interview Questions and Answers

FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the

PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit

your needs.

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

with PHP4 and PHP5.

13) for image work which library?

You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may

also require other libraries, depending on which image formats you want to work with.

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

Object oriented programming language allows concepts such as modularity, encapsulation,

polymorphism and inheritance.

Encapsulation passes the message without revealing the exact functional details of the class. It allows

only the relevant information to the user without revealing the functional mechanism through which a

particular class had functioned.

Abstract class is a template class that contains such things as variable declarations and methods, but

cannot contain code for creating new instances. A class that contains one or more methods that are

declared but not implemented and defined as abstract. Abstract class: abstract classes are the class

where one or more methods are abstract but not necessarily all method has to be abstract. Abstract

methods are the methods, which are declare in its class but not define. The definition of those

methods must be in its extending class.

Interface: Interfaces are one type of class where all the methods are abstract. That means all the

methods only declared but not defined. All the methods must be define by its implemented class.

15) what is design pattern? singleton pattern?

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

The Singleton design pattern allows many parts of a program to share a single resource without having

to work out the details of the sharing themselves.

16) what are magic methods?

Magic methods are the members functions that is available to all the instance of class Magic methods

always starts with “__”. Eg. __construct All magic methods needs to be declared as public To use magic

method they should be defined within the class or program scope Various Magic Methods used in PHP

Page 31: PHP Interview Questions and Answers

5 are: __construct() __destruct() __set() __get() __call() __toString() __sleep() __wakeup() __isset()

__unset() __autoload() __clone()

17) what is magic quotes? Magic Quotes is a process that automagically escapes incoming data to

the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime,

as needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying

on this feature is highly discouraged.

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

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

3. Overloading of methods through the __call function

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

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

trying to create.

6 Finality : can now use the final keyword to indicate that a method cannot be overridden by a child.

You can also declare an entire class as final which prevents it from having any children at all.

7 Interfaces & Abstract Classes

8 Passed by Reference : In PHP4, everything was passed by value, including objects. This has changed

in PHP5 — all objects are now passed by reference.

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

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

php4?

yes you can define class and can call class by creating object of that class. but the diff b/w php4 &

php5 is that in php4 everything was passed by value where as in php5 its by reference. And also any

value change in reference object changes the actucal value of object also. And one more thing in

introduction of __clone object in PHP5 for copying the object.

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

here are three basic types of runtime errors in PHP:

Page 32: PHP Interview Questions and Answers

1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for

example, accessing a variable that has not yet been defined. By default, such errors are not displayed

to the user at all – although you can change this default behaviour.

2. Warnings: These are more serious errors – for example, attempting to include() a file which does not

exist. By default, these errors are displayed to the user, but they do not result in script termination.

3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or

calling a non-existent function. These errors cause the immediate termination of the script, and PHP?s

default behaviour is to display them to the user when they take place.

by using ini_set function.

21) what is cross site scripting? SQL injection?

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web

applications which allow code injection by malicious web users into the web pages viewed by other

users. Examples of such code include HTML code and client-side scripts.

SQL injection is a code injection technique that exploits a security vulnerability occurring in the

database layer of an application. The vulnerability is present when user input is either incorrectly

filtered for string literal escape characters embedded in SQL statements or user input is not strongly

typed and thereby unexpectedly executed

22) what is outerjoin? inner join?

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

are present in other tables

An inner join requires each record in the two joined tables to have a matching record. An inner join

essentially combines the records from two tables (A and B) based on a given join-predicate.

23) what is URL rewriting?

Using URL rewriting we can convert dynamic URl to static URL Static URLs are known to be better than

Dynamic URLs because of a number of reasons 1. Static URLs typically Rank better in Search Engines.

2. Search Engines are known to index the content of dynamic pages a lot slower compared to static

pages. 3. Static URLs are always more friendlier looking to the End Users.

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

sessions.

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

Page 33: PHP Interview Questions and Answers

1. Never include, require, or otherwise open a file with a filename based on user input, without

thoroughly checking it first. 2. Be careful with eval() Placing user-inputted values into the eval()

function can be extremely dangerous. You essentially give the malicious user the ability to execute

any command he or she wishes! 3. Be careful when using register_globals = ON It was originally

designed to make programming in PHP easier (and that it did), but misuse of it often led to security

holes 4. Never run unescaped queries 5. For protected areas, use sessions or validate the login every

time. 6. If you don’t want the file contents to be seen, give the file a .php extension.

25) whether PHP supports Microsoft SQL server ? The SQL Server Driver for PHP v1.0 is designed

to enable reliable, scalable integration with SQL Server for PHP applications deployed on the Windows

platform. The Driver for PHP is a PHP 5 extension that allows the reading and writing of SQL Server

data from within PHP scripts. using MSSQL or ODBC modules we can access Microsoft SQL server.

26) what is MVC? why its been used? Model-view-controller (MVC) is an architectural pattern used

in software engineering. Successful use of the pattern isolates business logic from user interface

considerations, resulting in an application where it is easier to modify either the visual appearance of

the application or the underlying business rules without affecting the other. In MVC, the model

represents the information (the data) of the application; the view corresponds to elements of the user

interface such as text, checkbox items, and so forth; and the controller manages the communication of

data and the business rules used to manipulate the data to and from the model.

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

means:

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

understanding code

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

In general, a framework is a real or conceptual structure intended to serve as a support or guide for

the building of something that expands the structure into something useful. Advantages : Consistent

Programming Model Direct Support for Security Simplified Development Efforts Easy Application

Deployment and Maintenance

28) what is CURL?

CURL means Client URL Library

curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS,

SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST, HTTP

PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic,

Digest, NTLM, Negotiate, kerberos…), file transfer resume, proxy tunneling and a busload of other

useful tricks.

Page 34: PHP Interview Questions and Answers

CURL allows you to connect and communicate to many different types of servers with many different

types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap

protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also

be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password

authentication.

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

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

Uploading file

<?php

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

$ch = curl_init();

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

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

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

curl_exec($ch); ?>

output:

Array ( [name] => Foo ) Array ( [file] => Array ( [name] => test.png

[type] => image/png [tmp_name] => /tmp/phpcpjNeQ [error] => 0 [size] => 279 )

)

30) using CSS can we have a scroll to table?

No table won't support scrolling of its data. but we can do another workaround

like placing a table

 in a DIV layer and setting the DIV css property to overflow:auto will do the

trick.

31) how to increase session time in PHP ?

In php.ini by setting session.gc_maxlifetime and session.cookie_lifetime

values

we can change the session time in PHP.

Page 35: PHP Interview Questions and Answers

32) what is UI? What are the five primary user-interface components?

A user interface is a means for human beings to interact with computer-based

"tools" and"messages".

One presumed goal is to make the user's experience productive, efficient,

pleasing, and humane.

The primary components of UIs are a) metaphors (fundamental concepts

communicated

 through words, images, sounds, etc.)

b) mental models (structure of data, functions, tasks, roles, jobs, and people

in organizations of work

and/or play)

 c) navigation (the process of moving through the mental models)

d) interaction (all input-output sequences and means for conveying feedback)

 e) and appearance (visual, verbal, acoustic, etc.).

33) How can I set a cron and how can I execute it in Unix, Linux, and windows?

Cron is very simply a Linux module that allows you to run commands at predetermined times or

intervals.

In Windows, it’s called Scheduled Tasks. The name Cron is in fact derived from the same word from

which we get the word chronology, which means order of time.

The easiest way to use crontab is via the crontab command. # crontab This command ‘edits’ the

crontab.

Upon employing this command, you will be able to enter the commands that you wish to run.

My version of Linux uses the text editor vi. You can find information on using vi here.

The syntax of this file is very important – if you get it wrong, your crontab will not function properly.

The syntax of the file should be as follows: minutes hours day_of_month month day_of_week command

All the variables, with the exception of the command itself, are numerical constants.

In addition to an asterisk (*), which is a wildcard that allows any value, the ranges permitted for each

field are as follows: Minutes: 0-59 Hours: 0-23 Day_of_month: 1-31 Month: 1-12 Weekday: 0-6 We can

also include multiple values for each entry, simply by separating each value with a comma.

command can be any shell command and, as we will see momentarily, can also be used to execute a

Web document such as a PHP file. So, if we want to run a script every Tuesday morning at 8:15 AM, our

mycronjob file will contain the following content on a single line: 15 8 * * 2 /path/to/scriptname This all

seems simple enough, right? Not so fast! If you try to run a PHP script in this manner, nothing will

happen (barring very special configurations that have PHP compiled as an executable, as opposed to

an Apache module).

Page 36: PHP Interview Questions and Answers

The reason is that, in order for PHP to be parsed, it needs to be passed through Apache. In other

words, the page needs to be called via a browser or other means of retrieving Web content.

For our purposes, I’ll assume that your server configuration includes wget, as is the case with most

default configurations. To test your configuration, log in to shell.

If you’re using an RPM-based system (e.g. Redhat or Mandrake), type the following: # wget help If you

are greeted with a wget package identification, it is installed in your system.

You could execute the PHP by invoking wget on the URL to the page, like so: # wget

http://www.example.com/file.php Now, let’s go back to the mailstock.php file we created in the first

part of this article.

We saved it in our document root, so it should be accessible via the Internet. Remember that we

wanted it to run at 4PM Eastern time, and send you your precious closing bell report? Since I’m located

in the Eastern timezone, we can go ahead and set up our crontab to use 4:00, but if you live

elsewhere, you might have to compensate for the time difference when setting this value.

This is what my crontab will look like: 0 4 * * 1,2,3,4,5 wget http://www.example.com/mailstock.php

34)Difference b/w OOPS concept in php4 and PHP5 ?

version 4’s object-oriented functionality was rather hobbled. Although the very basic premises of

objectoriented programming (OOP) were offered in version 4, several deficiencies existed, including: •

An unorthodox object-referencing methodology • No means for setting the scope (public, private,

protected, abstract) of fields and methods • No standard convention for naming constructors •

Absence of object destructors • Lack of an object-cloning feature • Lack of support for interfaces

35) Difference b/w MyISAM and InnoDB in MySQL?

Ans:

The big difference between MySQL Table Type MyISAM and InnoDB is that InnoDB supports

transaction

InnoDB supports some newer features: Transactions, row-level locking, foreign keys

InnoDB is for high volume, high performance

use MyISAM if they need speed and InnoDB for data integrity.

InnoDB has been designed for maximum performance when processing large data volumes

Even though MyISAM is faster than InnoDB

Page 37: PHP Interview Questions and Answers

InnoDB supports transaction. You can commit and rollback with InnoDB but with MyISAM once you

issue a command it’s done

MyISAM does not support foreign keys where as InnoDB supports

Fully integrated with MySQL Server, the InnoDB storage engine maintains its own buffer pool for

caching data and indexes in main memory. InnoDB stores its tables and indexes in a tablespace,

which may consist of several files (or raw disk partitions). This is different from, for

example, MyISAM tables where each table is stored using separate files. InnoDB tables can be of any

size even on operating systems where file size is limited to 2GB.

36) how to set session tiem out at run time or how to extend the session timeout at

runtime?

Ans:

Sometimes it is necessary to set the default timeout period for PHP. To find out what the default (file-

based-sessions) session timeout value on the server is you can view it through a ini_get command:

// Get the current Session Timeout Value

$currentTimeoutInSecs = ini_get(’session.gc_maxlifetime’);

Change the Session Timeout Value

// Change the session timeout value to 30 minutes

ini_set(’session.gc_maxlifetime’, 30*60);

If you have changed the sessions to be placed inside a Database occasionally implementations will

specify the expiry manually. You may need to check through the session management class and see if

it is getting the session timeout value from the ini configuration or through a method parameter (with

default). It may require a little hunting about.

PHP Interview Questions

1) Explain about PHP?Personal home page language is used to create dynamic and interactive websites which are very efficient in delivering client needs from the server side. This language is widely used. It is used on various operating systems with Apache modules. This can be directly embedded into HTML code.

2) Explain about the installation of PHP on UNIX systems?PHP can be installed on UNIX in many different ways there are pre defined packages available which can ease the process. Initially it can be controlled by the command line options. Help can be obtained from./configure help command. After installing PHP modules or executables can be configures and make command should help you in the process.

3) How to enable parsing?Parsing is an important concept if you want to run your code appropriately and timely. PHP parses all

Page 38: PHP Interview Questions and Answers

the code present between the opening and closing tags, it ignores everything present out of the closing and opening tags. This tags allow PHP to be embedded between many documents.

4) What are the different opening and closing tags available in PHP?There are four different types of tags available in PHP they are* *

* PHP short tags* ASP style tags.Generally the first two tags are widely used because they are portable.

5) Explain about array uintersect()?This function is very useful in PHP. This function compares array values in a user defined function and it returns the array. If assoc() is added to the function it compares array keys. This function can also be defined as array uintersect uassoc().

6) Explain about converting an object?When an object is converted into an object the stance of the object is not modified. A new instance of the class is created if a value of different type if converted into an object. Incase the value is null at the time of conversion the new instance will be empty.

7) Explain about resource?Resource holds reference to an external resource and it is a special variable. These are created and used by specially defined functions. Resource holds defined and special handlers for opening files. Converting to a resource makes no sense at all.

8) Explain about null?Null represents a variable with no value inside. There doesn’t exist any value for type Null. Null is defined to be null if and only if it is assigned a constant null, there is no value set, it is set to be unset(). This is the case insensitive keyword. There are also two functions they are is_null and unset().9) Explain about mixed and callback functions?Mixed function indicates that the function may contain multiple types but it doesn’t form a necessary condition. Functions like call_user_func() or usort() accept user defined functions as parameter. These functions are not only simple but also object methods which includes static methods.10) Explain about PHP looping?Looping statements are used in PHP to execute the code for a developer defined number of times. PHP has these following looping statements they are while, do while, for and for each. Foreach is used to loop a block of code in each element in an array.11) Explain about Booleans in PHP?A Boolean type states a truth value whether it is true or false. These statements are case insensitive. An operator returns a Boolean value and this value is passed onto the control structure which executes the statement. If an argument is required it is automatically converted.12) Explain about Type juggling?PHP uses Type juggling similar to the way Perl uses. Variable is defined in the context in which it is used. It doesn’t require any explicit definition for a function to perform its duties. For example if a string value is assigned to a variable it is defined as string.13) Explain about the casts allowed in PHP?Type casting acts and functions similarly as it performs in C. The casts allowed are Integer, Boolean, float and double, string, binary, array and object. Casting and support was added in PHP 5.2.1. A variable can be enclosed in double quotes instead of casting it to a string.14) How to change the principal password?Principal password can be changed by using kadm5_chpass_principal command. If you also want to

Page 39: PHP Interview Questions and Answers

specify the new password for effecting a change to the principal password it should be asBool kadm5_chpass_principal (resource $handle, string $principal, string password). This changes the password to password.15) Explain about the advantages of using PHP?There are many advantages of PHP they are1) Easy and fast creation of dynamic web pages and a developer can also embed these dynamic functions into HTML.2) A huge community resource which has a ton of information before you.3) Connectivity ability lets you to connect to different interfaces and predefined libraries.4) Execution is very fast because it uses less system resources, etc.16) Explain about the connective abilities of the PHP?A huge advantage for PHP is its connective ability. It uses huge number of extensions to interface with huge pool of libraries such as XML, graphics and encryption. Programmers can create their own extensions and compiling them. They can load their own programs by using the dynamic loading mechanism.17) How can MYSQL functions be available with PHP?MYSQL is not available as a default feature it must be created by the user. You can use --with-mysql=DIR function to make available SQL on your system. Compiling PHP functions with MYSQL will increase the support and functioning of the language. MYSQL should be installed where there are extensions of PHP.