Professional Documents
Culture Documents
Php Questions
Php Questions
Php Questions
co
• It can handle forms, i.e. gather data from files, save data to a file, through email you can send
data, return data to the user.
• You can add, delete, modify elements within your database with the help of PHP.
• Using PHP, you can restrict users to access some pages of your website and also encrypt data.
Q10. What are the rules to determine the “truth” of any value which is not already
of the Boolean type?
The rules to determine the “truth” of any value which is not already of the Boolean type are:
• If the value is a number, it is false if exactly equal to zero and true otherwise.
• If the value is a string, it is false if the string is empty (has zero characters) or is the string “0”,
and is true otherwise.
• Values of type NULL are always false.
• If the value is an array, it is false if it contains no other values, and it is true otherwise. For an
object, containing a value means having a member variable that has been assigned a value.
• Valid resources are true (although some functions that return resources when they are successful
will return FALSE when unsuccessful).
• Don’t use double as Booleans.
Q14. What are the differences between PHP constants and variables?
Constants Variables
There is no need to write dollar ($) sign before a
A variable must be written with the dollar ($) sign
constant
Constants can only be defined using the define()
Variables can be defined by simple assignment
function
Constants may be defined and accessed anywhere In PHP, functions by default can only create and
without regard to variable scoping rules. access variables within its own scope.
Variables can be redefined for each path
Constants cannot be redefined or undefined.
individually.
Q17. What are the two most common ways to start and finish a PHP block of code?
The two most common ways to start and finish a PHP block of code are:
• It doesn’t have static methods and • It allows to have static Methods and Properties
properties in a class in a class
1
<?php class Foo { private $name; private $link; public function
2
__construct($name) { $this->;name = $name;
3
}
4
public function setLink(Foo $link){
5 $this->;link = $link;
6 }
7 public function __destruct() {
8 echo 'Destroying: ', $this->name, PHP_EOL;
9 }
10 }
11 ?>
12
Q26. What are include() and require() functions?
The Include() function is used to put data of one PHP file into another PHP file. If errors occur then the
include() function produces a warning but does not stop the execution of the script and it will continue
to execute.
The Require() function is also used to put data of one PHP file to another PHP file. If there are any
errors then the require() function produces a warning and a fatal error and stops the execution of the
script.
1
<?php
2
$colors = array("blue", "white", "black");
3
foreach ($colors as $value) {
4
echo "$value
5
";
6
}
7
?>
8
Q31. What is the difference between single quoted string and double quoted string?
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with
their values as well as specially interpreting certain character sequences. For example –
1 <?php
2 $variable = "name";
4 print($statement);
5 print "
6 ;"
8 print($statement);
9 ?>
Q33. How is it possible to set an infinite execution time for PHP script?
The set_time_limit(0) added at the beginning of a script sets to infinite the time of execution to not
have the PHP error ‘maximum execution time exceeded.’ It is also possible to specify this in the php.ini
file.
The POST method transfers information via HTTP headers. The information is encoded as described
in case of GET method and put into a header called QUERY_STRING.
• GET can’t be used to send binary data, like • The POST method can be used to send
images or word documents, to the server. ASCII as well as binary data.
• The data sent by GET method can be • The data sent by POST method goes
accessed using QUERY_STRING through HTTP header so security depends
environment variable. on HTTP protocol.
• The PHP provides $_GET associative array • The PHP provides $_POST associative
to access all the sent information using array to access all the sent information
GET method. using POST method.
1 <?php
2 function thisFuncTakesACallback($callbackFunc)
3 {
5 ";
6 $callbackFunc();
7 }
8 function thisFuncGetsCalled()
9 {
11 ";
12 }
13 thisFuncTakesACallback( 'thisFuncGetsCalled' );
14 ?>
15
16
function ($v) { return $v > 2; } is the lambda function definition. We can store it in a variable so that it
can be reusable.
__destruct() __sleep()
__construct() __wakeup()
__call() __toString()
__get() __invoke()
__set() __set_state()
__isset() __clone()
__unset() __debugInfo()
The crypt () function is used to create one way encryption. It takes one input string and one optional
parameter. The function is defined as: crypt (input_string, salt), where input_string consists of the
string that has to be encrypted and salt is an optional parameter. PHP uses DES for encryption. The
format is as follows:
<?php $password = crypt('edureka'); print $password. "is the
1 encrypted version of edureka"; ?>
Q48. How to connect to a URL in PHP?
PHP provides a library called cURL that may already be included in the installation of PHP by default.
cURL stands for client URL, and it allows you to connect to a URL and retrieve information from that
page such as the HTML content of the page, the HTTP headers and their associated data.
2 }
3 ?>
The example shows how to send Email function argument $email Type hinted of Email Class. It means
to call this function you must have to pass an email object otherwise an error is generated.
Q50. What is the difference between runtime exception and compile time
exception?
An exception that occurs at compile time is called a checked exception. This exception cannot be
ignored and must be handled carefully. For example, if you use FileReader class to read data from the
file and the file specified in class constructor does not exist, then a FileNotFoundException occurs and
you will have to manage that exception. For the purpose, you will have to write the code in a try-catch
block and handle the exception. On the other hand, an exception that occurs at runtime is called
unchecked-exception.
javatpoint.com
1) What is PHP?
PHP stands for Hypertext Preprocessor. It is an open source server-side scripting language which is
widely used for web development. It supports many databases like MySQL, Oracle, Sybase, Solid,
PostgreSQL, generic ODBC etc.
More Details...
49) What is the method to execute a PHP script from the command line?
You should just run the PHP command line interface (CLI) and specify the file name of the script to be
executed as follows.
Dear readers, these PHP Programming Language Interview Questions have been designed specially
to get you acquainted with the nature of questions you may encounter during your interview for the
subject of PHP Programming Language. As per my experience good interviewers hardly plan to ask
any particular question during your interview, normally questions start with some basic concept of the
subject and later they continue based on further discussion and what you answer −
PHP is a recursive acronym for "PHP: Hypertext Preprocessor". PHP is a server side scripting language
that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even
build entire e-commerce sites.
Common uses of PHP −
• PHP performs system functions, i.e. from files on a system it can create, open, read, write, and
close them.
• PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send
data, return data to the user.
• You add, delete, modify elements within your database thru PHP.
• Access cookies variables and set cookies.
• Using PHP, you can restrict users to access some pages of your website.
• It can encrypt data.
All PHP code must be included inside one of the three special markup tags ate are recognised by the
PHP Parser.
<?php PHP code goes here ?>
<? PHP code goes here ?>
<script language="php"> PHP code goes here </script>
Most common tag is the <?php...?>
The PHP configuration file, php.ini, is the final and most immediate way to affect PHP's functionality.
The php.ini file is read each time PHP is initialized.in other words, whenever httpd is restarted for the
module version or with each script execution for the CGI version. If your change isn.t showing up,
remember to stop and restart httpd. If it still isn.t showing up, use phpinfo() to check the path to php.ini.
The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The
mechanism for doing so is known as 'escaping to PHP.'
Whitespace is the stuff you type that is typically invisible on the screen, including spaces, tabs, and
carriage returns (end-of-line characters). PHP whitespace insensitive means that it almost never matters
how many whitespace characters you have in a row.one whitespace character is the same as many such
characters.
No, PHP is partially case sensitive.
Here are the most important things to know about variables in PHP.
• All variables in PHP are denoted with a leading dollar sign ($).
• The value of a variable is the value of its most recent assignment.
• Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
• Variables can, but do not need, to be declared before assignment.
• Variables in PHP do not have intrinsic types - a variable does not know in advance whether it
will be used to store a number or a string of characters.
• Variables used before they are assigned have default values.
• PHP does a good job of automatically converting types from one to another when necessary.
• PHP variables are Perl-like.
PHP has a total of eight data types which we use to construct our variables −
• Integers − are whole numbers, without a decimal point, like 4195.
• Doubles − are floating-point numbers, like 3.14159 or 49.1.
• Booleans − have only two possible values either true or false.
• NULL − is a special type that only has one value: NULL.
• Strings − are sequences of characters, like 'PHP supports string operations.'
• Arrays − are named and indexed collections of other values.
• Objects − are instances of programmer-defined classes, which can package up both other kinds
of values and functions that are specific to the class.
• Resources − are special variables that hold references to resources external to PHP (such as
database connections).
Rules for naming a variable are following −
• Variable names must begin with a letter or underscore character.
• A variable name can consist of numbers, letters, underscores but you cannot use characters like
+ , - , % , ( , ) . & , etc
Here are the rules for determine the "truth" of any value not already of the Boolean type −
• If the value is a number, it is false if exactly equal to zero and true otherwise.
• If the value is a string, it is false if the string is empty (has zero characters) or is the string "0",
and is true otherwise.
• Values of type NULL are always false.
• If the value is an array, it is false if it contains no other values, and it is true otherwise. For an
object, containing a value means having a member variable that has been assigned a value.
• Valid resources are true (although some functions that return resources when they are successful
will return FALSE when unsuccessful).
• Don't use double as Booleans.
NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply
assign it like this −
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive; you could
just as well have typed −
$my_var = null;
A variable that has been assigned NULL has the following properties:
It evaluates to FALSE in a Boolean context.
It returns FALSE when tested with IsSet() function.
To define a constant you have to use define() function and to retrieve the value of a constant, you have
to simply specifying its name. Unlike with variables, you do not need to have a constant with a $.
As indicated by the name, this function will return the value of the constant. This is useful when you
want to retrieve value of a constant, but you do not know its name, i.e. It is stored in a variable or
returned by a function.
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data (boolean, integer, float and string) can be contained in constants.
• There is no need to write a dollar sign ($) before a constant, where as in Variable one has to
write a dollar sign.
• Constants cannot be defined by simple assignment, they may only be defined using the define()
function.
• Constants may be defined and accessed anywhere without regard to variable scoping rules.
• Once the Constants have been set, may not be redefined or undefined.
PHP provides a large number of predefined constants to any script which it runs known as magic
constants.
_LINE_ − The current line number of the file.
_FILE_ − The full path and filename of the file. If used inside an include,the name of the included file
is returned. Since PHP 4.0.2, _FILE_ always contains an absolute path whereas in older versions it
contained relative path under some circumstances.
_FUNCTION_ − The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the
function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
_CLASS_ − The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as
it was declared (case-sensitive). In PHP 4 its value is always lowercased.
_METHOD_ − The class method name. (Added in PHP 5.0.0) The method name is returned as it was
declared (case-sensitive).
break terminates the for loop or switch statement and transfers execution to the statement immediately
following the for loop or switch.
continue causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.
The foreach statement is used to loop through arrays. For each pass the value of the current array
element is assigned to $value and the array pointer is moved by one and in the next pass next element
will be processed.
foreach (array as value)
{
code to be executed;
}
Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
Associative array − An array with strings as index. This stores element values in association with key
values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are accessed using
multiple indices.
To concatenate two string variables together, use the dot (.) operator −
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
The strpos() function is used to search for a string or character within a string. If a match is found in the
string, this function will return the position of the first match. If no match is found, it will return
FALSE. Let's see if we can find the string "world" in our string −
<?php
echo strpos("Hello world!","world");
?>
PHP provides a function getenv() to access the value of all the environment variables.
One of the environemnt variables set by PHP is HTTP_USER_AGENT which identifies the user's
browser and operating system.
The PHP rand() function is used to generate a random number. This function can generate numbers
with-in a given range. The random number generator should be seeded to prevent a regular pattern of
numbers being generated. This is achieved using the srand() function that specifiies the seed number as
its argument.
The PHP default variable $_PHP_SELF is used for the PHP script name and when you click "submit"
button then same PHP script will be called.
The PHP header() function supplies raw HTTP headers to the browser and can be used to redirect it to
another location. The redirection script should be at the very top of the page to prevent any other part of
the page from loading. The target is specified by the Location: header as the argument to the header()
function. After calling this function the exit() function can be used to halt parsing of rest of the code.
The HTTP header will be different from the actual header where we send Content-Type as text/html\n\
n. In this case content type will be application/octet-stream and actual file name will be concatenated
alongwith it. For example,if you want make a FileName file downloadable from a given link then its
syntax will be as follows.
#!/usr/bin/perl
# HTTP Header
print "Content-Type:application/octet-stream; name=\"FileName\"\r\n";
print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n";
# Actual File Content
open( FILE, "<FileName" );
while(read(FILE, $buffer, 100) )
{
print("$buffer");
}
The PHP provides $_GET associative array to access all the sent information using GET method.
The PHP provides $_POST associative array to access all the sent information using POST method.
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We
will discuss $_COOKIE variable when we will explain about cookies. The PHP $_REQUEST variable
can be used to get the result from form data sent with both the GET and POST methods.
array() − Creates an array.
sort() − Sorts an array.
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with
their values as well as specially interpreting certain character sequences.
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
print "<br />";
$literally = "My $variable will print!\\n";
print($literally);
?>
To concatenate two string variables together, use the dot (.) operator.
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We
will discuss $_COOKIE variable when we will explain about cookies. The PHP $_REQUEST variable
can be used to get the result from form data sent with both the GET and POST methods.
There are two PHP functions which can be used to included one PHP file into another PHP file.
• The include() Function
• The require() Function
If there is any problem in loading a file then the require() function generates a fatal error and halt the
execution of the script whereas include() function generates a warning but the script will continue
execution.
The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and
then mode in which to operate. "r" mode opens the file for reading only and places the file pointer at
the beginning of the file.
Once a file is opened using fopen() function it can be read with a function called fread(). This function
requires two arguments. These must be the file pointer and the length of the file expressed in bytes.
The files's length can be found using the filesize() function which takes the file name as its argument
and returns the size of the file expressed in bytes.
File's existence can be confirmed using file_exist() function which takes file name as an argument.
Yes! You can set a parameter to have a default value if the function's caller doesn't pass it.
PHP provided setcookie() function to set a cookie. This function requires upto six arguments and
should be called before <html> tag. For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables.
You can use isset() function to check if a cookie is set or not.
To delete a cookie you should call setcookie() with the name argument only.
A PHP session is easily started by making a call to the session_start() function.This function first
checks if a session is already started and if none is started then it starts one. It is recommended to put
the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed
during lifetime of a session.
Make use of isset() function to check if session variable is already set or not.
Here is the example to unset a single variable −
<?php
unset($_SESSION['counter']);
?>
PHP uses mysql_query function to create a MySQL database. This function takes two parameters and
returns TRUE on success or FALSE on failure.
bool mysql_query( sql, connection );
Its simplest function mysql_close PHP provides to close a database connection. This function takes
connection resource returned by mysql_connect function. It returns TRUE on success or FALSE on
failure.
bool mysql_close ( resource $link_identifier );
Function definitions in child classes override definitions with the same name in parent classes. In a
child class, we can modify the definition of a function inherited from parent class.
Interfaces are defined to provide a common function names to the implementors. Different
implementors can implement those interfaces according to their requirements. You can say, interfaces
are skeltons which are implemented by developers.
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by
prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
What is Next?
Further you can go through your past assignments you have done with the subject and make sure you
are able to speak confidently on them. If you are fresher then interviewer does not expect you will
answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever
you answered, you must have answered with confidence. So just feel confident during your interview.
We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future
endeavor. Cheers :-)
guru99.com
7) How to run the interactive PHP shell from the command line interface?
Just use the PHP CLI program with the option -a as follows:
php -a
8) What is the correct and the most two common way to start and finish a PHP block of code?
The two most common ways to start and finish a PHP script are:
<?php [ --- PHP code---- ] ?> and <? [--- PHP code ---] ?>
23) How can we display information of a variable and readable by a human with PHP?
To be able to display a human-readable result we use print_r().
24) How is it possible to set an infinite execution time for PHP script?
The set_time_limit(0) added at the beginning of a script sets to infinite the time of execution to not
have the PHP error 'maximum execution time exceeded.' It is also possible to specify this in the php.ini
file.
25) What does the PHP error 'Parse error in PHP - unexpected T_variable at line x' means?
This is a PHP syntax error expressing that a mistake at the line x stops parsing and executing the
program.
26) What should we do to be able to export data into an Excel file?
The most common and used way is to get data into a format supported by Excel. For example, it is
possible to write a .csv file, to choose for example comma as a separator between fields and then to
open the file with Excel.
27) What is the function file_get_contents() useful for?
file_get_contents() lets reading a file and storing it in a string variable.
28) How can we connect to a MySQL database from a PHP script?
To be able to connect to a MySQL database, we must use mysqli_connect() function as follows:
<!--?php $database = mysqli_connect("HOST", "USER_NAME", "PASSWORD");
mysqli_select_db($database,"DATABASE_NAME"); ?-->
35) How can we access the data sent through the URL with the POST method?
To access the data sent this way, you use the $_POST array.
Imagine you have a form field called 'var' on the form when the user clicks submit to the post form, you
can then access the value like this:
$_POST["var"];
$variable2 = 'World';
$variable3 = $variable1.$variable2;
Or
2- $variable3 = "$variable1$variable2";
$variable3 will contain "Hello World". The first code is faster than the second code especially for large
large sets of data.
64) what is the definition of a session?
A session is a logical object enabling us to preserve temporary data across multiple PHP pages.
65) How to initiate a session in PHP?
The use of the function session_start() lets us activating a session.
66) How can you propagate a session id?
You can propagate a session id via cookies or URL parameters.
67) What is the meaning of a Persistent Cookie?
A persistent cookie is permanently stored in a cookie file on the browser's computer. By default,
cookies are temporary and are erased if we close the browser.
68) When do sessions end?
Sessions automatically end when the PHP script finishes executing but can be manually ended using
the session_write_close().
69) What is the difference between session_unregister() and session_unset()?
The session_unregister() function unregister a global variable from the current session and the
session_unset() function frees all session variables.
70) What does $GLOBALS mean?
$GLOBALS is associative array including references to all variables which are currently defined in the
global scope of the script.
71) What does $_SERVER mean?
$_SERVER is an array including information created by the web server such as paths, headers, and
script locations.
72) What does $_FILES means?
$_FILES is an associative array composed of items sent to the current script via the HTTP POST
method.
73) What is the difference between $_FILES['userfile']['name'] and $_FILES['userfile']
['tmp_name']?
$_FILES['userfile']['name'] represents the original name of the file on the client machine,
$_FILES['userfile']['tmp_name'] represents the temporary filename of the file stored on the server.
74) How can we get the error when there is a problem to upload a file?
$_FILES['userfile']['error'] contains the error code associated with the uploaded file.
75) How can we change the maximum size of the files to be uploaded?
We can change the maximum size of files to be uploaded by changing upload_max_filesize in php.ini.
76) What does $_ENV mean?
$_ENV is an associative array of variables sent to the current PHP script via the environment method.
77) What does $_COOKIE mean?
$_COOKIE is an associative array of variables sent to the current PHP script using the HTTP Cookies.
78) What does the scope of variables mean?
The scope of a variable is the context within which it is defined. For the most part, all PHP variables
only have a single scope. This single scope spans included and required files as well.
79) what the difference between the 'BITWISE AND' operator and the 'LOGICAL AND'
operator?
$a and $b: TRUE if both $a and $b are TRUE.
$a & $b: Bits that are set in both $a and $b are set.
80) What are the two main string operators?
The first is the concatenation operator ('.'), which returns the concatenation of its right and left
arguments. The second is ('.='), which appends the argument on the right to the argument on the left.
81) What does the array operator '===' means?
$a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
82) What is the differences between $a != $b and $a !== $b?
!= means inequality (TRUE if $a is not equal to $b) and !== means non-identity (TRUE if $a is not
identical to $b).
83) How can we determine whether a PHP variable is an instantiated object of a certain class?
To be able to verify whether a PHP variable is an instantiated object of a certain class we use
instanceof.
84) What is the goto statement useful for?
The goto statement can be placed to enable jumping inside the PHP program. The target is pointed by a
label followed by a colon, and the instruction is specified as a goto statement followed by the desired
target label.
85) what is the difference between Exception::getMessage and Exception:: getLine?
Exception::getMessage lets us getting the Exception message and Exception::getLine lets us getting the
line in which the exception occurred.
86) What does the expression Exception::__toString means?
Exception::__toString gives the String representation of the exception.
87) How is it possible to parse a configuration file?
The function parse_ini_file() enables us to load in the ini file specified in filename and returns the
settings in it in an associative array.
88) How can we determine whether a variable is set?
The boolean function isset determines if a variable is set and is not NULL.
89) What is the difference between the functions strstr() and stristr()?
The string function strstr(string allString, string occ) returns part of allString from the first occurrence
of occ to the end of allString. This function is case-sensitive. stristr() is identical to strstr() except that it
is case insensitive.
90) what is the difference between for and foreach?
for is expressed as follows:
for (expr1; expr2; expr3)
statement
The first expression is executed once at the beginning. In each iteration, expr2 is evaluated. If it is
TRUE, the loop continues, and the statements inside for are executed. If it evaluates to FALSE, the
execution of the loop ends. expr3 is tested at the end of each iteration.
However, foreach provides an easy way to iterate over arrays, and it is only used with arrays and
objects.
91) Is it possible to submit a form with a dedicated button?
It is possible to use the document.form.submit() function to submit the form. For example: <input
type=button value="SUBMIT" onClick="document.form.submit()">
92) What is the difference between ereg_replace() and eregi_replace()?
The function eregi_replace() is identical to the function ereg_replace() except that it ignores case
distinction when matching alphabetic characters.
93) Is it possible to protect special characters in a query string?
Yes, we use the urlencode() function to be able to protect special characters.
94) What are the three classes of errors that can occur in PHP?
The three basic classes of errors are notices (non-critical), warnings (serious errors) and fatal errors
(critical errors).
95) What is the difference between characters \034 and \x34?
\034 is octal 34 and \x34 is hex 34.
96) How can we pass the variable through the navigation between the pages?
It is possible to pass the variables between the PHP pages using sessions, cookies or hidden form fields.
97) Is it possible to extend the execution time of a PHP script?
The use of the set_time_limit(int seconds) enables us to extend the execution time of a PHP script. The
default limit is 30 seconds.
98) Is it possible to destroy a cookie?
Yes, it is possible by setting the cookie with a past expiration time.
99) What is the default session time in PHP?
The default session time in php is until the closing of the browser
100) Is it possible to use COM component in PHP?
Yes, it's possible to integrate (Distributed) Component Object Model components ((D)COM) in PHP
scripts which is provided as a framework.
101) Explain whether it is possible to share a single instance of a Memcache between multiple
PHP projects?
Yes, it is possible to share a single instance of Memcache between multiple projects. Memcache is a
memory store space, and you can run memcache on one or more servers. You can also configure your
client to speak to a particular set of instances. So, you can run two different Memcache processes on
the same host and yet they are completely independent. Unless, if you have partitioned your data, then
it becomes necessary to know from which instance to get the data from or to put into.
102) Explain how you can update Memcached when you make changes to PHP?
When PHP changes you can update Memcached by
• Clearing the Cache proactively: Clearing the cache when an insert or update is made
• Resetting the Cache: It is similar to the first method but rather than just deleting the keys and
waiting for the next request for the data to refresh the cache, reset the values after the insert or
update.
hackr.io
removes extra
characters or spaces ltrim($mystr, "…. hello")
ltrim()
from the left side of
the string
Parses a query string parse_str("empId=1234&name=Sam");
parse_str()
into variables
str_replace replaces specified str_replace("mysite","hackr.io","Welcome to mysite");
() characters of a string
split the string into str_split("welcome")
str_split()
character array
str_word_count("my name is sam");
str_word_c word count of the result = 4
ount() string
strlen("welcome");
calculates length of result = 7
strlen()
the string
strncmp("welcome to mysite","welcome to hackr.io", 11);
compare first few
strncmp()
characters of a string result = 0 if the first 11 characters are same
For more string functions, refer to PHP manual string functions.
The myupload.php file contains code specific to the fule type to be uploaded, for example, image,
document, etc., and details like target path, size, and other parameters.
You can then write the HTML code to upload the file you want by specifying the input type as 'file.'
Question: Draw a comparison between the compile-time exception and the runtime exception.
What are they called?
Answer: Checked exception is the exception that occurs at the compile time. As it is not possible to
ignore this type of exception, it needs to be handled cautiously. An unchecked exception, on the other
side, is the one that occurs during the runtime. If a checked exception is not handled, it becomes an
unchecked exception.
Question: How can you update Memcached when changes are made to PHP?
Answer: There are two ways of updating the Memcached when changes are made to the PHP code:
1. Proactively Clearing the Cache – This means clearing the cache when an insert or update is
made
2. Resetting the Cache – Reset the values once the insert or update is made
Question: How would you connect to a MySQL database from a PHP script?
Answer: To connect to some MySQL database, the mysqli_connect() function is used. It is used in the
following way:
Question: What are constructors and destructors in PHP? Can you provide an example?
Answer: The constructors and destructors in PHP are a special type of functions, which are
automatically called when a PHP class object is created and destroyed, respectively.
While a constructor is used to initialize the private variables of a class, a destructor frees the resourced
created or used by the class.
Here is a code example demonstrating the concept of constructors and destructors:
<?php
class ConDeConExample {
private $name;
private $link;
public function __construct($name) {
$this->name = $name;
}
public function setLink(Foo $link){
$this->link = $link;
}
public function __destruct() {
echo 'Destroying: ', $this->name, PHP_EOL;
}
}
?>
Question: What are the most important advantages of using PHP 7 over PHP 5?
Answer:
• Support for 64-bit Integers – While PHP 7 comes with built-in support for native 64-bit integers
and also for large files, PHP 5 doesn’t provide support for either of them.
• Performance – PHP 7 performs far better than PHP 5. PHP 7 uses PHP-NG (NG stands for Next
Generation), whereas PHP 5 relies on Zend II.
• Return Type – One of the most important downsides of PHP 5 is that it doesn’t allow for
defining the return type of a function. This limitation is eliminated by PHP 7, which allows a
developer to define the type of value returned by any function in the code.
• Error Handling – It is extremely difficult to manage fatal errors in PHP 5. PHP 7, on the
opposite, comes with a new Exception Objects engine. It helps in managing several major
critical errors, which are now replaced with exceptions.
• Anonymous Class – To execute the class only once, for increasing the execution time, we have
the anonymous class in PHP 7. It is not available in PHP 5.
• Group Use Declaration – PHP 7 allows all the classes, constants, and functions to be imported
from the same namespace to be grouped in a single-use statement. This is known as group use
declaration. The feature is not available in PHP 5.
• New Operators – Several new operators are introduced to PHP 7, including ‘<=>’ and ‘??’ The
former is known as the three-way comparison operator, and the latter is called the null
coalescing operator.
Question: What are the various ways of handling the result set of Mysql in PHP?
Answer: There are four ways of handling the result set of Mysql in PHP:
• mysqli_fetch_array
• mysqli_fetch_assoc
• mysqli_fetch_object
• mysqli_fetch_row
Question: What is a session in PHP? Write a code example to demonstrate the removal of session
data.
Answer: The simplest way to store data for individual users against a unique session ID is by using a
PHP session. It is used for maintaining states on the server as well as sharing data across several pages.
This needs to be done because HTTP is a stateless protocol.
Typically, session IDs are sent to the browser using session cookies. The ID is used for retrieving
existing session data. If the session ID is not available on the server, then PHP creates a new session
and then generates a new session ID.
Here is the program for demonstrating how session data is removed:
<?php
session_start();
$_SESSION['user_info'] = ['user_id' =>1,
'first_name' =>
'Hacker', 'last_name' =>
'.io', 'status' =>
'active'];
if (isset($_SESSION['user_info']))
{
echo "logged In";
}
unset($_SESSION['user_info']['first_name']);
session_destroy();
?>
Question: What would you say is the best hashing method for passwords?
Answer: Rather than using the typical hashing algorithms, including md5, sha1, and sha256, it is
preferable to use either crypt() or hash(). While crypt() provides native support for several hashing
algorithms, hash(,) provides support for even more of them.
Question: Why is it not possible for JavaScript and PHP to interact directly? Do you know any
workarounds?
Answer: No direct interaction is possible between JS and PHP because while the former is a client-side
language, the latter is a server-side language. An indirect interaction between the two leading
programming languages can happen using exchanging variables.
This exchange of variable is possible due to two reasons:
1. PHP can generate JavaScript code meant to be executed by the browser
2. It is achievable to pass a specific variable back to PHP via the URL. Because PHP always gets
to be executed before JavaScript, the JS variables must be passed via a form or the URL. To
pass the variables, GET and POST are used. Similarly, to retrieve the passed variable, $_GET
and $_POST are used.
Question: Write code in PHP to calculate the total number of days between two dates?
Answer:
<?Php
$date1 = ‘2019-01-11’;
$date2 = ‘2019-01-09’;
$days = (strtotime($date1)-strtotime($date2))/(60*60*24);
echo $days;
?>
Output:
1
Question: Briefly explain PHP & some of the popular PHP frameworks.
Answer: PHP is a popular server-side scripting language used by developers to dynamically create
webpages. Originally, PHP meant Personal Home Page. However, today it stands for the recursive
acronym PHP: Hypertext Preprocessor.
As of now, there is a wide range of PHP frameworks available. Three of the most popular PHP
frameworks are briefly explained as follows:
• CodeIgniter – Simplistic and powerful, CodeIgniter is an incredibly lightweight PHP framework
with a hassle-free installation process and minimalistic configuration requirements. The
complete framework is a mere 2 MB and that too, including the documentation. As it comes
with many prebuilt modules that help in developing strong, reusable components, CodeIgniter is
ideal for developing dynamic websites. The popular PHP framework also offers a smooth
working experience on both dedicated as well as shared hosting platforms.
• Laravel – Although not as old as some of the other popular PHP frameworks, Laravel is perhaps
the most popular PHP framework. Launched in 2011, the immense popularity enjoyed by the
PHP framework can be credited to its ability to offer additional speed and security for handling
complex web applications. Laravel also eases the development process by reducing the
complexity of repetitive tasks, including authentication, routing, sessions, and queuing.
• Symfony – Used by PHP developers ever since its release back in 2005, Symfony is a popular
PHP framework that has stood the test of time. It has matured over its run of almost one-and-a-
half decade. An extensive PHP framework, Symfony, is the sole PHP framework that follows
the standard of PHP and web completely. Popular CMSs like Drupal, OroCRM, and PHPBB
make use of various Symfony components.
If you are interested in learning Codeigniter, Laravel or Symfony, then Hackr has programming
community-recommended best tutorials and courses:
• Codeigniter tutorials and courses
• Laravel tutorials and courses
• Symfony tutorials and courses
Question: Will you draw a comparison between server-side and client-side programming
languages?
Answer: Server-side programming languages are used for building programs that run on a server and
generate the contents of a webpage. Examples of server-side programming languages include C++,
Java, PHP, Python, and Ruby. A server-side programming language helps in:
• Accessing and/or writing a file present on the server
• Interacting with other servers
• Processing user input
• Querying and processing the database(s)
• Structuring web applications
Contrary to the server-side programming languages, client-side programming languages help in
developing programs that run on the client machine, typically browser, and involves displaying output
and/or additional processing, such as reading and writing cookies.
CSS, HTML, JavaScript, and VBScript are popular client-side programming languages. A client-side
programming language allows:
• Developing interactive webpages
• Interacting with temporary storage and/or local storage
• Making data and/or other requests to the server
• Offering an interface between the server and the end-user
Question: Please explain the differences between the echo and print statements in PHP?
Answer: There are two statements for getting output in PHP - echo and print. Following are the
distinctions between the two:
• Although used rarely, echo has the ability to take multiple parameters. The print statement, on
the contrary, can accept only a single argument
• Echo has no return value whereas, print has a return value of 1. Hence, the latter is the go-to
option for using in expressions
• Generally, the echo statement is preferred over the print statement as it is slightly faster
Question: Can you explain the difference between ‘passing the variable by value’ and ‘passing
the variable by reference’ in PHP?
Answer: Passing the variable by value means that the value of the variable is directly passed to the
called function. It then uses the value stored in the variable. Any changes made to the function doesn’t
affect the source variable.
Passing the variable by reference means that the address of the variable where the value is stored is
passed to the called function. It uses the value stored in the passed address. Any changes made to the
function does affect the source variable.
Question: Could you explain how to fetch data from a MySQL database using PHP?
Answer: To begin with, you need to first establish a connection with the MySQL database that you
wish to use. For that, you can use the mysqli_connect() function.
Suppose that the database that you need to access is stored on a server named localhost and has the
name instanceDB. Also, it has user_name as the username and pass_word as the password.
For establishing a connection to the instanceDB, you need to use the following PHP code:
<?php
$servername = “localhost”;
$username = “user_name”;
$password = “pass_word”;
$dbname = “instanceDB”;
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn) {
Next, you need to use the SELECT statement to fetch data from one or more tables. The general syntax
is:
SELECT column_name from table_name
Suppose, we have a single table called instancetable with column_1, column_2, and column_3 in the
instanceDB, then to fetch data; we need to add the following PHP code:
$sql = “SELECT column_1, column_2, column_3 from instancetable”;
$result = $conn->query($sql);
Question: What are some of the most popular PHP-based Content Management Systems (CMS)?
Answer: There are a plethora of PHP-based Content Management Systems in use today. Drupal,
Joomla, and WordPress are the most popular among the bunch.
The strstr() function is used for searching a string within another string in PHP. Unlike the substr()
function, strstr() is a case-sensitive function.
General syntax:
strstr(string, search, before_string);
Question: Please enumerate the major differences between for and foreach loop in PHP?
Answer: Following are the notable differences between for and for each loop:
• The for-each loop is typically used for dynamic array
• The for loop has a counter and hence requires extra memory. The for-each loop has no counter,
and hence there is no requirement for additional memory
• You need to determine the number of times the loop is to be executed when using the for a loop.
However, you need not do so while using the for each loop
Question: Please explain whether it is possible to extend a final defined class or not?
Answer: No, it isn’t possible to extend a final defined class. The final keyword prevents the class from
extending. When used with a method, the final keyword prevents it from overriding.
Question: Will it be possible to extend the execution time of a PHP script? How?
Answer: Yes, it is possible to extend the execution time of a PHP script. We have the set_time_limit(int
seconds) function for that. You need to specify the duration, in seconds, for which you wish to extend
the execution time of a PHP script. The default time is 30 seconds.
Summary
That’s all for now! Here are some important PHP tutorials to go for, just in case. Keep your calm, and
stay confident during the big day.
Though having a good understanding of the technical concepts is important, your presentation is also
one that’s being reviewed.
We would recommend you a great course that will help you enhance your interview skills with the
maximum questions set: PHP Interview Questions with Solutions part 1.
We also recommend a great book to prepare for the PHP Interview, which is, Modern PHP: Modern
PHP: New Features and Good Practices 1st Edition.
So, all the very best for your PHP interview!
People are also reading:
• Best PHP Certifications
• Best PHP Books
• Difference between Python vs PHP
• Best PHP Frameworks
• Download PHP Cheat Sheet
• Best PHP Projects
• Top PHP Alternatives
• PHP vs Javascript
• PHP vs Node.Js
• HTML vs HTML5: Head to Head Comparison
onlineinterviewquestions.com
• 1) What is PHP ?
• 2) Where sessions stored in PHP ?
• 3) What are constructor and destructor in PHP ?
• 4) List data types in PHP ?
• 5) How to register a variable in PHP session ?
• 6) What is purpose of @ in Php ?
• 7) Is multiple inheritance supported in PHP ?
• 8) What is default session time and path in PHP. How to change it ?
• 9) What is namespaces in PHP?
• 10) What are PHP Magic Methods/Functions. List them.
• 11) How to add 301 redirects in PHP?
• 12) What is difference between include,require,include_once and require_once() ?
• 13) What is a composer in PHP?
• 14) What is cURL in PHP ?
• 15) What is T_PAAMAYIM_NEKUDOTAYIM in PHP?
• 16) What is the difference between == and === operator in PHP ?
• 17) Explain Type hinting in PHP ?
• 18) What is session in PHP. How to remove data from a session?
• 19) How to increase the execution time of a PHP script ?
• 20) What are different types of errors available in Php ?
• 21) What is difference between strstr() and stristr() ?
• 22) Code to upload a file in PHP ?
• 23) How to get length of an array in PHP ?
• 24) Code to open file download dialog in PHP ?
• 25) How to Pass JSON Data in a URL using CURL in PHP ?
Last Updated: May 13, 2020,
PHP: Hypertext Preprocessor is open source server-side scripting language that is widely used for
creation of dynamic web applications.It was developed by Rasmus Lerdorf also know as Father of PHP
in 1994.
PHP is a loosely typed language , we didn’t have to tell PHP which kind of Datatype a Variable is. PHP
automatically converts the variable to the correct datatype , depending on its value.
PHP sessions are stored on the server generally in text files in a temp directory of the server.
That file is not accessible from the outside world. When we create a session PHP create a unique
session id that is shared by the client by creating a cookie on the client's browser. That session id is sent
by the client browser to the server each time when a request is made and the session is identified.
The default session name is "PHPSESSID".
PHP constructor and destructor are special type functions that are automatically called when a PHP
class object is created and destroyed.
Generally, Constructor is used to initializing the private variables for class and Destructors to free the
resources created /used by the class.
Here is a sample class with a constructor and destructor in PHP.
<?php
class Foo {
private $name;
private $link;
In PHP 5.3 or below we can register a variable session_register() function.It is deprecated now and we
can set directly a value in $_SESSION Global.
Example usage:
<?php
// Starting session
session_start();
// Use of session_register() is deprecated
$username = "PhpScots";
session_register("username");
// Use of $_SESSION is preferred
$_SESSION["username"] = "PhpScots";
?>
In PHP @ is used to suppress error messages.When we add @ before any statement in php then if any
runtime error will occur on that line, then the error handled by PHP
The default session time in PHP is 1440 seconds (24 minutes) and the Default session storage path is
temporary folder/tmp on the server.
You can change default session time by using below code
<?php
// server should keep session data
for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);
PHP Namespaces provide a way of grouping related classes, interfaces, functions and constants.
# define namespace and class in namespace
namespace Modules\Admin\;
class CityController {
}
In PHP all functions starting with __ names are magical functions/methods. Magical methods always
lives in a PHP class.The definition of magical function are defined by programmer itself.
Here are list of magic functions available in PHP
__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(),
__wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo() .
You can add 301 redirect in PHP by adding below code snippet in your file.
header("HTTP/1.1 301 Moved Permanently");
header("Location: /option-a");
exit();
Include :-Include is used to include files more than once in single PHP script.You can include a file as
many times you want.
Syntax:- include(“file_name.php”);
Include Once:-Include once include a file only one time in php script.Second attempt to include is
ignored.
Syntax:- include_once(“file_name.php”);
Require:-Require is also used to include files more than once in single PHP script.Require generates a
Fatal error and halts the script execution,if file is not found on specified location or path.You can
require a file as many time you want in a single script.
Syntax:- require(“file_name.php”);
Require Once :-Require once include a file only one time in php script.Second attempt to include is
ignored. Require Once also generates a Fatal error and halts the script execution ,if file is not found on
specified location or path.
Syntax:- require_once(“file_name.php”);
It is an application-level package manager for PHP. It allows you to declare the libraries your project
depends on and it will manage (install/update) them for you.
cURL is a library in PHP that allows you to make HTTP requests from the server.
$Cache::getConfig($key);
In PHP == is an equal operator and returns TRUE if $a is equal to $b after type juggling and === is
Identical operator and return TRUE if $a is equal to $b, and they are of the same data type.
Example Usages:
<?php
$a=true ;
$b=1;
// Below condition returns true and prints
a and b are equal
if($a==$b){
echo "a and b are equal";
}else{
echo "a and b are not equal";
}
//Below condition returns false
and prints a and b are not equal because $a and $b are of different data
types.
if($a===$b){
echo "a and b are equal";
}else{
echo "a and b are not equal";
}
?>
In PHP Type hinting is used to specify the excepted data type of functions argument.
Type hinting is introduced in PHP 5.
Example usage:-
//send Email function argument $email Type hinted of Email Class. It means to call this function you
must have to pass an email object otherwise an error is generated.
<?php
function sendEmail (Email $email)
{
$email->send();
}
?>
As HTTP is a stateless protocol. To maintain states on the server and share data across multiple pages
PHP session are used. PHP sessions are the simple way to store data for individual users/client against a
unique session ID. Session IDs are normally sent to the browser via session cookies and the ID is used
to retrieve existing session data, if session id is not present on server PHP creates a new session, and
generate a new session ID.
Example Usage:-
<?php
// starting a session
session_start();
// Creating a session
// checking session
if (isset($_SESSION['user_info']))
{
echo "logged In";
}
unset($_SESSION['user_info']['first_name']);
session_destroy();
?>
The default max execution time for PHP scripts is set to 30 seconds. If a php script runs longer than 30
seconds then PHP stops the script and reports an error.
You can increase the execution time by changing max_execution_time directive in your php.ini file or
calling ini_set(‘max_execution_time’, 300); //300 seconds = 5 minutes function at the top of your php
script.
In PHP both functions are used to find the first occurrence of a substring in a string except
stristr() is case-insensitive and strstr is case-sensitive, if no match is found then FALSE will be
returned.
Sample Usage:
<?php
$email = ‘abc@xyz.com’;
$hostname = strstr($email, ‘@’);
echo $hostname;
output: @xyz.com
?>
PHP count function is used to get the length or numbers of elements in an array
<?php
// initializing an array in PHP
$array=['a','b','c'];
// Outputs 3
echo count($array);
?>
You can open a file download dialog in PHP by setting Content-Disposition in the header.
Here is a usage sample:-
// outputting a PDF file
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
Mbstring
Mbstring is an extension used in PHP to handle non-ASCII strings. Mbstring provides multibyte
specific string functions that help us to deal with multibyte encodings in PHP. Multibyte character
encoding schemes are used to express more than 256 characters in the regular byte-wise coding system.
Mbstring is designed to handle Unicode-based encodings such as UTF-8 and UCS-2 and many single-
byte encodings for convenience PHP Character Encoding Requirements.
You may also Like Codeigniter interview questions
Below are some features of mbstring
1. It handles the character encoding conversion between the possible encoding pairs.
2. Offers automatic encoding conversion between the possible encoding pairs.
3. Supports function overloading feature which enables to add multibyte awareness to regular
string functions.
4. Provides multibyte specific string functions that properly detect the beginning or ending of a
multibyte character. For example, mb_strlen() and mb_split()
<?php
$tomorrow = mktime(0, 0, 0, date(“m”) , date(“d”)+1, date(“Y”));
$lastmonth = mktime(0, 0, 0, date(“m”)-1, date(“d”), date(“Y”));
echo ($tomorrow-$lastmonth)/86400;
?>
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web
applications. XSS enables attackers to inject client-side script into web pages viewed by other users. A
cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same-
origin policy.
echo in PHP
• echo is language constructs that display strings.
• echo has a void return type.
• echo can take multiple parameters separated by comma.
• echo is slightly faster than print.
Print in PHP
• print is language constructs that display strings.
• print has a return value of 1 so it can be used in expressions.
• print cannot take multiple parameters.
• print is slower than echo.
PHP is a server side scripting language for creating dynamic web pages. There are so many functions
available for displaying output in PHP. Here, I will explain some basic functions for displaying output
in PHP. The basic functions for displaying output in PHP are as follows:
• print() Function
• echo() Function
• printf() Function
• sprintf() Function
• Var_dump() Function
• print_r() Function
In PHP, one can specify two different submission methods for a form. The method is specified inside a
FORM element, using the METHOD attribute. The difference between METHOD=”GET” (the default)
and METHOD=”POST” is primarily defined in terms of form data encoding. According to the
technical HTML specifications, GET means that form data is to be encoded (by a browser) into a URL
while POST means that the form data is to appear within the message body of the HTTP request.
Get Post
Parameters remain in browser history because Parameters are not saved in browser
History:
they are part of the URL history.
Bookmarked: Can be bookmarked. Can not be bookmarked.
BACK GET requests are re-executed but may not be
The browser usually alerts the user
button/re-submit re-submitted to the server if the HTML is
that data will need to be re-submitted.
behavior: stored in the browser cache.
Encoding type multipart/form-data or application/x-
(enctype application/x-www-form-urlencoded www-form-urlencoded Use multipart
attribute): encoding for binary data.
can send but the parameter data is limited to
what we can stuff into the request line (URL). Can send parameters, including
Parameters:
Safest to use less than 2K of parameters, uploading files, to the server.
some servers handle up to 64K
Hacked: Easier to hack for script kiddies More difficult to hack
Restrictions on No restrictions. Binary data is also
Yes, only ASCII characters allowed.
form data type: allowed.
GET is less secure compared to POST POST is a little safer than GET
because data sent is part of the URL. So it’s because the parameters are not stored
Security:
saved in browser history and server logs in in browser history or in web server
plaintext. logs.
Yes, since form data is in the URL and URL
Restrictions on
length is restricted. A safe URL length limit is
form data No restrictions
often 2048 characters but varies by browser
length:
and web server.
Get Post
GET method should not be used when POST method used when sending
Usability: sending passwords or other sensitive passwords or other sensitive
information. information.
GET method is visible to everyone (it will be
displayed in the browsers address bar) and POST method variables are not
Visibility:
has limits on the amount of information to displayed in the URL.
send.
Cached: Can be cached Not Cached
Large variable
7607 characters maximum size. 8 Mb max size for the POST method.
values:
A database provides more flexibility and reliability than does logging to a file. It is easy to run queries
on databases and generate statistics than it is for flat files. Writing to a file has more overhead and will
cause your code to block or fail in the event that a file is unavailable. Inconsistencies caused by slow
replication in AFS may also pose a problem to errors logged to files. If you have access to MySQL, use
a database for logs, and when the database is unreachable, have your script automatically send an e-
mail to the site administrator.
get_browser() function is used to retrieve the client browser details in PHP. This is a library function is
PHP which looks up the browscap.ini file of the user and returns the capabilities of its browser.
Syntax:
get_browser(user_agent,return_array)
Example Usage:
$browserInfo = get_browser(null, true);
print_r($browserInfo);
You can access standard error stream in PHP by using following code snippet:
$stderr = fwrite("php://stderr");
$stderr = STDERR;
PHP (Hypertext Preprocessor) is an open source, a server-side scripting language that is used for the
web applications development.
The web pages can be designed using HTML and the execution of the code is done on the user’s
browser.
And, with PHP server-side scripting language, the code is executed on the server before being executed
on the web browser of the user.
PHP programming language is considered as a friendly language with abilities to easily connect with
Oracle, MySQL, and many other databases.
Advantages of PHP
Now, let's have a quick look at why PHP is used; that is the advantages of PHP.
• Open Source
PHP is an open source software, which means that it is freely available for modifications and
redistribution, unlike any other programming language. There is also an active team of PHP
developers who are ready to provide any kind of technical support when needed.
• Cross Platform
The PHP programming language is easy to use and modify and is also highly compatible with
the leading operating systems as well as the web browsers. And, that made the deployment of
the applications across a wide range of operating systems and browsers much easier than before.
PHP not only supports the platforms like Linux, Windows, Mac OS, Solaris but is also applied
to web servers like Apache, IIS and many others.
• Suits Web Development
PHP programming language perfectly suits the web development and can be directly embedded
into the HTML code.
Also Read: PHP Interview Questions
MCrypt is a file encryption function and that is delivered as Perl extension. It is the replacement of the
old crypt() package and crypt(1) command of Unix. It allows developers to encrypt files or data
streams without making severe changes to their code.
MCrypt is was deprecated in PHP 7.1 and completely removed in PHP 7.2.
PECL is an online directory or repository for all known PHP extensions. It also provides hosting
facilities for downloading and development of PHP extensions.
You can read More about PECL from https://pecl.php.net/
$string = $_GET['text'];
$im = imagecreatefrompng("images/button1.png");
$mongo = imagecolorallocate($im, 220, 210, 60);
$px = (imagesx($im) - 7.5 * strlen($string)) / 2;
imagestring($im, 3, $px, 9, $string, $mongo);
imagepng($im);
imagedestroy($im);
?>
use function_exists('curl_version') function to check curl is enabled or not. This function returns true
if curl is enabled other false
Example :
if(function_exists('curl_version') ){
echo "Curl is enabled";
}else{
echo "Curl is not enabled";
You can use $_SERVER['REMOTE_ADDR'] to get IP address of user/client in PHP, But sometime it
may not return the true IP address of the client at all time. Use Below code to get true IP address of
user.
function getTrueIpAddr(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from
proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
Traits in PHP are similar to Abstract classes that are not be instantiated on its own. Traits allow us to
declare methods that are used by multiple classes in PHP. trait keyword is used to create Traits in PHP
and can have concrete and abstract methods.
Syntax
<?php
trait TraitName {
// some code...
}
?>
An exception that occurs at compile time is called a checked exception. This exception cannot be
ignored and must be handled carefully. For example, in Java if you use FileReader class to read data
from the file and the file specified in class constructor does not exist, then a FileNotFoundException
occurs and you will have to manage that exception. For the purpose, you will have to write the code in
a try-catch block and handle the exception. On the other hand, an exception that occurs at runtime is
called unchecked-exception Note: Checked exception is not handled so it becomes an unchecked
exception. This exception occurs at the time of execution.
Zend Engine is used by PHP. The current stable version of Zend Engine is 3.0. It is developed by Andi
Gutmans and Zeev Suraski at Technion – Israel Institute of Technology.
These are the commonly used regular expressions in PHP. These are an inbuilt function that is used to
work with other regular functions.
preg-Match: This is the function used to match a pattern in a defined string. If the patterns match with
string, it returns true otherwise it returns false.
Preg_replace: This function is used to perform a replace operation. In this, it first matches the pattern in
the string and if pattern matched, ten replace that match with the specified pattern.
Both are used to make the changes to your PHP setting. These are explained below:
php.ini: It is a special file in PHP where you make changes to your PHP settings. It works when you
run PHP as CGI. It depends on you whether you want to use the default settings or changes the setting
by editing a php.ini file or, making a new text file and save it as php.ini.
.htaccess: It is a special file that you can use to manage/change the behavior of your site. It works
when PHP is installed as an Apache module. These changes include such as redirecting your domain’s
page to https or www, directing all users to one page, etc.
You can use a .htaccess file to block the direct access of directory in PHP. It would be best if you add
all the files in one directory, to which you want to deny access.
For Apache, you can use this code:
<< Order deny, allow Deny from all</<
But first, you have to create a .htaccess file, if it is not present. Create the .htaccess file in the root of
your server and then apply the above rule.
• ksort() function is used to sort an array according to its key values whereas asort() function is
used to sort an array according to its values.
• They both used to sort an associative array in PHP.
Example of asort():
<?php
$age = array("Peter"=>"37", "Ben"=>"27", "Joe"=>"43");
asort($age);
?>
It is easy and simple to execute PHP scripts from the windows command prompt. You just follow the
below steps:
1. Open the command prompt. Click on Start button->Command Prompt.
2. In the Command Prompt, write the full path to the PHP executable(php.exe) which is followed by
the full path of a script that you want to execute. You must add space in between each component. It
means to navigate the command to your script location.
For example,
let you have placed PHP in C:\PHP, and your script is in C:\PHP\sample-php-
script.php,
Floyd’s triangle is the right-angled triangle which starts with 1 and filled its rows with a consecutive
number. The count of elements in next row will increment by one and the first row contains only one
element.
Example of Floyd's triangle having 4 rows
The logic to print Floyd's triangle
<?php
echo "print Floyd's triangle";
echo "<pre>
$key = 1;
for ($i = 1; $i <= 4; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo $key;
$key++;
if ($j == $i) {
echo "<br/>";
}
}
}
echo "";
?>
Output:
1
23
456
7 8 9 10
There are many differences between PHP 5 and 7. Some of the main points are:
• Performance: it is obvious that later versions are always better than the previous versions if
they are stable. So, if you execute code in both versions, you will find the performance of PHP 7
is better than PHP5. This is because PHP 5 use Zend II and PHP & uses the latest model PHP-
NG or Next Generation.
• Return Type: In PHP 5, the programmer is not allowed to define the type of return value of a
function which is the major drawback. But in PHP 7, this limitation is overcome and a
programmer is allowed to define the return type of any function.
• Error handling: In PHP 5, there is high difficulty to manage fatal errors but in PHP 7, some
major errors are replaced by exceptions which can be managed effortlessly. In PHP 7, the new
engine Exception Objects has been introduced.
• 64-bit support: PHP 5 doesn’t support 64-bit integer while PHP 7 supports native 64-bit
integers as well as large files.
• Anonymous Class: Anonymous class is not present n PHP 5 but present in PHP 7. It is
basically used when you need to execute the class only once to increase the execution time.
• New Operators: Some new operators have added in PHP 7 such as <=> which is called a three-
way comparison operator. Another operator has added is a null coalescing operator which
symbol as?? and use to find whether something exists or not.
• Group Use declaration: PHP 7 includes this feature whereas PHP 5 doesn’t have this feature.
Static Members of a Class can be accessed directly using a class name with a scope resolution
operator. To access Static members we don't need to create an object of Class.
Example
class Hello {
public static $greeting = 'Greeting from Hello Class';
}
The explode() and split() functions are used in PHP to split the strings. Both are defined here:
Split() is used to split a string into an array using a regular expression whereas explode() is used to
split the string by string using the delimiter.
Example of split():
split(":", "this:is:a:split"); //returns an array that contains this, is, a, split.
Output: Array ([0] => this,[1] => is,[2] => a,[3] => split)
Example of explode():
explode ("take", "take a explode example "); //returns an array which have value "a explode example"
Output: array([0] => "a explode example")
The list is similar to an array but it is not a function, instead, it is a language construct. This is used for
the assignment of a list of variables in one operation. If you are using PHP 5 version, then the list
values start from a rightmost parameter, and if you are using PHP 7 version, then your list starts with a
left-most parameter. Code is like:
<?php
$info = array('red', 'sign', 'danger');
// Listing all the variables
list($color, $symbol, $fear) = $info;
echo "$color is $symbol of $fear”
?>
An access specifier is a code element that is used to determine which part of the program is allowed to
access a particular variable or other information. Different programming languages have different
syntax to declare access specifiers. There are three types of access specifiers in PHP which are:
• Private: Members of a class are declared as private and they can be accessed only from that
class.
• Protected: The class members declared as protected can be accessed from that class or from the
inherited class.
• Public: The class members declared as public can be accessed from everywhere.
array_combine is used to combine two or more arrays while array_merge is used to append one array
at the end of another array.
array_combine is used to create a new array having keys of one array and values of another array that
are combined with each other whereas array_merge is used to create a new array in such a way that
values of the second array append at the end of the first array.
array_combine doesn't override the values of the first array but in array_merge values of the first array
overrides with the values of the second one.
Example of array_combine
<?php
$arr1 = array("sub1","sub2","sub3");
$arr2 = array(("php","html","css");
$new_arr = array_combine($arr1, $arr2);
print_r($new_arr);
?>
OUTPUT:
Array([sub1] => php [sub2] => html [sub3 =>css)
Example of array_merge
<?php
$arr1 = array("sub1" => "node", "sub2" => "sql");
$arr2 = array("s1"=>"jQuery", "s3"=>"xml", "sub4"=>"Css");
$result = array_merge($arr1, $arr2);
print_r($result);
?>
OUTPUT:
Array ([s1] => jquery [sub2] => sql [s3] => xml [sub4] =>Css )
MIME stands for Multipurpose Internet Mail Extensions is an extension of the email protocol. It
supports exchanging of various data files such as audio, video, application programs, and many others
on the internet. It can also handle ASCII texts and Simple Mail Transport Protocol on the internet.
getimagesize() function is used to get the size of an image in PHP. This function takes the path of file
with name as an argument and returns the dimensions of an image with the file type and height/width.
Syntax:
array getimagesize( $filename, $image_info )
Path Traversal also is known as Directory Traversal is referring to an attack which is attacked by an
attacker to read into the files of the web application. Also, he/she can reveal the content of the file
outside the root directory of a web server or any application. Path traversal operates the web
application file with the use of dot-dot-slash (../) sequences, as ../ is a cross-platform symbol to go up in
the directory.
Path traversal basically implements by an attacker when he/she wants to gain secret passwords, access
token or other information stored in the files. Path traversal attack allows the attacker to exploit
vulnerabilities present in web file.
Heredoc and nowdoc are the methods to define the string in PHP in different ways.
• Heredoc process the $variable and special character while nowdoc doesn't do the same.
• Heredoc string uses double quotes "" while nowdoc string uses single quote ''
• Parsing is done in heredoc but not in nowdoc.
The mail function is used in PHP to send emails directly from script or website. It takes five parameters
as an argument.
Syntax of mail (): mail (to, subject, message, headers, parameters);
• to refers to the receiver of the email
• Subject refers to the subject of an email
• the message defines the content to be sent where each line separated with /n and also one line
can't exceed 70 characters.
• Headers refer to additional information like from, Cc, Bcc. These are optional.
• Parameters refer to an additional parameter to the send mail program. It is also optional
Both MD5 and SHA256 are used as hashing algorithms. They take an input file and generate an output
which can be of 256/128-bit size. This output represents a checksum or hash value. As, collisions are
very rare between hash values, so no encryption takes place.
• The difference between MD5 and SHA256 is that the former takes less time to calculate than
later one.
• SHA256 is difficult to handle than MD5 because of its size.
• SHA256 is less secure than MD5
• MD5 result in an output of 128 bits whereas SHA256 result output of 256 bits.
Concluding all points, it will be better to use MDA5 if you want to secure your files otherwise you can
use SHA256.
To terminate the script in PHP, exit() function is used. It is an inbuilt function which outputs a message
and then terminates the current script. The message which is you want to display is passed as a
parameter to the exit () function and this function terminates the script after displaying the message. It
is an alias function of die () function. It doesn’t return any value.
Syntax: exit(message)
Where massage is a parameter to be passed as an argument. It defines message or status.
Exceptions of exit():
• If no status is passed to exit(), then it can be called without parenthesis.
• If a passed status is an integer then the value will not be printed but used as the exit status.
• The range of exit status is from 0 to 254 where 255 is reserved in PHP.
Errors And Exceptions
• exit() can be called without parentheses if no status is passed to it. Exit() function is also known
by the term language construct.
• If the status passed to an exit() is an integer as a parameter, that value will be used as the exit
status and not be displayed.
• The range of exit status should be in between 0 to 25. the exit status 255 should not be used
because it is reserved by PHP.
It is clear from the name SHA256 that the length is of 256 bits long. If you are using hexadecimal
representation, then you require 64 digits to replace 256 bits, as one digit represents four bits. Or if you
are using a binary representation which means one byte equals to eight bits, then you need 32 digits.
Static method is a member of class that is called directly by class name without creating an instance.In
PHP uou can create a static method by using static keyword.
Example:
class A {
public static function sayHello() {
echo 'hello Static';
}
}
A::sayHello();
class A {
function showName() {
return "Ajay";
}
}
class B extends A {
function showName() {
return "Anil";
}
}
$foo = new A;
$bar = new B;
echo($foo->myFoo()); //"Ajay"
echo($bar->myFoo()); //"Anil"
?>
In Overloading, there are multiple methods with the same name with different signatures or parameters.
Overloading is done within the same class. Overloading is also called early binding or compile time
polymorphism or static binding.
An example of Overloading in PHP
<?php
class A{
function sum($a,$b){
return $a+$b;
function sum($a,$b,$c){
return $a+$b+$c;
}
$obj= new A;
$obj->sum(1,3); // 4
$obj->sum(1,3,5); // 9
?>
You can use library function array_unique() for removing duplicated values for an array. Here is
syntax to use it.
<?php
$a=array("a"=>"home","b"=>"town","c"=>"town","php");
print_r(array_unique($a));
?>
Both strstr() as well as stristr() in PHP are used for the purpose of finding the first occurrence of the
string. The only difference between the two is while strstr() is case sensitive but on the other hand,
stristr() is case insensitive.
In PHP5 or above, type hinting is a process used to specify the data type of a given argument. This is
mainly used in a function declaration. Whenever the function is called, PHP checks if the arguments are
of the type preferred by the user or not. If the argument is not of the specified type, the run time will
display an error and the program will not execute.
intellipaat.com
Or
$var = null;
19. What is the use of the final class and the final method in PHP?
The ‘final’ keyword, if present in a declaration, denotes that the current method does not support
overriding by other classes. This is used when there is a requirement to create an immutable class.
Note: Properties cannot be declared as final. It is only methods and classes that get to be final.
?>
31. What is the most used method for hashing passwords in PHP?
The crypt() function is widely used for this functionality as it provides a large amount of hashing
algorithms that can be used. These algorithms include md5, sha1 or sha256.
36. Can a form be submitted in PHP without making use of a submit button?
Yes, a form can be submitted without the explicit use of a button. This is done by making use of the
JavaScript submit() function easily.
function add(...$num) {
$sum = 0;
$sum += $n;
}
return $sum;
?>
Output: 26
The session_destroy() function is mostly used to destroy all of the session variables as shown below:
<?php
session_start();
session_destroy();
?>
This is used further to store data into a variable, and then you can use it when required without the
requirement of defining it again.
45. Differentiate between compile-time exception and runtime exception in PHP.
As the name suggests, if there is an occurrence of any sort of exception while the script is being
compiled, it is called a compile-time exception. The FileNotFoundException is a good example of a
compile-time exception.
An exception that interrupts the script while running is called a runtime exception. The
ArrayIndexOutOfBoundException is an example of a runtime exception.
48. What are the steps to create a new database using MySQL and PHP?
There are four basic steps that are used to create a new MySQL database in PHP. They are as follows:
• First, a connection is established to the MySQL server using the PHP script.
• Second, the connection is validated. If the connection is successful, then you can write a sample
query to verify.
• Queries that create the database are input and later stored into a string variable.
• Then, the created queries are executed one after the other.
50. Do you have any certification to boost your candidature for this PHP Developer
role?
With this question, the interviewer is trying to assess if you have any exposure to real-time projects and
hands-on experience. This is usually provided by a good certification program, and this gives an
impression to the interviewer that you are serious about the career path you are aspiring for. If you do
have any relevant experience, make sure to explain about what you learned and implemented during the
certification course.
where input_string consists of the string that has to be encrypted and salt is an optional parameter.
PHP uses DES for encryption. The format is as follows:
• Using header(“location:page.php”);
The metaphone() function calculates the metaphone key of a string. A metaphone key represents how a
string sounds if it is pronounced by an English (native) person. This function can also be used for
spelling applications.
<?php
echo metaphone(“world”);
?>
Answer.
<unlink()> function is useful for file system handling. We use this function when we want to delete the
files (physically).
Sample code:
<?php
$xx = fopen('sample.html', 'a');
fwrite($xx, '<h1>Hello !!</h1>');
fclose($xx);
unlink('sample.html');
?>
unset() function performs variable management. It makes a variable undefined. Or we can say that
unset() changes the value of a given variable to null. Thus, in PHP if a user wants to destroy a variable,
it uses unset(). It can remove a single variable, multiple variables, or an element from an array.
Sample code:
<?php
$val = 200;
echo $val; //Out put will be 200
$val1 = unset($val);
echo $val1; //Output will be null
?>
<?php
unset($val); // remove a single variable
unset($sample_array['element']); //remove a single element in an array
unset($val1, $val2, $val3); // remove multiple variables
?>
Answer.
It is a mechanism that allows us to do code reusability in single inheritance language, such as PHP. Its
structure is almost the same as that of a PHP class, just that it is a group of reusable functions. Despite
having the same name and definition, they appear in several classes, each one having a separate
declaration leading to code duplicity. We can group these functions and create PHP Traits. The class
can use this Trait to include the functionality of the functions defined in it.
Let’s take an example, where we create a Message class.
class Message
{
}
We cannot include the functionality of the Goodmorning class in Message class, as PHP does not
support Multiple Inheritance. Here, PHP Traits comes into the picture. Let’s see how Traits resolve the
issue of Multiple Inheritance for Message class.
Example.
trait Goodmorning
{
public function goodmorning()
{
echo "Good Morning","\n";
}
}
trait Welcome
{
public function welcome()
{
echo "Welcome","\n";
}
}
class Message
{
use Welcome, Goodmorning;
public function sendMessage()
{
echo 'I said Welcome',"\n";
echo $this->welcome(),"\n";
echo 'and you said Good Morning',"\n";
echo $this->goodmorning();
}
}
$o = new Message;
$o->sendMessage();
Q-3. How can we display the correct URL of the current webpage?
Answer.
<?php
echo $_SERVER['PHP_SELF'];
?>
Answer.
The extract() function imports variables into the local symbol table from an array. It uses variable
names as array keys and variable values as array values. For each element of an array, it creates a
variable in the current symbol table.
Following is the syntax.
extract(array,extract_rules,prefix)
Answer.
The default session timeout happens in 24 minutes (1440 seconds). However, we can change this value
by setting the variable <session.gc_maxlifetime()> in [php.ini] file.
Q-6. What is autoloading classes in PHP?
Answer.
With autoloaders, PHP allows the last chance to load the class or interface before it fails with an error.
The spl_autoload_register() function in PHP can register any number of autoloaders, enable classes
and interfaces to autoload even if they are undefined.
<?php
spl_autoload_register(function ($classname) {
include $classname . '.php';
});
$object = new Class1();
$object2 = new Class2();
?>
In the above example, we do not need to include Class1.php and Class2.php. The
spl_autoload_register() function will automatically load Class1.php and Class2.php.
Q-7. What are different ways to get the extension of a file in PHP?
Answer.
There are following two ways to retrieve the file extension.
1. $filename = $_FILES[‘image’][‘name’];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
2. $filename = $_FILES[‘image’][‘name’];
$array = explode(‘.’, $filename);
$ext = end($array);
Answer.
PDO stands for <PHP Data Object>.
• It is a set of PHP extensions that provide a core PDO class and database, specific drivers.
• It provides a vendor-neutral, lightweight, data-access abstraction layer. Thus, no matter what
database we use, the function to issue queries and fetch data will be the same.
• It focuses on data access abstraction rather than database abstraction.
• PDO requires the new object-oriented features in the core of PHP 5. Therefore, it will not run
with earlier versions of PHP.
PDO divides into two components.
• The core which provides the interface.
• Drivers to access a particular driver.
Q-9. What does the presence of the operator ‘::’ represent?
Answer.
It gets used to access the static methods that do not require initializing an object.
Q-10. How to get the information about the uploaded file in the receiving Script?
Answer.
Once the Web server receives the uploaded file, it calls the PHP script specified in the form action
attribute to process it.
This receiving PHP script can get the information of the uploaded file using the predefined array called
$_FILES. PHP arranges this information in $_FILES as a two-dimensional array. We can retrieve it as
follows.
• $_FILES[$fieldName][‘name’] – It represents the file name on the browser system.
• $_FILES[$fieldName][‘type’] – It indicates the file type determined by the browser.
• $_FILES[$fieldName][‘size’] – It represents the size of the file in bytes.
• $_FILES[$fieldName][‘tmp_name’] – It gives the temporary filename with which the
uploaded file got stored on the server.
• $_FILES[$fieldName][‘error’] – It returns the error code associated with this file upload.
The $fieldName is the name used in the <input type=”file” name=”<?php echo $fieldName; ?>”>.
Q-11. What is the difference between Split and Explode functions for String
manipulation in PHP?
Answer.
Both of them perform the task of splitting a String. However, the method they use is different.
The split() function splits the String into an array using a regular expression and returns an array.
For Example.
split(:May:June:July);
Answer.
PHP allows the user to modify some of its settings mentioned in <php.ini> using ini_set(). This
function requires two string arguments. First one is the name of the setting to be modified and the
second one is the new value to be assigned to it.
The given lines of code will enable the display_error setting for the script if it’s disabled.
ini_set('display_errors', '1');
We need to put the above statement, at the top of the script so that, the setting remains enabled till the
end. Also, the values set via ini_set() are applicable, only to the current script. Thereafter, PHP will
start using the original values from php.ini.
Before changing any settings via ini_set(), it’s necessary to determine that PHP allows modifying it or
not. We can only change the settings that get listed as ‘PHP_INI_USER’ or ‘PHP_INI_ALL’ in the
‘Changeable’ column of PHP manual [http://www.php.net/manual/en/ini.list.php].
Let’s see an example where we are modifying the SQL connection timeout using ini_set() function and
later on verify the configured value by using ini_get() function.
echo ini_get('mysql.connect_timeout'); // OUTPUT 60
ini_set('mysql.connect_timeout',100);
echo "<br>";
Answer.
Permissions in PHP are very similar to UNIX. Each file has the following three types of permissions.
• Read,
• Write and
• Execute.
PHP uses the <chmod()> function to change the permissions of a specific file. It returns TRUE on
success and FALSE on failure.
Following is the Syntax.
chmod(file,mode)
- file
Mandatory parameter. It indicates the name of the file to set the permissions.
- mode
Mandatory parameter. Specifies the new permissions. The mode parameter consists of
four numbers.
• File
• Mandatory parameter. It indicates the name of the file to set the permissions.
• Mode
• Mandatory parameter. Specifies the new permissions. The mode parameter consists of
four numbers.
1. The first number is always zero.
2. The second number specifies the permissions for the owner.
3. The third number specifies the permissions for the owner’s user group.
4. The fourth number specifies the permissions for everybody else.
Possible values are (add up the numbers to set multiple permissions)
• 1 = execute permissions
• 2 = write permissions
• 4 = read permissions
For Example.
To set read and write permission for the owner and read for everybody else, we use.
chmod("test.txt",0644);
Answer.
The use of urlencode() is to encode a string before using it in a query part of a URL. It encodes the
same way as posted data from a web page is encoded. It returns the encoded string.
Following is the Syntax.
urlencode (string $str )
Answer.
The name of that Extension is Xdebug. It uses the DBGp debugging protocol for debugging. It is
highly configurable and adaptable to a variety of situations.
Xdebug provides the following details in the debug information.
• Stack and function trace in the error messages.
• Full parameter display for user-defined functions.
• It displays function name, file name and line indications where the error occurs.
• Support for member functions.
• Memory allocation
• Protection for infinite recursions
Xdebug also provides.
• Profiling information for PHP scripts.
• Code coverage analysis.
• Capabilities to debug your scripts interactively with a front-end debugger.
• Xdebug is also available via PECL.
5. 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. Sessions are commonly used to store temporary data to allow multiple PHP pages to
offer a complete functional transaction for the same visitor.
6. How can we register the variables into a session?
<?php
session_register($ur_session_var);
?>
7. How many ways we can pass the variable through the navigation between the pages?
Register the variable into the session
Pass the variable as a cookie
Pass the variable as part of the URL
8. How can we know the total number of elements of Array?
sizeof($array_var)
count($array_var)
9. How can we create a database using php?
mysql_create_db();
CRYPT(), MD5()
16. What are the differences between Get and post methods.
There are some defference between GET and POST method
1. GET Method have some limit like only 2Kb data able to send for request
But in POST method unlimited data can we send
2. when we use GET method requested data show in url but
Not in POST method so POST method is good for send sensetive request
21. How can we encrypt the username and password using php?
You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD("Password");
We can encode data using base64_encode($string) and can decode using base64_decode($string);
25. What does a special set of tags <?= and ?> do in PHP?
The output is displayed directly to the browser.
29. What is the difference between the functions unlink and unset?
unlink() deletes the given file from the file system.
unset() makes a variable undefined.
30. How many ways can we get the value of current session id?
session_id() returns the session id for the current session.
33. How can we get second of the current time using date function?
<?php
$second = date(“s”);
?>
34. What are the Formatting and Printing Strings available in PHP?
printf()- Displays a formatted string
sprintf()-Saves a formatted string in a variable
fprintf() -Prints a formatted string to a file
number_format()-Formats numbers as strings
35. How can we find the number of rows in a result set using PHP?
$result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo "$num_rows rows found";
besanttechnologies.com
We would advise you read this blog because it provides an insight of the following:
• A significant PHP Interview Questions and Answers which will be very helpful for those who
are trying for a job in web development and want to start a career in PHP.
• Customized PHP Interview Questions for Freshers as well as it will be useful for experienced
candidates too.
• Generally required technical PHP Interview Questions and answers in 2018.
PHP 5 is an upgrade version of PHP 4. PHP 5 offers many extra OOPs features. It introduces new
functions which are not found in PHP4.
In PHP 5, you have to name your constructors.
In PHP 5, Class can be declared as Abstract.
PHP 5 introduced a special function which is __autoload().
In PHP 5, Class or method can be declared as Final.
In PHP 5, Magic methods are introduced such as __call, __get, __set and __toString.
In PHP 5, ‘exceptions'(exception errors) has introduced.
In PHP 5, interfaces are introduced.
17. What are tags used?
They allow making the result of the expression between the tags directly to the browser response.
18. What is the difference between explode() and split() functions?
Split function splits a string into array by regular expression. Explode splits a string into array by
string.
19. Is PHP supports multiple inheritance?
The PHP comprises only single inheritance which means that a class could be enlarged from just one
single class utilizing the keyword ‘extended.’
20. What is the use of count function in MySQL?
count() function is used for fetching the total number records in a table.
Conclusion:
Are you want to become a PHP developer? If you are looking for a job in web development, we hope
these PHP interview questions and answers will get you on the right track of finding a good developer
for your needs.
If you are interested in learning Advanced level PHP programming, Join any professional PHP training
course. This professional course will assist you to get advanced knowledge in PHP and become a full-
stack web developer.
PHP Interview questions
IT Job usually ask the following questions ?
unset() method won't change array key when array_splice() method change the array
keys automatically
17.What is the use of 'print' in php?
This is not actually a real function, It is a language construct. So you can use with out
parentheses with its argument list.
Example print('PHP Interview questions');
print 'Job Interview ');
18.What is use of in_array() function in php ?
in_array used to checks if a value exists in an array
19.What is use of count() function in php ?
count() is used to count all elements in an array, or something in an object
20.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.
21.What is the difference between Session and Cookie?
The main difference between sessions and cookies is that sessions are stored on the server, and
cookies are stored on the user's computers in the text file format. Cookies can't hold multiple
variable while session can hold multiple variables..We can set expiry for a cookie,The session
only remains active as long as the browser is open.Users do not have access to the data you
stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose
while cookies using for user activity tracking
22.How to set cookies in PHP?
Setcookie("sample", "ram", time()+3600);
23.How to Retrieve a Cookie Value?
eg : echo $_COOKIE["user"];
24.How to create a session? How to set a value in session ? How to Remove data from a
session?
Create session : session_start();
Set value into session : $_SESSION['USER_ID']=1;
Remove data from a session : unset($_SESSION['USER_ID'];
25.what types of loops exist in php?
for,while,do while and foreach (NB: You should learn its usage)
26.Note:-
MySQLi (the "i" stands for improved) and PDO (PHP Data Objects) are the MySQL extensions
used to connect to the MySQL server in PHP5 or verions, MySQL extension was deprecated in
2012.
MySQLi only works with MySQL databases whereas PDO will works with 12 other Database
systems
I recommend PDO because, if you want to choose another database instead of MySQL, then
you only have to change the connection string and a few queries. But if you are using MySQLi
you will need to rewrite the entire code
27.How to create a mysql connection?
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB"; // Optional
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB"; // Optional
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) { // fetch data from the result set
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
Example (MySQLi Procedural)
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) { // fetch data from the result set
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
Example (PDO)
Method 1:USE PDO query method
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
31.How we can retrieve the data in the result set of MySQL using PHP?
MySQLi methods
• 1. mysqli_fetch_row
• 2. mysqli_fetch_array
• 3. mysqli_fetch_object
• 4. mysqli_fetch_assoc
PDO methods
• 1. PDOStatement::fetch(PDO::FETCH_ASSOC)
• 2. PDOStatement::fetch(PDO::FETCH_OBJ)
• 3. PDOStatement::fetch()
• 4. PDOStatement::fetch(PDO::FETCH_NUM)
32.What is the use of explode() function ?
Syntax : array explode ( string $delimiter , string $string [, int $limit ] );
This function breaks a string into an array. Each of the array elements is a substring of string
formed by splitting it on boundaries formed by the string delimiter.
33.What is the difference between explode() and str_split() functions?
str_split function splits string into array by regular expression. Explode splits a string into array
by string.
34.What is the use of mysqli_real_escape_string() function?
It is used to escapes special characters in a string for use in an SQL statement
35.Write down the code for save an uploaded file in php.
<?php
if ($_FILES["file"]["error"] == 0)
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
?>
36.How to create a text file in php?
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" ); exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
37.How to strip whitespace (or other characters) from the beginning and end of a string ?
The trim() function removes whitespaces or other predefined characters from both sides of a
string.
38.What is the use of header() function in php ?
The header() function sends a raw HTTP header to a client browser.Remember that this function
must be called before sending the actual out put.For example, You do not print any HTML
element before using this function.
39.How to redirect a page in php?
The following code can be used for it, header("Location:index.php");
40.How stop the execution of a php scrip ?
exit() function is used to stop the execution of a page
41.How to set a page as a home page in a php based site ?
index.php is the default name of the home page in php based sites
42.How to find the length of a string?
strlen() function used to find the length of a string
43.what is the use of rand() in php?
It is used to generate random numbers.If called without the arguments it returns a pseudo-
random integer between 0 and getrandmax(). If you want a random number between 6 and 12
(inclusive), for example, use rand(6, 12).This function does not generate cryptographically safe
values, and should not be used for cryptographic uses. If you want a cryptographically secure
value, consider using openssl_random_pseudo_bytes() instead.
44.what is the use of isset() in php?
This function is used to determine if a variable is set and is not NULL
45.What is the difference between mysqli_fetch_array() and mysqli_fetch_assoc() ?
mysqli_fetch_assoc function Fetch a result row as an associative array, While
mysqli_fetch_array() fetches an associative array, a numeric array, or both
46.What is mean by an associative array?
Associative arrays are arrays that use string keys is called associative arrays.
47.What is the importance of "method" attribute in a html form?
"method" attribute determines how to send the form-data into the server.There are two methods,
get and post. The default method is get.This sends the form information by appending it on the
URL.Information sent from a form with the POST method is invisible to others and has no
limits on the amount of information to send.
48.What is the importance of "action" attribute in a html form?
The action attribute determines where to send the form-data in the form submission.
49.What is the use of "enctype" attribute in a html form?
The enctype attribute determines how the form-data should be encoded when submitting it to
the server. We need to set enctype as "multipart/form-data" when we are using a form for
uploading files
50.How to create an array of a group of items inside an HTML form ?
We can create input fields with same name for "name" attribute with squire bracket at the end of
the name of the name attribute, It passes data as an array to PHP.
For instance :
<input name="animal[]" id="cat" />
<input name="animal[]" id="rat" />
<input name="animal[]" id="lion" />
<input name="animal[]" id="snake" />
51.Define Object-Oriented Methodology
Object orientation is a software programming methodology that is based on the modeling a real
world system.An object is the core concept involved in the object orientation. An object is the
copy of the real world enity.An object oriented model is a collection of objects and its inter-
relationships
52.How do you define a constant?
Using define() directive, like define ("MYCONSTANT",150)
53.How send email using php?
To send email using PHP, you use the mail() function.This mail() function accepts 5 parameters
as follows (the last 2 are optional). You need webserver, you can't send email from localhost.
eg :
<?php
mail($to,$subject,$message,$headers);
?>
mcrypt_encrypt :- string mcrypt_encrypt ( string $cipher , string $key , string $data , string
$mode [, string $iv ] );
Encrypts plaintext with given parameters
54.How to find current date and time?
The date() function provides you with a means of retrieving the current date and time, applying
the format integer parameters indicated in your script to the timestamp provided or the current
local time if no timestamp is given. In simplified terms, passing a time parameter is optional - if
you don't, the current timestamp will be used.
55.How to find the number of days between two dates ?
<?php
$now = time(); // or your date as well
$your_date = strtotime("2010-01-31");
$datediff = $now - $your_date;
echo round($datediff / (60 * 60 * 24));
?>
56.How to convert one date format into another in PHP ?
<?php
$old_date = date('l, F d y h:i:s'); // returns Saturday, January 30 10 02:06:34
$old_date_timestamp = strtotime($old_date);
$new_date = date('Y-m-d H:i:s', $old_date_timestamp);
?>
57.What is the use of "ksort" in php?
It is used for sort an array by key in reverse order.
58.What is the difference between $var and $$var?
They are both variables. But $var is a variable with a fixed name. $$var is a variable who's
name is stored in $var. For example, if $var contains "message", $$var is the same as $message.
59.What are the encryption techniques in PHP
MD5 PHP implements the MD5 hash algorithm using the md5 function,
<?php
$encrypted_text = md5 ($msg);
?>
60.What is the use of the function htmlentities?
htmlentities Convert all applicable characters to HTML entities This function is identical to
htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML
character entity equivalents are translated into these entities.
61.How to delete a file from the system
Unlink() deletes the given file from the file system.
62.How to get the value of current session id?
session_id() function returns the session id for the current session.
63.What are the differences between mysqli_fetch_array(), mysqli_fetch_object(),
mysqli_fetch_row()?
• Mysqli_fetch_array Fetch a result row as an associative array, a numeric array, or both.
• mysqli_fetch_object ( resource result ) Returns an object with properties that correspond
to the fetched row and moves the internal data pointer ahead. Returns an object with
properties that correspond to the fetched row, or FALSE if there are no more rows
• mysqli_fetch_row() fetches one row of data from the result associated with the specified
result identifier. The row is returned as an array. Each result column is stored in an array
offset, starting at offset 0.
64.Why we shouldn't use mysql_* functions in PHP?
• Is not under active development
• Is officially deprecated as of PHP 5.5 (released June 2013).
• Has been removed entirely as of PHP 7.0 (released December 2015)
65.What are the different types of errors in PHP ?
Here are three basic types of runtime errors in PHP:
• 1. Notices: These are trivial, non-critical errors that PHP encounters while executing a
script - for example, accessing a variable that has not yet been defined. By default, such
errors are not displayed to the user at all - although you can change this default behavior.
• 2. Warnings: These are more serious errors - for example, attempting to include() a file
which does not exist. By default, these errors are displayed to the user, but they do not
result in script termination.
• 3. Fatal errors: These are critical errors - for example, instantiating an object of a non-
existent class, or calling a non-existent function. These errors cause the immediate
termination of the script, and PHP's default behavior is to display them to the user when
they take place.
66.what is sql injection ?
SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web
applications
67.What is x+ mode in fopen() used for?
Read/Write. Creates a new file. Returns FALSE and an error if file already exists
68.How to find the position of the first occurrence of a substring in a string
strpos() is used to find the position of the first occurrence of a substring in a string
69.What is PEAR?
PEAR is a framework and distribution system for reusable PHP components.The project seeks
to provide a structured library of code, maintain a system for distributing code and for managing
code packages, and promote a standard coding style.PEAR is broken into three classes: PEAR
Core Components, PEAR Packages, and PECL Packages. The Core Components include the
base classes of PEAR and PEAR_Error, along with database, HTTP, logging, and e-mailing
functions. The PEAR Packages include functionality providing for authentication, networking,
and file system features, as well as tools for working with XML and HTML templates.
70.Distinguish between urlencode and urldecode?
This method is best when encode a string to used in a query part of a url. it returns a string in
which all non-alphanumeric characters except -_. have replece with a percentege(%) sign . the
urldecode->Decodes url to encode string as any %and other symbole are decode by the use of
the urldecode() function.
71.What are the different errors in PHP?
In PHP, there are three types of runtime errors, they are:
Warnings:
These are important errors. Example: When we try to include () file which is not available.
These errors are showed to the user by default but they will not result in ending the script.
Notices:
These errors are non-critical and trivial errors that come across while executing the script in
PHP. Example: trying to gain access the variable which is not defined. These errors are not
showed to the users by default even if the default behavior is changed.
Fatal errors:
These are critical errors. Example: instantiating an object of a class which does not exist or a
non-existent function is called. These errors results in termination of the script immediately and
default behavior of PHP is shown to them when they take place. Twelve different error types are
used to represent these variations internally.
72.What is a REST API?
An API is an interface which can be a program or a web application which is capable to
communicate to other websites or programs
REST stands for REpresentational State Transfer and is an architectural style for exposing your
program using existing protocols, typically HTTP
A REST API utilize HTTP Methods like GET/POST/DELETE/UPDATE etc to get or set data in
a server
73.Give me the list of function you are usually using when you debug your PHP scripts ?
During the development time, i will put error_reporting(E_ALL); ini_set('display_errors', 1); on
the top of the php script to display all the errors and notices.
I will use print_r, var_dump functions to debug logical errors, there are so many other function
also available for the same.
74.What are magic constants in PHP?
Magic constants are predefined constants which starts and ends with double underscore (__).
Following are some of the magic constants.
• __LINE__
• __FUNCTION__
• __CLASS__
• __FILE__
• __METHOD__
75.Does PHP support multiple inheritance ?
PHP does not support multiple inheritance it will support only single inheritance. We can use
the keyword extent a class from another class
76.What is the use of print_r function?
print_r function can be used to display human readable format of an array
77.What happened if we pass '0' as the parameter to set_time_limit() function ?
It will set the the execution time as infinite
78.How to store the content of a file in to a a string variable?
File get contents function can be e used to to read the content of a file and save the the data into
a variable
79.How to find the number of rows returned from a MySQL result set?
mysqli_num_rows function can be used to find the number of rows of a rasult set
80.What is the difference between the empty() and isset() ?
isset() function is used to check available is already declared or not while empty() function is
used to check weather the variable has a value or not
81.What is the use of the key word global ?
If we declare a variable as 'global' then we can access it within the PHP functions
82.How to get the current memory usage in PHP?
memory_get_usage function can be used to get the memory usage information
83.What is scalar type declarations in in PHP 7?
It's a new feature in PHP 7 we can declare scalar types like inch string bullion fraught
84.Explain anonymous classes in PHP 7?
Anonymous classes does not require any name this anonymous classes can be e defined using
the new class. It will internal generate class names so we don't have to to give names to the
classes. IT can replace ful class definition.
85.How to collect IP address from an HTTP request ?
$_SERVER['REMOTE_ADDR'];
86.How to collect IP address of the Web server in php ?
$_SERVER['SERVER_ADDR'];
87.How to enable error reporting ?
error_reporting(E_ALL);
88.What is $_GLOBAL ?
It is an associative array which containing references to all variables currently defined in the
global scope of the script.
89.What is .htaccess file ?
.htaccess is a configuration file used to alter the default behavior of a Apache web server
software. Most common usage is to redirect the http request to some URLs based on some
conditions. For example, we can hide the .html or .php extensions of the URLs to make it SEO
friendly
90.How to print structured information about a available in PHP ?
var_dump — This function displays structured information about one or more expressions that
includes its value and type. Objects and arrays are explored recursively with values indented to
show structure.
Usage var_dump($a);
91.What is the difference between var_dump and print_r ?
var_dump will display all the information of a variable including keys values and types while
print_r display the keys and values only in a human readable format.
92.What is automatic type conversion ?
In php we can declare variables without specifying its type, php it do that process automatically
since PHP is a loosely types language.
For example :
<?php
//$count is a string variable
$count = "5";
//$count is an int variable
$count = "5";
93.How to make API calls from php scripts ?
We can use cURL library to make HTTP calls from a php script
<?php
$ch = curl_init();
$postData = 'var1=value1&var2=value2&var3=value3';
curl_setopt($ch, CURLOPT_URL, "http://mydomain.com/ajaxurl";);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
$ch = curl_exec($ch);
$ch = curl_close($ch);
echo $result;die;
94.How to change the php configurations at run time ?
We can use `ini_set` function to change the configurations of php at run time.
95.How can we resolve the errors like 'Maximum execution time of 30 seconds exceeded' ?
We can use the following code to increase the maximum execution time of the script
ini_set('max_execution_time', 300);
We can also set the max_execution_time for all the scripts in a website by the following code
in .htaccess file
<IfModule mod_php5.c> php_value max_execution_time 300 </IfModule>
But, we must try to optimize the php script to avoid this kind of situations as a part good user
experience.
96.How to avoid email sent through php getting into spam folder?
There's no special method of keeping your emails from being identified as spam. However we
can consider some points that cause this problem. Let me explain few common reasons.
1. sending mail using the `mail` function with minimum parameters
We must use all possible mail headers like `MIME-version`, `Content-type`, `reply address`,
`from address` etc in order to avoid this situation
2. Not using a proper SMTP mail script like PHPmailer or SwiftMailer with an actual e-mail
credentials including username, password etc
If we are able to send e-mail from an actual e-mail account using an SMTP mailer script with
username and password, then we can avoid
If you’re on a shared web server, consider buying a unique IP address for yourself, because
others using your IP may have gotten your IP blacklisted for spam. Do not send more than 250
emails to each provider per hour.
Give your users unsubscribe link and view in browser link, if they cannot see the email properly
they will mark you as spam, if they no longer want emails for you they will mark you as spam.
How can we prevent SQL injection in PHP?
Most popular way is, use prepared statements and parameterized queries. These are SQL
statements that are sent to and parsed by the database server separately from any parameters.
This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
• Using PDO (for any supported database driver):
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
// do something with $row
}
• What is CSS?
CSS Stands for Cascading Style Sheets. It is a platform independent web page designing
language and it will saves time because we can write this once and use the same in other pages.
• Which property specifies the distance between a marker and the text
in the list?
The marker-offset specifies the distance between a marker and the text in the list.
html4
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
Unit Description
em 1 em is the computed value of the font-size on the element on which it is used.
1 ex is the current font’s x-height. The x-height is usually (but not always, e.g., if there is
ex
no ‘x’ in the font) equal to the height of a lowercase ‘x’
ch 1 ch is the advance of the ‘0’ (zero) glyph in the current font. ‘ch’ stands for character.
rem 1 rem is the computed value of the font-size property for the document’s root element.
vw 1vw is 1% of the width of the viewport. ‘vw’ stands for ‘viewport width’.
vh 1vh is 1% of the height of the viewport. ‘vh’ stands for ‘viewport height’.
vmin Equal to the smaller of ‘vw’ or ‘vh’
vmax Equal to the larger of ‘vw’ or ‘vh’
• What is SVG?
SVG stands for Scalable Vector Graphics, It is an XML based two-dimensional vector graphics
image format.
102.
Object 2