PHP Interview Questions and Answers
PHP Interview Questions and Answers
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.
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.
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? - ^^
These are the simplest method to backup and restore the MySQl table
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.
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.
Ans:
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.
Example
<?php
$strW3 = "Hello w3answers";
$arrW3 = str_split($strW3 );
$arrW3 = str_split($strW3 , 3);
print_r($arrW3);
print_r($arrW3);
?>
reply
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.
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?
---------------------------------
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 can we encrypt and decrypt a data present in a MySQL table using
MySQL?
How do you convert an old fashioned 10 digit ISBN to a new 13 digit ISBN
using php ?
function isbn10_to_13($isbnold){
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
}
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-
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.
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
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
If you refersh the page , POST method shows an annoying alert box
All the informations which is passed by GET method will be stored in webserver(log file) but in POST
we can not
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;
/* this is invalid */
// echo $row->0;
?>
Example
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
mysql_free_result($result);
?>
The Session Manager session support allows multiple server instances to share a common pool of
sessions, known as a session cluster
#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.
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.
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);
}
}
<?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
{
}
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
What is PHP?
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).
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, 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:
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.
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...
What's PHP ?
The PHP Hypertext Preprocessor is a programming language that allows web developers to create
dynamic content that interacts with databases. PHP is basically used for developing web based
software applications.
What Is a Session?
A session is a logical object created by the PHP engine to allow you to preserve data across
subsequent HTTP requests.
There is only one session object available to your PHP scripts at any time. Data saved to the session
by a script can be retrieved by the same script or another script when requested from the same
visitor.
Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete
functional transaction for the same visitor.
What is meant by PEAR in php?
Answer1:
PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR
is a framework and distribution system for reusable PHP components. It eases installation by bringing
an automated wizard, and packing the strength and experience of PHP users into a nicely organised
OOP library. PEAR also provides a command-line interface that can be used to automatically install
"packages"
Answer2:
PEAR is short for "PHP Extension and Application Repository" and is pronounced just like the fruit. The
purpose of PEAR is to provide:
A structured library of open-sourced code for PHP users
A system for code distribution and package maintenance
A standard style for code written in PHP
The PHP Foundation Classes (PFC),
The PHP Extension Community Library (PECL),
A web site, mailing lists and download mirrors to support the PHP/PEAR community
PEAR is a community-driven project with the PEAR Group as the governing body. The project has been
founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then.
How can we know the number of days between two given dates using PHP?
Simple arithmetic:
$date1 = date('Y-m-d');
$date2 = '2006-07-01';
$days = (strtotime() - strtotime()) / (60 * 60 * 24);
echo "Number of days since '2006-07-01': $days";
What is the difference between $message and $$message?
Anwser 1:
$message is a simple variable whereas $$message is a reference variable. Example:
$user = 'bob'
is equivalent to
$holder = 'user';
$$holder = 'bob';
Anwser 2:
They are both variables. But $message is a variable with a fixed name. $$message is a variable who's
name is stored in $message. For example, if $message contains "var", $$message is the same as
$var.
What Is a Persistent Cookie?
A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer.
By default, cookies are created as temporary cookies which stored only in the browser's memory.
When the browser is closed, temporary cookies will be erased. You should decide when to use
temporary cookies and when to use persistent cookies based on their differences:
*Temporary cookies can not be used for tracking long-term information.
*Persistent cookies can be used for tracking long-term information.
*Temporary cookies are safer because no programs other than the browser can access them.
*Persistent cookies are less secure because users can open cookie files see the cookie values.
What does a special set of tags <?= and ?> do in PHP?
The output is displayed directly to the browser.
How do you define a constant?
Via define() directive, like define ("MYCONSTANT", 100);
What are the differences between require and include, include_once?
Anwser 1:
require_once() and include_once() are both the functions to include and evaluate the specified file
only once. If the specified file is included previous to the present call occurrence, it will not be done
again.
But require() and include() will do it as many times they are asked to do.
Anwser 2:
The include_once() statement includes and evaluates the specified file during the execution of the
script. This is a behavior similar to the include() statement, with the only difference being that if the
code from a file has already been included, it will not be included again. The major difference between
include() and require() is that in failure include() produces a warning message whereas require()
produces a fatal errors.
Anwser 3:
All three are used to an include file into the current page.
If the file is not present, require(), calls a fatal error, while in include() does not.
The include_once() statement includes and evaluates the specified file during the execution of the
script. This is a behavior similar to the include() statement, with the only difference being that if the
code from a file has already been included, it will not be included again. It des not call a fatal error if
file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not
exists.
Anwser 4:
File will not be included more than once. If we want to include a file once only and further calling of
the file will be ignored then we have to use the PHP function include_once(). This will prevent
problems with function redefinitions, variable value reassignments, etc.
What is the difference between mysql_fetch_object and mysql_fetch_array?
MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all
matching records from the table in an array
How can I execute a PHP script using command line?
Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the
command line argument. For example, "php myScript.php", assuming "php" is the command to invoke
the CLI program.
Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in
command line environment.
I am trying to assign a variable the value of 0123, but it keeps coming up with a different
number, what?s the problem?
PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions
for more numeric problems.
Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this
example?
In this example it wouldn?t matter, since the variable is all by itself, but if you were to print something
like "{$a},000,000 mln dollars", then you definitely need to use the braces.
What are the different tables present in MySQL? Which type of table is generated when we
are creating a table in the following syntax: create table employee(eno int(2),ename
varchar(10))?
Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the default storage engine as of MySQL 3.23. When you fire the above create query MySQL
will create a MyISAM table.
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.
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'
You need to have access to the GD Library in order to use the image functions in PHP.
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.
Rate This
There are 3 PHP.ini variables, which deal with the garbage collector: PHP ini value
name default
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.
It’s quite straightforward, just edit email.php, and add this at vars definitions:
4) Runtime library loading ? without default mysql support, how to run mysql with php?
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()).
Warning :This function has been removed from some SAPI’s in PHP 5.3.
5) what is XML-RPC ? XML-RPC is a remote procedure call protocol which uses XML to encode its
calls and HTTP as a transport mechanism. An XML-RPC message is an HTTP-POST request. The body
of the request is in XML. A procedure executes on the server and the value it returns is also formatted
in XML.
6) default session time ? default session time in PHP is 1440 seconds or 24 minutes.
7) default session save path ? Default session save path id temporary folder /tmp
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() {
// 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” ) );
global $sess_save_path;
$sess_save_path = $save_path;
return true;
function close() {
return true;
$time = time();
return $data;
$rs = db_query($sql);
return TRUE;
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);
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.
The PDF functions in PHP can create PDF files using the PDFlib library With version 6, PDFlib offers an
object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. There is also the »
Panda module.
FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the
PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit
your needs.
FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works
with PHP4 and PHP5.
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.
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.
Magic methods are the members functions that is available to all the instance of class Magic methods
always starts with “__”. Eg. __construct All magic methods needs to be declared as public To use
magic method they should be defined within the class or program scope Various Magic Methods used
in PHP 5 are: __construct() __destruct() __set() __get() __call() __toString() __sleep() __wakeup()
__isset() __unset() __autoload() __clone()
17) what is magic quotes? Magic Quotes is a process that automagically escapes incoming data to
the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime,
as needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0.
Relying on this feature is highly discouraged.
18) diff b/w php4 & php5 ? In PHP5 1 Implementation of exceptions and exception handling
2. Type hinting which allows you to force the type of a specific argument as object, array or NULL
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.
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.
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.
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.
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
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.
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.
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.
A — Tweaking design (HTML) without altering code B — Web design staff can modify UI without
understanding code
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
curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS,
SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST,
HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication
(Basic, Digest, NTLM, Negotiate, kerberos…), file transfer resume, proxy tunneling and a busload of
other useful tricks.
CURL allows you to connect and communicate to many different types of servers with many different
types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap
protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also
be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password
authentication.
29) HOW we can transfer files from one server to another server without web forms?
using CURL we can transfer files from one server to another server. ex:
Uploading file
<?php
$ch = curl_init();
curl_exec($ch); ?>
output:
Array ( [name] => Foo ) Array ( [file] => Array ( [name] => test.png
[type] => image/png [tmp_name] => /tmp/phpcpjNeQ [error] => 0 [size] => 279 )
)
32) what is UI? What are the five primary user-interface components?
A user interface is a means for human beings to interact with computer-based
"tools" and"messages".
One presumed goal is to make the user's experience productive, efficient,
pleasing, and humane.
The primary components of UIs are a) metaphors (fundamental concepts
communicated
through words, images, sounds, etc.)
b) mental models (structure of data, functions, tasks, roles, jobs, and people
in organizations of work
and/or play)
c) navigation (the process of moving through the mental models)
d) interaction (all input-output sequences and means for conveying feedback)
e) and appearance (visual, verbal, acoustic, etc.).
33) How can I set a cron and how can I execute it in Unix, Linux, and windows?
Cron is very simply a Linux module that allows you to run commands at predetermined times or
intervals.
In Windows, it’s called Scheduled Tasks. The name Cron is in fact derived from the same word from
which we get the word chronology, which means order of time.
The easiest way to use crontab is via the crontab command. # crontab This command ‘edits’ the
crontab.
Upon employing this command, you will be able to enter the commands that you wish to run.
My version of Linux uses the text editor vi. You can find information on using vi here.
The syntax of this file is very important – if you get it wrong, your crontab will not function properly.
The syntax of the file should be as follows: minutes hours day_of_month month day_of_week
command All the variables, with the exception of the command itself, are numerical constants.
In addition to an asterisk (*), which is a wildcard that allows any value, the ranges permitted for each
field are as follows: Minutes: 0-59 Hours: 0-23 Day_of_month: 1-31 Month: 1-12 Weekday: 0-6 We
can also include multiple values for each entry, simply by separating each value with a comma.
command can be any shell command and, as we will see momentarily, can also be used to execute a
Web document such as a PHP file. So, if we want to run a script every Tuesday morning at 8:15 AM,
our mycronjob file will contain the following content on a single line: 15 8 * * 2 /path/to/scriptname
This all seems simple enough, right? Not so fast! If you try to run a PHP script in this manner, nothing
will happen (barring very special configurations that have PHP compiled as an executable, as opposed
to an Apache module).
The reason is that, in order for PHP to be parsed, it needs to be passed through Apache. In other
words, the page needs to be called via a browser or other means of retrieving Web content.
For our purposes, I’ll assume that your server configuration includes wget, as is the case with most
default configurations. To test your configuration, log in to shell.
If you’re using an RPM-based system (e.g. Redhat or Mandrake), type the following: # wget help If
you are greeted with a wget package identification, it is installed in your system.
You could execute the PHP by invoking wget on the URL to the page, like so: # wget
http://www.example.com/file.php Now, let’s go back to the mailstock.php file we created in the first
part of this article.
We saved it in our document root, so it should be accessible via the Internet. Remember that we
wanted it to run at 4PM Eastern time, and send you your precious closing bell report? Since I’m
located in the Eastern timezone, we can go ahead and set up our crontab to use 4:00, but if you live
elsewhere, you might have to compensate for the time difference when setting this value.
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
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
use MyISAM if they need speed and InnoDB for data integrity.
InnoDB has been designed for maximum performance when processing large data volumes
InnoDB supports transaction. You can commit and rollback with InnoDB but with MyISAM once you
issue a command it’s done
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:
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.
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.