PHP Interview
Questions
1. What is php? Who found it?
PHP (Hyper text Pre Processor) is a server side scripting
language commonly used for web applications that allows web developers to
create dynamic content that interacts with databases. Rasmus Lerdorf is the
founder of php.
2. What
is a web page?
A
web page is a document or information resource that is suitable for the World
Wide Web and can be accessed through a web browser and displayed on a monitor
or mobile device. This information is usually in HTML or XHTML format, and may
provide navigation to other web pages via hyperlinks. Web pages frequently
subsume other resources such as style sheets, scripts and images into their
final presentation.
Web pages may be retrieved from a local
computer or from a remote web server. The web server may restrict access only
to a private network, e.g. a corporate intranet, or it may publish pages on the
World Wide Web. Web pages are requested and served from web servers using
Hypertext Transfer Protocol (HTTP).
Web pages may consist of files of
static text and other content stored within the web server's file system
(static web pages), or may be constructed by server-side software when they are
requested (dynamic web pages). Client-side scripting can make web pages more
responsive to user input once on the client browser.
3. How
can you get the complete list of the PHP variables?
By
looking at the output of the phpinfo() function.
4. What
do you mean by Text Editors? And list the some PHP editors?
There
are many text editors and Integrated
Development Environments you can use to create, edit and manage PHP files.
Notpad, notpad++, gedit, bluefish etc. Dream viewer and Net beans are the famous ide(s) used in the
development of php.
5. Write
the name of some databases that are currently supported to PHP?
MYSQL
Direct MS-SQL
Sybase
ODBC
oracle(OC 17
and OC 18)
mSQL
FrontBase
6. Write
name of the web servers to which PHP supports?
Apache
Microsoft
Internet Information Server(IIS)
personal web server
Netscape
7. How
can I execute a PHP script using command line?
You
can execute a PHP script by running the Command line interface program, in
which you can enter the PHP script file as an argument. If the file is made for
the web interface then it may not execute properly using command line. Command
line allows faster execution of the statements and gives faster results.
8. How
can we encrypt the password using PHP?
Crypt
( ) function is used to create one way encryption. It takes one input string and
one optional parameter. The function look is defined as: crypt (input string,
salt), where input string consists of the string which has to be encrypted and
salt is an optional parameter.
<?
Php
$password =
crypt('mypassword');
print $password
. “ is the encrypted version of mypassword”;
? >
9. What
are different types of Runtime Errors in PHP?
There are three
types of Runtime Errors in PHP. They are as follows:-
- Notices :
These are trivial, non-critical
errors. that PHP encounters while executing a script - for example, accessing a
variable that has not yet been defined. By default, such errors are not
displayed to the user at all - although you can change this default behavior.
- 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.
- Fatal errors :
These are critical errors - for
example, instantiating an object of a non-existent class, or calling a
non-existent function. These errors cause the immediate termination of the
script, and PHP's default behavior is to display them to the user when they
take place.
Internally, these variations are
represented by twelve different error types
10. Define
urlencode ( ) and urldecode( ) used in PHP?
urlencode ( )
returns the URL encoded version of given string. For URL encoding string values
are used in the queries to be passed as URL. Whereas,
urldecode ( ) returns the URL decoded
string (original string) which will be decoded by taking the already encoded
string.
Example is as follows:
$discount ="10.00%";
$url =
"http://domain.com/submit.php?disc=".urlencode($discount);
echo $url;
Output:
"http://domain.com/submit.php?disc=10%2E00%25".
11. What
is the difference between $message and $$message?
The only
difference between $message and $$message is that, $message is a normal
variable and $$message is variable to variable. The difference in functioning
is shown below:
When declaring a variable in PHP the
variable gets declared like this
$message //which
is simply a variable
To store the data to assign the value
to it we write like
$message= “ride”; //assigned
the string to the variable
echo $message; //
it will print the value ride
Whereas if you want to display the
variable to variable then you use
$var = "Hello";
$message = "var";
echo $message; //print
var
echo $$message; //print
Hello.
12. What
Is a Persistent Cookie?
Persistent
cookie is a cookie which is permanently stored on user’s computer in a cookie
file. They are used for tracking the user information of the users who are
browsing from a very long time. They also have the drawbacks of being unsecure,
as user can see the cookies which are saved on the 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.
13. What
is a PHP Session?
PHP session is
not different from a normal session. It can be used to store information on the
server for future use. PHP session allows you to store the user session, like
their information on server for faster access and for later use like username,
IP addresses, their actions etc. The information which is saved is temporary
and can be deleted after the user is no longer active. Example of starting a
PHP session is as follows:
<? php
Session start();
//
start up your PHP session!
?>
14. What
is meant by PEAR in php? What is the purpose of it?
PEAR stands for
"PHP Extension and Application Repository". As the name suggests, it
gives advanced functionality to the PHP language and include many applications
which can be used on fly.
The purpose of it is as follows:-
- Open source structured library for
PHP users
- Code distribution and package
maintenance system
- Standard style for code written in
PHP
15. Is
PHP a loosely Typed Language?. What is
the difference between strongly typed and loosely typed language?
Yes, PHP is a
loosely typed language.
In this type of language variable doesn’t need
to be declared before their use. This language converts the data according to
its given value.
Whereas, in strongly typed language
first every type has to be declared (defined) then only it can be used.
16. Explain
"GET" and "POST" methods ?.
Both the
methods are used to send data to the server.
GET method - the browser appends the
data onto the URL.
POST method - the data is sent as
“standard input.”
17. Explain
the "unlink" and "unset" functions.
unlink( )
function is for file system handling. It just deletes the file in context.
unset( ) function is for variable
management. It makes a variable undefined
18. What
is the default session time in PHP?
Until closing
the browser.
19. How
will you find out the value of current session id?
By using: session_id( )
20. How
can we increase the execution time of a php script?
Default time
allowed for the PHP scripts to execute is 30s defined in the php.ini file. The
function used is set_time_limit (int seconds). If the value passed is ‘0’, it
takes unlimited time.
21. What
is zend engine? Explain the architecture of Zend engine with the diagram.
Zend
engine is like a virtual machine and is an open source, and is known for its
role in automating the web using PHP. Zend is named after its developers Zeev
and Aandi. Its reliability, performance and extensibility has a significant
role in increasing the PHP’s popularity. The Zend Engine II is the heart of PHP
5. It is an open source project and freely available under BSD style license.
Zend Engine is
used internally by PHP as a complier and runtime engine. PHP Scripts are loaded
into memory and compiled into Zend opcodes. These opcodes are executed and the
HTML generated is sent to the client. The same is depicted above
22. What
is the difference between Split and Explode?
In
simple
Split - Splits string into array by regular
expression.
Explode - Split a string by string
Split :
Returns an
array of strings, each of which is a substring of string formed by splitting it
on boundaries formed by the case-sensitive regular expression pattern.
If there are n
occurrences of pattern, the returned array will contain n+1 items. For example,
if there is no occurrence of pattern, an array with only one element will be
returned. Of course, this is also true if string is empty. If an error occurs,
split() returns FALSE.
Example :
<? Php // Delimiters may be
slash, dot, or hyphen
$date =
"04/30/1973";
list($month,
$day, $year) = split('[/.-]', $date);
echo
"Month: $month; Day: $day; Year: $year<br />\n";
?>
spliti() - Split string into array by
regular expression case insensitive
Explode :
explode ( string $delimiter , string
$string , int $limit )
Returns an array of strings created
by splitting the string parameter on boundaries formed by the delimiter.
If limit is set and positive, the
returned array will contain a maximum of limit elements with the last element
containing the rest of string.
If the limit parameter is negative, all
components except the last -limit are returned.
If the limit parameter is zero, then
this is treated as 1.
If delimiter is an empty string
(""), explode() will return FALSE. If delimiter contains a value that
is not contained in string and a negative limit is used, then an empty array
will be returned, otherwise an array containing string will be returned.
Example :
<? php
$str =
'one|two|three|four';
print_r(explode('|',
$str, 2)); //
positive limit
print_r(explode('|',
$str, -1)); //
negative limit (since PHP 5.1)
?>
The above example will output:
Array ( [0] => one,[1] =>
two|three|four )
Array ( [0] => one , [1] => two,[2]
=> three )
23. Explain
the functionality of str_split( ) function in php
The str_split( )
function splits a string into an array.
Syntax :
str_split (string , length)
string -
Required. Specifies the string
to split
length - Optional. Specifies the length of
each array element. Default is 1
Note:
If length is less than 1, the str_split
() function will return FALSE.
If length is larger than the length of
string, the entire string will be returned as the only element of the array.
Example 1
<? php
print_r (str_split
("Hello"));
?>
The output of the code above will be:
Array ( [0] => H,[1] => e,[2]
=> l,[3] => l,[4] => o)
Example 2
<? php
print_r(str_split("Hello",3));
?>
The output of the code above will be:
Array ( [0] => Hel,[1] => lo)
24. What
is difference between developing website using Java and PHP?
Both
technologies are used for dynamic websites development.
PHP is an interpreter based technology
where as java is compiler based(usually JSP).
PHP is open source where as JSP is not.
Web sites developed in PHP are much
more faster compared to Java technology
Java is a distributed technology, which
means N tier application can be developed, where as PHP is used only for web
development.
25. How
can we know the number of days between two given dates using PHP?
The start date and end date can be
first found as shown below:
$date1= strotime ($start_date);
$date2= strotime ($end_date);
$date_diff = (($date1)- ($date2)) /
(60*60*24)
26. Different
methods to pass data from one web page to another:
1. Store the data in a session
variable. By storing the data, the data can be passed from one page to another.
2. Store data in a cookie: By storing
data in a persistent cookie, data can be passed from one form to another.
3. Set the data in a hidden field and
post the data using a submit button.
4. using get method
5. using post method
6. using javascript
27. $one
= true; $two = null;
echo $a = isset($one) &&
isset($two);
echo $b = isset($one) and isset($two);
$a will out put false, while $b will
out put true and what is the reason for this?
These are small
aspects but very important a programmer must know. In the first phrase it uses
“&&” operator to bind those two expressions which will give the
expected answer. but the second one gives an unexpected answer where “and”
operator is used.
The reason behind is the “higher
precedence” between these 3 operators,
1. &&
2. =
3. and
In the first condition it will first
check for the “&&” operation and then for the “=”
But in the second condition it will
first look for the “=” operator and then for the “and”.
In order to fix this you can force the
precedence by using parenthesis as follows,
echo $b = (isset($one) and
isset($two));
28. Write
a simple query to get the second largest value of a table column?
There are many
ways that we can write this,
But the simplest way in mysql is,
SELECT * FROM country ORDER BY id DESC
LIMIT 1, 1
And the following also are true
SELECT * FROM country ORDER BY id DESC
LIMIT 1 OFFSET 1
select max(id) from country where id
not in(select max(id) from country)
SELECT min(id) FROM (SELECT DISTINCT id
FROM country ORDER BY id DESC LIMIT 2) AS t
29. How
to reset/ destroy a cookie ?
Reset a cookie
by specifying expire time in the past:
Example:
Setcookie ('Test',$i,time()-3600); //
already expired time
Reset a cookie by specifying its name
only
Example:
Setcookie ('Test');
30. Tools
used for drawing ER diagrams ?.
1. Case
Studio
2. Smart
Draw
31. How
can I know that a variable is a number or not using a JavaScript?
bool
is_numeric( mixed var)
Returns TRUE if var is a number or a
numeric string, FALSE otherwise.
The isNaN()
function is used to check if a value is not a number.
Syntax
isNaN(number)
32. How
can we submit from without a submit button?
Trigger the JavaScript code on any
event ( like onSelect of drop down list box, onfocus, etc ) document.myform.submit();
This will submit the form.
33. What
are the reasons for selecting LAMP (Linux, Apache, MySQL, Php) instead of
combination of other software programs, servers and operating systems?
All of those
are open source resource. Security of
Linux is very more than windows. Apache is a better server that IIS both
in functionality and security. Mysql is world most popular open source
database. Php is more faster that asp or any other scripting language.
34. What
are the features and advantages of OBJECT ORIENTED PROGRAMMING?
One of the main
advantages of OO programming is its ease of modification; objects can easily be
modified and added to a system there by reducing maintenance costs. OO
programming is also considered to be better at modeling the real world than is
procedural programming. It allows for more complicated and flexible
interactions. OO systems are also easier for non-technical personnel to
understand and easier for them to participate in the maintenance and
enhancement of a system because it appeals to natural human cognition patterns.
For some systems, an OO approach can speed development time since many objects
are standard across systems and can be reused. Components that manage dates,
shipping, shopping carts, etc. can be purchased and easily modified for a
specific system.
35. How
can we get second of the current time using date function?
$second =
date("s");
36. How
do you define a constant?
Via define()
directive, like define ("MYCONSTANT", 100);
37. What
are the differences between require and include, include_once, require_once()?
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. The major difference between include ( )
and require ( ) is that in failure include ( ) produces a warning message
whereas require ( ) produces a fatal errors.
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.
38. 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.
39. What
are the different tables present in MySQL?
Total 5 types
of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
40. What
is the functionality of the functions STRSTR() and STRISTR()?
string strstr (
string haystack, string needle ) returns part of haystack string from the first
occurrence of needle to the end of haystack. This function is case-sensitive.
stristr() is idential to strstr()
except that it is case insensitive.
For example:
strstr("user@example.com","@")
will return "@example.com".
41. How
do I find out the number of parameters passed into function?.
func_num_args ()
function returns the number of parameters passed in.
42. How
do you call a constructor for a parent class?
parent::constructor($value)
43. 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.
44. For
printing out strings, there are echo, print and printf. Explain the
differences.
Echo :
echo is the
most primitive of them, and just outputs the contents following the construct
to the screen. We can pass multiple parameters to echo, like:
<?php echo 'Welcome ', 'to', ' ',
'techpreparations!'; ?>
and it will output the string
"Welcome to techpreparations!"
Print :
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. 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 :
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.
45. 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 ( ).
46. What’s
the output of the ucwords function in this example?
$formatted =
ucwords("TECHPREPARATIONS IS COLLECTION OF INTERVIEW QUESTIONS");
print $formatted;
What will be printed is
TECHPREPARATIONS IS COLLECTION OF INTERVIEW QUESTIONS.
ucwords ( ) makes every first letter of
every word capital, but it does not lower-case anything else. To avoid this,
and get a properly formatted string, it’s worth using strtolower ( ) first.
47. 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.
48. How
can we destroy the session, how can we unset the variable of a session?
session_unregister ( ) - Unregister
a global variable from the current session
session_unset ( ) - Free all session variables
49. What
are the different functions in sorting an array?
Sorting
functions in PHP:
asort( )
arsort( )
ksort( )
krsort( )
uksort( )
sort( )
natsort( )
rsort( )
50. How
can we know the count/number of elements of an array?
2 ways:
a) sizeof($array) - This
function is an alias of count()
b) count($array) - This
function returns the number of elements in an array.
Interestingly if you just pass a simple
var instead of an array, count() will return 1.
51. 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 160 bit value, and md5() returns a 128 bit value. This
is important when avoiding collisions.
52. 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.
53. What
are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row() ?.
mysql_fetch_array() - Fetch a result row as a combination of associative array
and
regular array.
mysql_fetch_object() - Fetch
a result row as an object.
mysql_fetch_row() - Fetch a result set as a regular array().
The difference
between mysql_fetch_row() and mysql_fetch_array() is that the first returns the results in a numeric array
($row[0], $row[1], etc.), while the latter returns a the results an array
containing both numeric and associative keys ($row['name'], $row['email'],
etc.). mysql_fetch_object() returns an object ($row->name, $row->email,
etc.).
54. What
is the difference between PHP4 and PHP5?
PHP4 cannot
support oops concepts and Zend engine 1 is used.
PHP5 supports oops concepts and Zend
engine 2 is used, Error supporting is increased in PHP5, XML and SQLLite will
is increased in PHP5.
55. Can
we use include(abc.PHP) two times in a PHP page makeit.PHP”?
Yes we can
include that many times we want, but here are some things to make sure of:
(including abc.PHP, the file names are
case-sensitive). There shouldn't be any duplicate function names, means there
should not be functions or classes or variables with the same name in abc.PHP
and makeit.php.
56. What
is meant by nl2br()?
nl2br() inserts
a HTML tag <br> before all new line characters \n in a string.
echo nl2br("god bless \n
you");
output:
god bless<br>
you
57. How
can I retrieve values from one database server and store them in other database
server using PHP?
For this
purpose, you can first read the data from one server into session variables.
Then connect to other server and simply insert the data into the database.
58. In
how many ways we can retrieve data in the result set of MYSQL using PHP?
mysql_fetch_array - Fetch
a result row as an associative array, a numeric array, or both
mysql_fetch_assoc - Fetch
a result row as an associative array
mysql_fetch_object - Fetch
a result row as an object
mysql_fetch_row - Get a result
row as an enumerated array
59. What
are the functions for IMAP?
Internet
message access protocol (IMAP) is one of the two most prevalent Internet
standard protocols for e-mail retrieval, the other being the Post Office
Protocol (POP).Virtually all modern e-mail clients and mail servers support
both protocols as a means of transferring e-mail messages from a server. IMAP
was designed by Mark Crispin in 1986. IMAP was previously known as Internet
Mail Access Protocol, Interactive Mail Access Protocol (RFC 1064), and Interim
Mail Access Protocol. The following are the some of IMAP functions commonly
used.
imap_body - Read the message body
imap_check - Check current mailbox
imap_delete - Mark a message for deletion from
current mailbox
imap_mail - Send an email message
imap_open - Open
an IMAP stream to a mailbox
imap_close - Close an IMAP stream
imap_create - Alias of imap_createmailbox
imap_createmailbox - Create
a new mailbox
imap_ping - Check
if the IMAP stream is still active
60. How
can we get the properties (size, type, width, height) of an image using php
image functions?
getimagesize() - To know
the image size
imagesx() - To
know the image width
imagesy() - To
know the image height
exif_imagetype - When a
correct signature is found, the appropriate constant value
will
be returned otherwise the return value is FALSE.
The return value is the same value that
getimagesize()
returns in index 2 but exif_imagetype() is
much faster.
The
constant values mentioned above are IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG,
IMAGETYPE_SWF, IMAGETYPE_PSD ,IMAGETYPE_BMP, IMAGETYPE_TIFF_II (intel byte
order), IMAGETYPE_TIFF_MM (motorola byte order), IMAGETYPE_JPC,IMAGETYPE_JP2, IMAGETYPE_JPX,
IMAGETYPE_JB2, IMAGETYPE_SWC, IMAGETYPE_IFF, IMAGETYPE_WBMP, IMAGETYPE_XBM, IMAGETYPE_ICO
61. How
can we take a backup of a mysql table and how can we restore it?
Create a full
backup of your database:
shell> mysqldump
tab=/path/to/some/dir opt db_name
Or
shell> mysqlhotcopy db_name
/path/to/some/dir
The full backup file is just a set of
SQL statements, so restoring it is very easy:
shell> mysql
"."Executed";
Another way To backup:
BACKUP TABLE tbl_name TO
/path/to/backup/directory
Another way To restore:
RESTORE TABLE tbl_name FROM
/path/to/backup/directory
62. What
is the maximum size of a file that can be uploaded using PHP and how can we
change this?
Maximum upload
size by default is 2MB. You can change maximum size of a file set
upload_max_filesize variable in php.ini file
63. 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.
-> Is used to access the methods
through objects
64. What
type of inheritance that php supports?
In PHP an
extended class is always dependent on a single base class, that is multiple
inheritance is not supported. Classes are extended using the keyword 'extends'.
65. What
changes I have to do in php.ini file for file uploading?
Make the following line uncomment like:
Whether to allow HTTP file uploads.
file_uploads = On
Temporary directory for HTTP uploaded
files (will use system default if not specified).
upload_tmp_dir = C:\apache2triad\temp
Maximum allowed size for uploaded
files.
upload_max_filesize = 2M
66. Steps
for the payment gateway processing?
An online
payment gateway is the interface between your merchant account and your Web
site. The online payment gateway allows you to immediately verify credit card
transactions and authorize funds on a customer's credit card directly from your
Web site. It then passes the transaction off to your merchant bank for
processing, commonly referred to as transaction batching.
67. What
is the difference between Reply-to and Return-path in the headers of a mail
function?
Reply-to :
Reply-to is
where to delivery the reply of the mail.
Return-path :
Return path is
when there is a mail delivery failure occurs then where to delivery the failure
notification.
68. How
to store the uploaded file to the final location?
move_uploaded_file
( string filename, string destination)
This function checks to ensure that the
file designated by filename is a valid upload file (meaning that it was
uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will
be moved to the filename given by destination.
If filename is
not a valid upload file, then no action will occur, and move_uploaded_file()
will return FALSE.
If filename is
a valid upload file, but cannot be moved for some reason, no action will occur,
and move_uploaded_file() will return FALSE. Additionally, a warning will be
issued.
69. 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.
70. 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.
71. Explain
about Type Juggling in php?
PHP does not
require (or support) explicit type definition in variable declaration; a
variable's type is determined by the context in which that variable is used.
That is to say, if you assign a string value to variable $var, $var becomes a
string. If you then assign an integer value to $var, it becomes an integer.
An example of
PHP's automatic type conversion is the addition operator '+'. If any of the
operands is a float, then all operands are evaluated as floats, and the result
will be a float. Otherwise, the operands will be interpreted as integers, and
the result will also be an integer. Note that this does NOT change the types of
the operands themselves; the only change is in how the operands are evaluated.
$foo += 2;
// $foo is now an integer (2)
$foo = $foo + 1.3; //
$foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs"; // $foo is integer (15)
If the last two examples above seem
odd, see String conversion to numbers.
If you wish to change the type of a
variable, see settype ( ).
If you would like to test any of the
examples in this section, you can use the var_dump ( ) function.
Note: The behavior of an automatic
conversion to array is currently undefined.
72. What
does a special set of tags <?= and ?> do in PHP?
The output is
displayed directly to the browser.
73. 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.
74. 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.
75. 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.
76. 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.
77. I
want to combine two variables together: $var1 = 'Welcome to ';
$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.
78. What
is CAPTCHA?
CAPTCHA stands
for Completely Automated Public Turing Test to tell Computers and Humans Apart.
To prevent spammers from automatically fill out forms, CAPTCHA programmers will
generate an image containing distorted images of a string of numbers and
letters. Computers cannot determine what the numbers and letters are from the
image but humans have great pattern recognition abilities and will be able to
fairly accurately determine the string of numbers and letters. By entering the
numbers and letters from the image in the validation field, the application can
be fairly assured that there is a human client using it. To read more look
here:
79. If
you have to work with dates in the following format: "Tuesday, February
14, 2006 @ 10:39 am", how can you convert them to another format, that is
easier to use?
The strtotime
function can convert a string to a timestamp. A timestamp can be converted to
date format. So it is best to store the dates as timestamp in the database, and
just output them in the format you like.
So let's say we have
$date = "Tuesday, February 14,
2006 @ 10:39 am";
In order to convert that to a
timestamp, we need to get rid of the "@" sign, and we can use the
remaining string as a parameter for the strtotime function.
So we have
$date = str_replace("@
","",$date);
$date = strtotime($date);
now $date is a timestamp
and we can say:
echo date("d M Y",$date);
80. How
i can get ip address?
We can use
SERVER variable
$_SERVER['SERVER_ADDR'] and
getenv("REMOTE_ADDR") functions to get the IP address.
81. What
is differenc between mysql_connect and mysql_pconnect?
mysql_pconnect
establishes a persistent connection. If you don't need one (such as a website
that is mostly HTML files or PHP files that don't call the db) then you don't
need to use it. mysql_connect establishes a connection for the duration of the
script that access the db. Once the script has finished executing it closes the
connection. The only time you need to close the connection manually is if you
jump out of the script for any reason.
If you do use
mysql_pconnect. You only need to call it once for the session. That's the
beauty of it. It will hold open a connection to the db that you can use over
and over again simply by calling the resource ID whenever you need to interact
with the db.
82. What
are the superglobal variables in php?.
There are number of superglobal variables in php
• $GLOBALS
• $_SERVER
• $_GET
• $_POST
• $_FILES
• $_COOKIE
• $_SESSION
• $_REQUEST
• $_ENV
83. What
is the difference between Primary Key and Unique key?
Both Primary
Key and Unique Key enforces uniqueness of the column on which they are defined.
But by default Primary Key creates a Clustered Index on the column, where are
Unique Key creates a Nonclustered Index by default. Another major difference is
that, Primary Key doesn’t allow NULLs, but Unique Key allows one NULL only.
84. what
are the most common caching policy approaches ?
1)Time triggered caching (expiry
timestamp).
2)Content change triggered caching
(sensitive content has changed, so cache must be updated).
3)Manually triggered caching (manually
inform the application that information is outdated, and force a new cache
creation).
85. How
to prevent web browser to image caching ?.
The simple way
to prevent image caching is to append time stamp with the name on image.
Example :
<img src=’image.jpg?<?php echo
time() ?>’ />
In the
above code browser understand a new image at every call. But HTML parser
understands“image.jpg” for every call.
86. How
can we increase Memory size in php during run time?
using
ini_set(‘memory_limit’,’15M’); //
now 15M space is set during run time.
87. How
to increase Execution Time Limit in php Using ini_set()
To increase the execution time for any php
script simple use below code.
ini_set(‘max_execution_time’, 240); //240seconds = 4
minutes
88. Which
of the variable that PHP makes automatically available to you ?
$_SERVER
89. Where
the all webserver information is stored in PHP ?
$_SERVER
is a PHP variable that contains all web server information It is known as a
superglobal.
90. Differentiate
between DROP a table and TRUNCATE a table?
DROP - It will
delete the table and table data.
TRUNCATE - It will delete data of the
table but not the table definition.
91. How
will you change the name of a column in a table?
ALTER TABLE table_name CHANGE
old_column_name new_column _name[new type]
92. How
will you create a database using PHP and MySQL?
By using :
mysql_create_db("Database
Name")
93. What
is the purpose of the following files having extensions: frm, myd, and myi?
What these files contain?
In MySQL, the
default table type is MyISAM.
Each MyISAM table is stored on disk in
three files. The files have names that begin with the table name and have an
extension to indicate the file type.
The '.frm' file stores the table
definition.
The data file has a '.MYD' (MYData)
extension.
The index file has a '.MYI' (MYIndex)
extension,
94. What
is the maximum length of a table name, a database name, or a field name in
MySQL?
Database name : 64
characters
Table name : 64
characters
Column name : 64
characters
95. How
many values can the SET function of MySQL take?
MySQL SET
function can take zero or more values, but at the maximum it can take 64
values.
96. What
are the other commands to know the structure of a table using MySQL commands
except EXPLAIN command?
DESCRIBE
table_name;
97. How
can we find the number of rows in a table using MySQL?
SELECT COUNT(*)
FROM table_name;
98. How
can we find the number of rows in a result set using PHP?
Here is how can
you find the number of rows in a result set in PHP:
$result = mysql_query($any_valid_sql,
$database_link);
$num_rows = mysql_num_rows($result);
echo "$num_rows rows found";
99. How
many ways we can we find the current date using MySQL?
SELECT CURDATE();
SELECT CURRENT_DATE();
SELECT CURTIME();
SELECT CURRENT_TIME();
100. Give
the syntax of GRANT commands?
The generic
syntax for GRANT is as following
GRANT [rights] on [database] TO
[username@hostname] IDENTIFIED BY [password]
Now rights can be:
a) ALL privilages
b) Combination of CREATE, DROP, SELECT,
INSERT, UPDATE and DELETE etc.
We can grant
rights on all databse by usingh *.* or some specific database by database.* or
a specific table by database.table_name.
101. Give
the syntax of REVOKE commands?
The generic
syntax for revoke is as following
REVOKE [rights] on [database] FROM
[username@hostname]
Now rights can be:
a) ALL privileges
b) Combination of CREATE, DROP, SELECT,
INSERT, UPDATE and DELETE etc.
We can grant
rights on all database by using *.* or some specific database by database.* or
a specific table by database.table_name.
102. What
is the difference between CHAR and VARCHAR data types?
CHAR is a fixed
length data type. CHAR(n) will take n characters of storage even if you enter
less than n characters to that column. For example, "Hello!" will be
stored as "Hello! " in CHAR(10) column.
VARCHAR is a
variable length data type. VARCHAR(n) will take only the required storage for
the actual number of characters entered to that column. For example,
"Hello!" will be stored as "Hello!" in VARCHAR(10) column.
103. How
can we encrypt and decrypt a data present in a mysql table using mysql?
AES_ENCRYPT()
and AES_DECRYPT()
AES_ENCRYPT(str, key_str)
AES_DECRYPT(crypt_str, key_str)
104. How
can we know the number of days between two given dates using MySQL?
Use DATEDIFF()
SELECT DATEDIFF(NOW(),'2006-07-01');
105. What
is the difference between GROUP BY and ORDER BY in SQL?
To sort a
result, use an ORDER BY clause.
The most general way to satisfy a GROUP
BY clause is to scan the whole table and create a new temporary table where all
rows from each group are consecutive, and then use this temporary table to
discover groups and apply aggregate functions (if any).
ORDER BY [col1],[col2],...[coln]; Tells
DBMS according to what columns it should sort the result. If two rows will have
the same value in col1 it will try to sort them according to col2 and so on.
GROUP BY [col1],[col2],...[coln]; Tells
DBMS to group (aggregate) results with same value of column col1. You can use
COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in
group, sum all values or view average.
106. How
can increase the performance of MySQL select query?
We can use
LIMIT to stop MySql for further search in table after we have received our
required no. of records, also we can use LEFT JOIN or RIGHT JOIN instead of
full join in cases we have related data in two or more tables.
107. How
can we change the name of a column of a table?
MySQL query to rename table:
RENAME TABLE tbl_name TO new_tbl_name
or,
ALTER TABLE tableName CHANGE OldName newName
108. How
can we repair a MySQL table?
The syntex for
repairing a mysql table is:
REPAIR TABLE tablename
REPAIR TABLE tablename QUICK
REPAIR TABLE tablename EXTENDED
This command will repair the table
specified.
If QUICK is given, MySQL will do a
repair of only the index tree.
If EXTENDED is given, it will create
index row by row.
109. How
can I load data from a text file into a table?
The MySQL
provides a LOAD DATA INFILE command. You can load data from a file. Great tool
but you need to make sure that:
a) Data must be delimited
b) Data fields must match table columns
correctly
110. What
is Joomla in PHP?
Joomla is a
content management system. Powerful online applications and web sites are build
using Joomla. Joomla is an open source CMS tool. Clients can easily manage
their web sites with minimal amount of instructions. It is highly extensible.
Joomla runs off PHP or MySQL. Joomla is used to create, maintain a structured,
flexible portal, add or edit content, changes the look and feel of the site.
PHP scripting is used and persisted most of its data / information in MySQL
database.
111. What
is meant by MIME?
MIME is
Multipurpose Internet Mail Extensions is an Internet standard for the format of
e-mail.
WWW's ability
to recognize and handle files of different types is largely dependent on the
use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard
provides for a system of registration of file types with information about the
applications needed to process them. This information is incorporated into Web
server and browser software, and enables the automatic recognition and display
of registered file types.
However
browsers also uses MIME standard to transmit files. MIME has a header which is
added to a beginning of the data. When browser sees such header it shows the
data as it would be a file (for example image)
Some examples of MIME types:
audio/x-ms-wmp
image/png
application/x-shockwave-flash
112. If
we login more than one browser windows at the same time with same user and
after that we close one window, then is the session is exist to other windows
or not? And if yes then why? If no then why?
Session depends
on browser. If browser is closed then session is lost. The session data will be
deleted after session time out. If connection is lost and you recreate
connection, then session will continue in the browser.
113. What
are the difference between abstract class and interface?
Abstract class:
abstract
classes are the class where one or more methods are abstract but not
necessarily all method has to be abstract. Abstract methods are the methods,
which are declare in its class but not define. The definition of those methods
must be in its extending class.
Interface:
Interfaces are
one type of class where all the methods are abstract. That means all the
methods only declared but not defined. All the methods must be define by its
implemented class.
114. What
are the advantages of stored procedures, triggers, indexes?
Stored procedures :
A stored
procedure is a set of SQL commands that can be compiled and stored in the
server. Once this has been done, clients don't need to keep re-issuing the
entire query but can refer to the stored procedure. This provides better
overall performance because the query has to be parsed only once, and less
information needs to be sent between the server and the client. You can also
raise the conceptual level by having libraries of functions in the server.
However, stored procedures of course do increase the load on the database
server system, as more of the work is done on the server side and less on the
client (application) side.
Triggers :
Triggers will
also be implemented. A trigger is effectively a type of stored procedure, one
that is invoked when a particular event occurs. For example, you can install a
stored procedure that is triggered each time a record is deleted from a
transaction table and that stored procedure automatically deletes the
corresponding customer from a customer table when all his transactions are
deleted.
Indexes :
Indexes are
used to find rows with specific column values quickly. Without an index, MySQL
must begin with the first row and then read through the entire table to find
the relevant rows. The larger the table, the more this costs. If the table has
an index for the columns in question, MySQL can quickly determine the position
to seek to in the middle of the data file without having to look at all the
data. If a table has 1,000 rows, this is at least 100 times faster than reading
sequentially. If you need to access most of the rows, it is faster to read
sequentially, because this minimizes disk seeks.
115. What
are the different ways to login to a remote server? Explain the means,
advantages and disadvantages?
Some of the ways to logon to a remote
server are :
Use ssh
Use telnet if you concern with security
We can also use rlogin to logon to a
remote server.
We can use Team viewer like
applications
116. 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. 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.