Php Questions

You might also like

Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 165

edureka.

co

Top 50 PHP Interview Questions and Answers in


2020 | Edureka
Sayantini
22-28 minutes
PHP is a recursive acronym for PHP Hypertext Preprocessor. It is a widely used open-source
programming language especially suited for creating dynamic websites and mobile API’s. So, if you are
planning to start your career in PHP and you wish to know the skills related to it, now is the right time
to dive in. These PHP Interview Questions and Answers are collected after consulting with PHP
Certification Training experts.
The PHP Interview Questions are divided into 2 sections:
• Basic Level PHP Interview Questions
• Advanced Level PHP Interview Questions
Let’s begin with the first section of PHP interview questions.

Basic Level PHP Interview Questions


Q1. What are the common uses of PHP?
Uses of PHP
• It performs system functions, i.e. from files on a system it can create, open, read, write, and
close them.

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

• Access cookies variables and set cookies.

• Using PHP, you can restrict users to access some pages of your website and also encrypt data.

Q2. What is PEAR in PHP?


PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP Extension
and Application Repository. It contains all types of PHP code snippets and libraries. It also provides a
command line interface to install “packages” automatically.
Q3. What is the difference between static and dynamic websites?
Static Websites Dynamic Websites
In static websites, content can’t be changed after In dynamic websites, content of script can be
running the script. You cannot change anything in changed at the run time. Its content is regenerated
the site as it is predefined. every time a user visits or reloads.

Q4. How to execute a PHP script from the command line?


To execute a PHP script, use the PHP Command Line Interface (CLI) and specify the file name of
the script in the following way:

Q5. Is PHP a case sensitive language?


PHP is partially case sensitive. The variable names are case-sensitive but function names are not. If
you define the function name in lowercase and call them in uppercase, it will still work. User-defined
functions are not case sensitive but the rest of the language is case-sensitive.

Q6. What is the meaning of ‘escaping to PHP’?


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’. Escaping a string means to reduce ambiguity
in quotes used in that string.

Q7. What are the characteristics of PHP variables?


Some of the important characteristics of PHP variables include:
• 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.

Q8. What are the different types of PHP variables?


There are 8 data types in PHP which are used to construct the variables:
1. Integers − are whole numbers, without a decimal point, like 4195.
2. Doubles − are floating-point numbers, like 3.14159 or 49.1.
3. Booleans − have only two possible values either true or false.
4. NULL − is a special type that only has one value: NULL.
5. Strings − are sequences of characters, like ‘PHP supports string operations.’
6. Arrays − are named and indexed collections of other values.
7. Objects − are instances of programmer-defined classes, which can package up both other kinds
of values and functions that are specific to the class.
8. Resources − are special variables that hold references to resources external to PHP.

Q9. What are the rules for naming a PHP variable?


The following rules are needed to be followed while naming a PHP variable:
• 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.

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.

Q11. What is NULL?


NULL is a special data type which can have only one value. A variable of data type NULL is a variable
that has no value assigned to it. It can be assigned as follows:
The special constant NULL is capitalized by convention but actually it is case insensitive. So,you can
also write it as :
A variable that has been assigned the NULL value, consists of the following properties:
• It evaluates to FALSE in a Boolean context.
• It returns FALSE when tested with IsSet() function.
Q12. How do you define a constant in PHP?
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.If you have defined a constant, it can never be changed or undefined.
There is no need to have a constant with a $. A valid constant name starts with a letter or underscore.

Q13. What is the purpose of constant() function?


The constant() 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. For example –
<?php define("MINSIZE", 50); echo MINSIZE; echo
1 constant("MINSIZE"); // same thing as the previous line ?>

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.

Q15. Name some of the constants in PHP and their purpose.


1. _LINE_ – It represents the current line number of the file.
2. _FILE_ – It represents the full path and filename of the file. If used inside an include,the name
of the included file is returned.
3. _FUNCTION_ – It represents the function name.
4. _CLASS_ – It returns the class name as it was declared.
5. _METHOD_ – It represents the class method name.

Q16. What is the purpose of break and continue statement?


Break – It terminates the for loop or switch statement and transfers execution to the statement
immediately following the for loop or switch.
Continue – It causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.

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:

1 <?php [ --- PHP code---- ] ?>


Q18. What is the difference between PHP4 and PHP5?
PHP4 PHP5
• Constructor have same name as the • Constructors are named as _construct and
Class name. Destructors as _destruct().

• Everything is passed by value. • All objects are passed by references.

• PHP4 does not declare a class as


• PHP5 allows to declare a class as abstract
abstract

• It doesn’t have static methods and • It allows to have static Methods and Properties
properties in a class in a class

Q19. What is the meaning of a final class and a final method?


The final keyword in a method declaration indicates that the method cannot be overridden by
subclasses. A class that is declared final cannot be subclassed. This is particularly useful when we are
creating an immutable class like the String class.Properties cannot be declared final, only classes and
methods may be declared as final.

Q20. How can you compare objects in PHP?


We use the operator ‘==’ to test if two objects are instanced from the same class and have same
attributes and equal values. We can also test if two objects are referring to the same instance of the
same class by the use of the identity operator ‘===’.

Q21. How can PHP and Javascript interact?


PHP and Javascript cannot directly interact since PHP is a server side language and Javascript is a
client-side language. However, we can exchange variables since PHP can generate Javascript code to
be executed by the browser and it is possible to pass specific variables back to PHP via the URL.

Q22. How can PHP and HTML interact?


It is possible to generate HTML through PHP scripts, and it is possible to pass pieces of information
from HTML to PHP. PHP is a server side language and HTML is a client side language so PHP
executes on server side and gets its results as strings, arrays, objects and then we use them to display its
values in HTML.

Q23. Name some of the popular frameworks in PHP.


Some of the popular frameworks in PHP are:
• CakePHP
• CodeIgniter
• Yii 2
• Symfony
• Zend Framework

Q24. What are the data types in PHP?


PHP support 9 primitive data types:

Scalar Types Compound Types Special Types


• Integer
• Array
• Boolean • Resource
• Object
• Float • Null
• Callable
• String

Q25. What are constructor and destructor in PHP?


PHP constructor and destructor are special type functions which are automatically called when a PHP
class object is created and destroyed. The constructor is the most useful of the two because it allows
you to send parameters along when creating a new object, which can then be used to initialize variables
on the object.
Here is an example of constructor and destructor in PHP:

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.

Q27. What is the main difference between require() and require_once()?


The require() includes and evaluates a specific file, while require_once() does that only if it has not
been included before. The require_once() statement can be used to include a php file in another one,
when you may need to include the called file more than once. So, require_once() is recommended to
use when you want to include a file where you have a lot of functions.

Q28. What are different types of errors available in Php ?


The different types of error in PHP are:
• E_ERROR– A fatal error that causes script termination.
• E_WARNING– Run-time warning that does not cause script termination.
• E_PARSE– Compile time parse error.
• E_NOTICE– Run time notice caused due to error in code.
• E_CORE_ERROR– Fatal errors that occur during PHP initial startup.
• E_CORE_WARNING– Warnings that occur during PHP initial startup.
• E_COMPILE_ERROR– Fatal compile-time errors indication problem with script.
• E_USER_ERROR– User-generated error message.
• E_USER_WARNING– User-generated warning message.
• E_USER_NOTICE- User-generated notice message.
• E_STRICT– Run-time notices.
• E_RECOVERABLE_ERROR– Catchable fatal error indicating a dangerous error
• E_ALL– Catches all errors and warnings.

Q29. Explain the syntax for ‘foreach’ loop with example.


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.
Syntax-
foreach (array as value)
{
code to be executed;
}
Example-

1
<?php
2
$colors = array("blue", "white", "black");
3
foreach ($colors as $value) {
4
echo "$value
5
";
6
}
7
?>
8

Q30. What are the different types of Array in PHP?


There are 3 types of Arrays in PHP:
1. Indexed Array – An array with a numeric index is known as the indexed array. Values are
stored and accessed in linear fashion.
2. Associative Array – An array with strings as index is known as the associative array. This
stores element values in association with key values rather than in a strict linear index order.
3. Multidimensional Array – An array containing one or more arrays is known as
multidimensional array. The values are accessed using multiple indices.

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

3 $statement = 'My $variable will not print!n';

4 print($statement);

5 print "

6 ;"

7 $statement = "My $variable will print!n"

8 print($statement);

9 ?>

It will give the following output–


My $variable will not print!

My name will print

Q32. How to concatenate two strings in PHP?


To concatenate two string variables together, we use the dot (.) operator.
<?php $string1="Hello edureka"; $string2="123"; echo $string1 . " "
1 . $string2; ?>

This will produce following result −


Hello edureka 123

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.

Programming & Frameworks Training

Q34. What is the difference between “echo” and “print” in PHP?


• PHP echo output one or more string. It is a language construct not a function. So use of
parentheses is not required. But if you want to pass more than one parameter to echo, use of
parentheses is required. Whereas, PHP print output a string. It is a language construct not a
function. So use of parentheses is not required with the argument list. Unlike echo, it always
returns 1.
• Echo can output one or more string but print can only output one string and always returns 1.
• Echo is faster than print because it does not return any value.

Q35. Name some of the functions in PHP.


Some of the functions in PHP include:
• ereg() – The ereg() function searches a string specified by string for a string specified by
pattern, returning true if the pattern is found, and false otherwise.
• ereg() – The ereg() function searches a string specified by string for a string specified by
pattern, returning true if the pattern is found, and false otherwise.
• split() – The split() function will divide a string into various elements, the boundaries of each
element based on the occurrence of pattern in string.
• preg_match() – The preg_match() function searches string for pattern, returning true if pattern
exists, and false otherwise.
• preg_split() – The preg_split() function operates exactly like split(), except that regular
expressions are accepted as input parameters for pattern.
These were some of the most commonly asked basic level PHP interview questions. Let’s move on to
the next section of advanced level PHP interview questions.

Advanced level PHP Interview Questions


Q36. What is the main difference between asp net and PHP?
PHP is a programming language whereas ASP.NET is a programming framework. Websites
developed by ASP.NET may use C#, but also other languages such as J#. ASP.NET is compiled
whereas PHP is interpreted. ASP.NET is designed for windows machines, whereas PHP is platform free
and typically runs on Linux servers.

Q37. What is the use of session and cookies in PHP?


A session is a global variable stored on the server. Each session is assigned a unique id which is used to
retrieve stored values. Sessions have the capacity to store relatively large data compared to cookies.
The session values are automatically deleted when the browser is closed.
Following example shows how to create a cookie in PHP-
<?php $cookie_value = "edureka"; setcookie("edureka",
1 $cookie_value, time()+3600, "/your_usename/", "edureka.co", 1, 1);
if (isset($_COOKIE['cookie'])) echo $_COOKIE["edureka"]; ?>

Following example shows how to start a session in PHP-

1 <?php session_start(); if( isset( $_SESSION['counter'] ) )


{ $_SESSION['counter'] += 1; }else { $_SESSION['counter'] = 1; }
$msg = "You have visited this page". $_SESSION['counter']; $msg .=
"in this session."; ?>

Q38. What is overloading and overriding in PHP?


Overloading is defining functions that have similar signatures, yet have different parameters.
Overriding is only pertinent to derived classes, where the parent class has defined a method and the
derived class wishes to override that method. In PHP, you can only overload methods using the magic
method __call.

Q40. What is the difference between $message and $$message in


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

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


The basic steps to create MySQL database using PHP are:
• Establish a connection to MySQL server from your PHP script.
• If the connection is successful, write a SQL query to create a database and store it in a string
variable.
• Execute the query.

Q42. What is GET and POST method in PHP?


The GET method sends the encoded user information appended to the page request. The page and the
encoded information are separated by the ? character. For example –
<a href="http://www.test.com/index.htm?
1 name1=value1&name2=value2">http://www.test.com/index.htm?
name1=value1&name2=value2</a>

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.

Q43. What is the difference between GET and POST method?


GET POST
• The GET method is restricted to send upto • The POST method does not have any
1024 characters only. restriction on data size to be sent.

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

Q44. What is the use of callback in PHP?


PHP callback are functions that may be called dynamically by PHP. They are used by native functions
such as array_map, usort, preg_replace_callback, etc. A callback function is a function that you
create yourself, then pass to another function as an argument. Once it has access to your callback
function, the receiving function can then call it whenever it needs to.
Here is a basic example of callback function –

1 <?php

2 function thisFuncTakesACallback($callbackFunc)

3 {

4 echo "I'm going to call $callbackFunc!

5 ";

6 $callbackFunc();

7 }

8 function thisFuncGetsCalled()

9 {

10 echo "I'm a callback function!

11 ";

12 }

13 thisFuncTakesACallback( 'thisFuncGetsCalled' );

14 ?>

15
16

Q45. What is a lambda function in PHP?


A lambda function is an anonymous PHP function that can be stored in a variable and passed as an
argument to other functions or methods. A closure is a lambda function that is aware of its surrounding
context. For example –

1 $input = array(1, 2, 3, 4, 5);

2 $output = array_filter($input, function ($v) { return $v > 2; });

function ($v) { return $v > 2; } is the lambda function definition. We can store it in a variable so that it
can be reusable.

Q46. What are PHP Magic Methods/Functions?


In PHP all functions starting with __ names are magical functions/methods. These methods, identified
by a two underscore prefix (__), function as interceptors that are automatically called when certain
conditions are met. PHP provides a number of ‘magic‘ methods that allow you to do some pretty neat
tricks in object oriented programming.
Here are list of Magic Functions available in PHP

__destruct() __sleep()
__construct() __wakeup()
__call() __toString()
__get() __invoke()
__set() __set_state()
__isset() __clone()
__unset() __debugInfo()

Q47. How can you encrypt password using PHP?

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.

Q49. What is Type hinting in PHP?


Type hinting is used to specify the expected data type of an argument in a function declaration. When
you call the function, PHP will check whether or not the arguments are of the specified type. If not, the
run-time will raise an error and execution will be halted.
Here is an example of type hinting–

1 <?php function sendEmail (Email $email) { $email->send();

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

Top 69 PHP Interview Questions - javatpoint


17-21 minutes
There is given PHP interview questions and answers that have been asked in many companies. Let's see
the list of top PHP interview questions.

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

2) What is PEAR in PHP?


PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP Extension
and Application Repository. It contains all types of PHP code snippets and libraries.
It also provides a command line interface to install "packages" automatically.

3) Who is known as the father of PHP?


Rasmus Lerdorf

4) What was the old name of PHP?


The old name of PHP was Personal Home Page.

5) Explain the difference b/w static and dynamic websites?


In static websites, content can't be changed after running the script. You can't change anything on the
site. It is predefined.
In dynamic websites, content of script can be changed at the run time. Its content is regenerated every
time a user visit or reload. Google, yahoo and every search engine is the example of dynamic website.

6) What is the name of scripting engine in PHP?


The scripting engine that powers PHP is called Zend Engine 2.

7) Explain the difference between PHP4 and PHP5.


PHP4 doesn't support oops concept and uses Zend Engine 1.
PHP5 supports oops concept and uses Zend Engine 2.

8) What are the popular Content Management Systems (CMS) in PHP?


• WordPress: WordPress is a free and open-source content management system (CMS) based on
PHP & MySQL. It includes a plug-in architecture and template system. It is mostly connected
with blogging but supports another kind of web content, containing more traditional mailing
lists and forums, media displays, and online stores.
• Joomla: Joomla is a free and open-source content management system (CMS) for distributing
web content, created by Open Source Matters, Inc. It is based on a model-view-controller web
application framework that can be used independently of the CMS.
• Magento: Magento is an open source E-trade programming, made by Varien Inc., which is
valuable for online business. It has a flexible measured design and is versatile with many
control alternatives that are useful for clients. Magento utilizes E-trade stage which offers
organization extreme E-business arrangements and extensive support network.
• Drupal: Drupal is a CMS platform developed in PHP and distributed under the GNU (General
Public License).

9) What are the popular frameworks in PHP?


• CakePHP
• CodeIgniter
• Yii 2
• Symfony
• Zend Framework etc.

10) Which programming language does PHP resemble to?


PHP has borrowed its syntax from Perl and C.
11) List some of the features of PHP7.
• Scalar type declarations
• Return type declarations
• Null coalescing operator (??)
• Spaceship operator
• Constant arrays using define()
• Anonymous classes
• Closure::call method
• Group use declaration
• Generator return expressions
• Generator delegation
• Space ship operator

12) What is "echo" in PHP?


PHP echo output one or more string. It is a language construct not a function. So the use of parentheses
is not required. But if you want to pass more than one parameter to echo, the use of parentheses is
required.
Syntax:
1. void echo ( string $arg1 [, string $... ] )
More details...

13) What is "print" in PHP?


PHP print output a string. It is a language construct not a function. So the use of parentheses is not
required with the argument list. Unlike echo, it always returns 1.
Syntax:
More details...

14) What is the difference between "echo" and "print" in PHP?


Echo can output one or more string but print can only output one string and always returns 1.
Echo is faster than print because it does not return any value.
15) How a variable is declared in PHP?
A PHP variable is the name of the memory location that holds data. It is temporary storage.
Syntax:
More details...

16) What is the difference between $message and $$message?


$message stores variable data while $$message is used to store variable of variables.
$message stores fixed data whereas the data stored in $$message may be changed dynamically.
More Details...

17) What are the ways to define a constant in PHP?


PHP constants are name or identifier that can't be changed during execution of the script. PHP
constants are defined in two ways:
• Using define() function
• Using const() function
More details...

18) What are magic constants in PHP?


PHP magic constants are predefined constants, which change based on their use. They start with a
double underscore (__) and end with a double underscore (__).
More Details...

19) How many data types are there in PHP?


PHP data types are used to hold different types of data or values. There are 8 primitive data types which
are further categorized in 3 types:
• Scalar types
• Compound types
• Special types
More Details...

20) How to do single and multi line comment in PHP?


PHP single line comment is made in two ways:
• Using // (C++ style single line comment)
• Using # (Unix Shell style single line comment)
PHP multi-line comment is made by enclosing all lines within.
More details...

21) What are the different loops in PHP?


For, while, do-while and for each.

22) What is the use of count() function in PHP?


The PHP count() function is used to count total elements in the array, or something an object.

23) What is the use of header() function in PHP?


The header() function is used to send a raw HTTP header to a client. It must be called before sending
the actual output. For example, you can't print any HTML element before using this function.

24) What does isset() function?


The isset() function checks if the variable is defined and not null.

25) Explain PHP parameterized functions.


PHP parameterized functions are functions with parameters. You can pass any number of parameters
inside a function. These given parameters act as variables inside your function. They are specified
inside the parentheses, after the function name. Output depends upon dynamic values passed as
parameters into the function.
More details...

26) Explain PHP variable length argument function


PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments
in function. To do this, you need to use 3 ellipses (dots) before the argument name. The 3 dot concept is
implemented for variable length argument since PHP 5.6.
More details...
27) Explain PHP variable length argument function.
PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments.

28) What is the array in PHP?


An array is used to store multiple values in a single value. In PHP, it orders maps of pairs of keys and
values. It saves the collection of the data type.
More Details...

29) How many types of array are there in PHP?


There are three types of array in PHP:
1. Indexed array: an array with a numeric key.
2. Associative array: an array where each key has its specific value.
3. Multidimensional array: an array containing one or more arrays within itself.

30) Explain some of the PHP array functions?


There are many array functions in PHP:
• array()
• array_change_key_case()
• array_chunk()
• count()
• sort()
• array_reverse()
• array_search()
• array_intersect()
More details...

31) What is the difference between indexed and associative array?


The indexed array holds elements in an indexed form which is represented by number starting from 0
and incremented by 1. For example:
1. $season=array("summer","winter","spring","autumn");
The associative array holds elements with name. For example:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
More Details...
32) How to get the length of string?
The strlen() function is used to get the length of the string.
More Details...

33) Explain some of the PHP string functions?


There are many array functions in PHP:
• strtolower()
• strtoupper()
• ucfirst()
• lcfirst()
• ucwords()
• strrev()
• strlen()
More details...

34) What are the methods to submit form in PHP?


There are two methods GET and POST.
More Details...

35) How can you submit a form without a submit button?


You can use JavaScript submit() function to submit the form without explicitly clicking any submit
button.

36) What are the ways to include file in PHP?


PHP allows you to include file so that page content can be reused again. There are two ways to add the
file in PHP.
1. include
2. require
More details...
37) Differentiate between require and include?
Require and include both are used to include a file, but if data is not found include sends warning
whereas require sends Fatal error.
More Details...

38) Explain setcookie() function in PHP?


PHP setcookie() function is used to set cookie with HTTP response. Once the cookie is set, you can
access it by $_COOKIE superglobal variable.
Syntax:
1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
More details...

39) How can you retrieve a cookie value?


More Details...

40) What is a session?


PHP Engine creates a logical object to preserve data across subsequent HTTP requests, which is known
as session.
Sessions generally store temporary data to allow multiple PHP pages to offer a complete functional
transaction for the same user.
Simply, it maintains data of an user (browser).
More Details...

41) What is the method to register a variable into a session?


1. <?php
2. Session_register($ur_session_var);
3. ?>

42) What is $_SESSION in PHP?


A session creates a file in a temporary directory on the server where registered session variables and
their session id are stored. This data will be available to all pages on the site amid that visit.
The area of the temporary record is controlled by a setting in the php.ini document called
session.save_path.
At the point when a session is begun following things happen -
1. PHP first makes two duplicates of one of a kind session id for that particular session of the
client which is an arbitrary string of 32 hexadecimal numbers, for example,
3c7foj34c3jjhkyepop2fc937e3443.
2. One copy of unique session id automatically sent to the user?s computer for the sake of
synchronization in future ahead, and one copy is being maintained at server side till the session
is running.
3. Whenever you want to access the page of website or web app, then session id of the current user
will be associated with the HTTP header, and that will be compared by the session id which is
being maintained at the server. After completing the comparison process, you can easily access
the page of the website or web app
4. A session ends when the user closes the browser, or after leaving the site, the server will
terminate the session after a predetermined period, commonly 30 minutes duration.

43) What is PHP session_start() and session_destroy() function?


PHP session_start() function is used to start the session. It starts new or resumes the current session. It
returns the current session if the session is created already. If the session is not available, it creates and
returns new sessions.
More details...

44) What is the difference between session and cookie?


The main difference between session and cookie is that cookies are stored on user's computer in the
text file format while sessions are stored on the server side.
Cookies can't hold multiple variables, on the other hand, Session can hold multiple variables.
You can manually set an expiry for a cookie, while session only remains active as long as browser is
open.

45) Write syntax to open a file in PHP?


PHP fopen() function is used to open file or URL and returns resource. It accepts two arguments:
$filename and $mode.
Syntax:
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource
$context ]] )
More details...

46) How to read a file in PHP?


PHP provides various functions to read data from the file. Different functions allow you to read all file
data, read data line by line, and read data character by character.
PHP file read functions are given below:
• fread()
• fgets()
• fgetc()
More details...

47) How to write in a file in PHP?


PHP fwrite() and fputs() functions are used to write data into file. To write data into a file, you need to
use w, r+, w+, x, x+, c or c+ mode.
More details...

48) How to delete file in PHP?


The unlink() function is used to delete a file in PHP.
1. bool unlink (string $filename)
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.

50) How to upload file in PHP?


The move_uploaded_file() function is used to upload file in PHP.
1. bool move_uploaded_file ( string $filename , string $destination )
More Details...
51) How to download file in PHP?
The readfile() function is used to download the file in PHP.
1. int readfile ( string $filename )
More Details...

52) How can you send email in PHP?


The mail() function is used to send email in PHP.
1. bool mail($to,$subject,$message,$header);
More Details...

53) How do you connect MySQL database with PHP?


There are two methods to connect MySQL database with PHP. Procedural and object-oriented style.
More Details...

54) How to create connection in PHP?


The mysqli_connect() function is used to create a connection in PHP.
1. resource mysqli_connect (server, username, password)
More Details...

55) How to create database connection and query in PHP?


Since PHP 4.3, mysql_reate_db() is deprecated. Now you can use the following 2 alternatives.
• mysqli_query()
• PDO::_query()
More details...

56) How can we increase execution time of a PHP script?


By default, the maximum execution time for PHP scripts is set to 30 seconds. If a script takes more
than 30 seconds, PHP stops the script and returns an error.
You can change the script run time by changing the max_execution_time directive in the php.ini file.
When a script is called, set_time_limit function restarts the timeout counter from zero. It means, if
default timer is set to 30 sec, and 20 sec is specified in function set_time_limit(), then script will run for
45 seconds. If 0sec is specified in this function, script takes unlimited time.

57) What are the different types of errors in PHP?


There are 3 types of error in PHP.
1. Notices:These are non-critical errors. These errors are not displayed to the users.
2. Warnings:These are more serious errors, but they do not result in script termination. By
default, these errors are displayed to the user.
3. Fatal Errors:These are the most critical errors. These errors may cause due to immediate
termination of script.

58) How to stop the execution of PHP script?


The exit() function is used to stop the execution of PHP script.

59) What are the encryption functions in PHP?


CRYPT() and MD5()

60) What is htaccess in PHP?


The .htaccess is a configuration file on Apache server. You can change configuration settings using
directives in Apache configuration files like .htaccess and httpd.conf.

61) Explain PHP explode() function.


The PHP explode() function breaks a string into an array.

62) Explain PHP split() function.


The PHP split() function splits string into an array by regular expression.

63) How can we get IP address of a client in PHP?


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

65) What is the use of the function 'imagetypes()'?


imagetypes() gives the image format and types supported by the current version of GD-PHP.

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

67) What is Cookies? How to create cookies in PHP?


A cookie is used to identify a user. A cookie is a little record that the server installs on the client's
Computer. Each time a similar PC asks for a page with a program, it will send the cookie as well. With
PHP, you can both make and recover cookie value.
Some important points regarding Cookies:
1. Cookies maintain the session id generated at the back end after verifying the user's identity in
encrypted form, and it must reside in the browser of the machine
2. You can store only string values not object because you can't access any object across the
website or web apps
3. Scope: - Multiple pages.
4. By default, cookies are temporary and transitory cookie saves in the browser only.
5. By default, cookies are URL particular means Gmail isn't supported in Yahoo and the vice
versa.
6. Per site 20 cookies can be created in one website or web app
7. The Initial size of the cookie is 50 bytes.
8. The Maximum size of the cookie is 4096 bytes.
68) What is the Importance of Parser in PHP?
PHP parser parses the PHP developed website from the opening to the closing tag. Tags indicate that
from where PHP code is being started and ended. In other words, opening and closing tags decide the
scope of PHP scripting syntax of closing tag in PHP
<?php syntax of opening tag in PHP
?> syntax of closing tag in PHP

69) How can we create a database using PHP and MySQL?


The necessary steps to create a MySQL database using PHP are:
• Establish a connection to MySQL server from your PHP script.
• If the connection is successful, write a SQL query to create a database and store it in a string
variable.
• Execute the query.
tutorialspoint.com

PHP Interview Questions - Tutorialspoint


24-30 minutes

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

This will produce following result −


Hello World 1234
The strlen() function is used to find the length of a string. Let's find the length of our string "Hello
world!" −
<?php
echo strlen("Hello world!");
?>

This will produce following result −


12

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

This will produce following result −


6

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

This will produce following result −


My $variable will not print!\n
My name will print

To concatenate two string variables together, use the dot (.) operator.
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>

This will produce following result −


Hello World 1234

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']);
?>

A PHP session can be destroyed by session_destroy() function.


PHP makes use of mail() function to send an email. This function requires three mandatory arguments
that specify the recipient's email address, the subject of the the message and the actual message
additionally there are other two optional parameters.
mail( to, subject, message, headers, parameters );
This is a global PHP variable. This variable is an associate double dimension array and keeps all the
information related to uploaded file.
Using $_FILES['file']['tmp_name'] − it provides access to the uploaded file in the temporary directory
on the web server.
Using $_FILES['file']['name'] − it provides the actual name of the uploaded file.
Using $_FILES['file']['size'] − it provides the size in bytes of the uploaded file.
Using $_FILES['file']['type'] − it provides the MIME type of the uploaded file.
Using $_FILES['file']['error'] − it provides the error code associated with this file upload.
$GLOBALS − Contains a reference to every variable which is currently available within the global
scope of the script. The keys of this array are the names of the global variables.
$_SERVER − This is an array containing information such as headers, paths, and script locations. The
entries in this array are created by the web server. There is no guarantee that every web server will
provide any of these. See next section for a complete list of all the SERVER variables.
$_COOKIE − An associative array of variables passed to the current script via HTTP cookies.
$_SESSION − An associative array containing session variables available to the current script.
$_PHP_SELF − A string containing PHP script file name in which it is called.
$php_errormsg − $php_errormsg is a variable containing the text of the last error message generated by
PHP.
ereg() − The ereg() function searches a string specified by string for a string specified by pattern,
returning true if the pattern is found, and false otherwise.
eregi() − The eregi() function searches throughout a string specified by pattern for a string specified by
string. The search is not case sensitive.
The split() function will divide a string into various elements, the boundaries of each element based on
the occurrence of pattern in string.
preg_match() - The preg_match() function searches string for pattern, returning true if pattern exists,
and false otherwise.
The preg_split() function operates exactly like split(), except that regular expressions are accepted as
input parameters for pattern.
Using getMessage() method of Exception class which returns the message of exception.
Using getCode() method of Exception class which returns the code of exception.
Using getFile() method of Exception class which returns source filename.
Using getLine() method of Exception class which returns source line.
Using getTrace() method of Exception class which returns array of the backtrace.
Using getTraceAsString() method of Exception class which returns formated string of trace.
PHP's time() function gives you all the information that you need about the current date and time. It
requires no arguments but returns an integer.
The function getdate() optionally accepts a time stamp and returns an associative array containing
information about the date. If you omit the time stamp, it works with the current time stamp as returned
by time().
The date() function returns a formatted string representing a date. You can exercise an enormous
amount of control over the format that date() returns with a string argument that you must pass to it.
PHP provides mysql_connect function to open a database connection.
connection mysql_connect(server,user,passwd,new_link,client_flag);

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

If a resource is not specified then last opend database is closed.


PHP 5's new SimpleXML module makes parsing an XML document, well, simple. It turns an XML
document into an object that provides structured access to the XML. To create a SimpleXML object
from an XML document stored in a string, pass the string to simplexml_load_string( ). It returns a
SimpleXML object.
Yes!
PHP provides a special function called __construct() to define a constructor. You can pass as many as
arguments you like into the constructor function.
Like a constructor function you can define a destructor function using function __destruct(). You can
release all the resourceses with-in a destructor.
The variable $this is a special variable and it refers to the same object ie. itself.
Once you defined your class, then you can create as many objects as you like of that class type.
Following is an example of how to create object using new operator.
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
After creating your objects, you will be able to call member functions related to that object. One
member function will be able to process member variable of related object only. Following example
shows how to set title and prices for the three books by calling member functions.
$physics−>setTitle( "Physics for High School" );
$chemistry−>setTitle( "Advanced Chemistry" );
$maths−>setTitle( "Algebra" );
$physics−>setPrice( 10 );
$chemistry−>setPrice( 15 );
$maths−>setPrice( 7 );

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

Top 100 PHP Interview Questions and Answers


18-23 minutes
Download PDF
1) What is PHP?
PHP is a web language based on scripts that allow developers to dynamically create generated web
pages.
2) What do the initials of PHP stand for?
PHP means PHP: Hypertext Preprocessor.
3) Which programming language does PHP resemble?
PHP syntax resembles Perl and C
4) What does PEAR stand for?
PEAR means "PHP Extension and Application Repository". It extends PHP and provides a higher level
of programming for web developers.
5) What is the actually used PHP version?
Version 7.1 or 7.2 is the recommended version of PHP.
6) How do you execute a PHP script from the command line?
Just use the PHP command line interface (CLI) and specify the file name of the script to be executed as
follows:
php script.php

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

9) How can we display the output directly to the browser?


To be able to display the output directly to the browser, we have to use the special tags <?= and ?>.
10) What is the main difference between PHP 4 and PHP 5?
PHP 5 presents many additional OOP (Object Oriented Programming) features.
11) Is multiple inheritance supported in PHP?
PHP supports only single inheritance; it means that a class can be extended from only one single class
using the keyword 'extended'.
12) What is the meaning of a final class and a final method?
'final' is introduced in PHP5. Final class means that this class cannot be extended and a final method
cannot be overridden.
13) How is the comparison of objects done in PHP?
We use the operator '==' to test is two objects are instanced from the same class and have same
attributes and equal values. We can test if two objects are referring to the same instance of the same
class by the use of the identity operator '==='.
14) How can PHP and HTML interact?
It is possible to generate HTML through PHP scripts, and it is possible to pass pieces of information
from HTML to PHP.
15) What type of operation is needed when passing values through a form or an URL?
If we would like to pass values through a form or an URL, then we need to encode and to decode them
using htmlspecialchars() and urlencode().
16) How can PHP and Javascript interact?
PHP and Javascript cannot directly interact since PHP is a server side language and Javascript is a
client-side language. However, we can exchange variables since PHP can generate Javascript code to
be executed by the browser and it is possible to pass specific variables back to PHP via the URL.
17) What is needed to be able to use image function?
GD library is needed to execute image functions.
18) What is the use of the function 'imagetypes()'?
imagetypes() gives the image format and types supported by the current version of GD-PHP.
19) What are the functions to be used to get the image's properties (size, width, and height)?
The functions are getimagesize() for size, imagesx() for width and imagesy() for height.
20) How failures in execution are handled with include() and require() functions?
If the function require() cannot access the file then it ends with a fatal error. However, the include()
function gives a warning, and the PHP script continues to execute.
21) What is the main difference between require() and require_once()?
require(), and require_once() perform the same task except that the second function checks if the PHP
script is already included or not before executing it.
(same for include_once() and include())
22) How can I display text with a PHP script?
Two methods are possible:
<!--?php echo "Method 1"; print "Method 2"; ?-->

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

29) What is the function mysql_pconnect() useful for?


mysql_pconnect() ensure a persistent connection to the database, it means that the connection does not
close when the PHP script ends.
This function is not supported in PHP 7.0 and above
30) How be the result set of Mysql handled in PHP?
The result set can be handled using mysqli_fetch_array, mysqli_fetch_assoc, mysqli_fetch_object or
mysqli_fetch_row.
31) How is it possible to know the number of rows returned in the result set?
The function mysqli_num_rows() returns the number of rows in a result set.
32) Which function gives us the number of affected entries by a query?
mysqli_affected_rows() return the number of entries affected by an SQL query.
33) What is the difference between mysqli_fetch_object() and mysqli_fetch_array()?
The mysqli_fetch_object() function collects the first single matching record where
mysqli_fetch_array() collects all matching records from the table in an array.
34) How can we access the data sent through the URL with the GET method?
To access the data sent via the GET method, we use $_GET array like this:
www.url.com?var=value
$variable = $_GET["var"]; this will now contain 'value'

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

36) How can we check the value of a given variable is a number?


It is possible to use the dedicated function, is_numeric() to check whether it is a number or not.
37) How can we check the value of a given variable is alphanumeric?
It is possible to use the dedicated function, ctype_alnum to check whether it is an alphanumeric value
or not.
38) How do I check if a given variable is empty?
If we want to check whether a variable has a value or not, it is possible to use the empty() function.
39) What does the unlink() function mean?
The unlink() function is dedicated for file system handling. It simply deletes the file given as entry.
40) What does the unset() function mean?
The unset() function is dedicated for variable management. It will make a variable undefined.
41) How do I escape data before storing it in the database?
The addslashes function enables us to escape data before storage into the database.
42) How is it possible to remove escape characters from a string?
The stripslashes function enables us to remove the escape characters before apostrophes in a string.
43) How can we automatically escape incoming data?
We have to enable the Magic quotes entry in the configuration file of PHP.
44) What does the function get_magic_quotes_gpc() means?
The function get_magic_quotes_gpc() tells us whether the magic quotes is switched on or no.
45) Is it possible to remove the HTML tags from data?
The strip_tags() function enables us to clean a string from the HTML tags.
46) what is the static variable in function useful for?
A static variable is defined within a function only the first time, and its value can be modified during
function calls as follows:
<!--?php function testFunction() { static $testVariable = 1; echo $testVariable;
$testVariable++; } testFunction(); //1 testFunction(); //2
testFunction(); //3 ?-->

47) How can we define a variable accessible in functions of a PHP script?


This feature is possible using the global keyword.
48) How is it possible to return a value from a function?
A function returns a value using the instruction 'return $value;'.
49) What is the most convenient hashing method to be used to hash passwords?
It is preferable to use crypt() which natively supports several hashing algorithms or the function hash()
which supports more variants than crypt() rather than using the common hashing algorithms such as
md5, sha1 or sha256 because they are conceived to be fast. Hence, hashing passwords with these
algorithms can create vulnerability.
50) Which cryptographic extension provide generation and verification of digital signatures?
The PHP-OpenSSL extension provides several cryptographic operations including generation and
verification of digital signatures.
51) How is a constant defined in a PHP script?
The define() directive lets us defining a constant as follows:
define ("ACONSTANT", 123);

52) How can you pass a variable by reference?


To be able to pass a variable by reference, we use an ampersand in front of it, as follows $var1 =
&$var2
53) Will a comparison of an integer 12 and a string "13" work in PHP?
"13" and 12 can be compared in PHP since it casts everything to the integer type.
54) How is it possible to cast types in PHP?
The name of the output type has to be specified in parentheses before the variable which is to be cast as
follows:
* (int), (integer) - cast to integer
* (bool), (boolean) - cast to boolean
* (float), (double), (real) - cast to float
* (string) - cast to string
* (array) - cast to array
* (object) - cast to object
55) When is a conditional statement ended with endif?
When the original if was followed by: and then the code block without braces.
56) How is the ternary conditional operator used in PHP?
It is composed of three expressions: a condition, and two operands describing what instruction should
be performed when the specified condition is true or false as follows:
Expression_1?Expression_2 : Expression_3;

57) What is the function func_num_args() used for?


The function func_num_args() is used to give the number of parameters passed into a function.
58) If the variable $var1 is set to 10 and the $var2 is set to the character var1, what's the value of
$$var2?
$$var2 contains the value 10.
59) What does accessing a class via :: means?
:: is used to access static methods that do not require object initialization.
60) In PHP, objects are they passed by value or by reference?
In PHP, objects passed by value.
61) Are Parent constructors called implicitly inside a class constructor?
No, a parent constructor have to be called explicitly as follows:
parent::constructor($value)

62) What's the difference between __sleep and __wakeup?


__sleep returns the array of all the variables that need to be saved, while __wakeup retrieves them.
63) What is faster?
1- Combining two variables as follows:
$variable1 = 'Hello ';

$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

50+ Top PHP Interview Questions and Answers


in 2020 [Updated]
Vijay Singh
29-37 minutes
Hypertext Preprocessor also abbreviated as PHP is widely used scripting language specially used for
web development and can be embedded into HTML and is mostly executed in the server. This open-
source language was created in 1994 and is now managed by the PHP group. The language can run on
various platforms such as Windows, Linux, MacOSX, and is compatible with most of the servers used
today like Apache and IIS; the language also supports a wide range of databases.
So if you aspire to be a PHP developer, we have made a collection of popular PHP interview questions
to start your journey if you are a fresher or to contribute your journey if you are professional and want
to upgrade your skills.

Best PHP Interview Questions and Answers


Once you are done with double-checking all PHP core concepts and working hard to build adequacy
for best PHP frameworks, it’s time to assess how good you are. To help you, here we have compiled a
list of Most frequently asked PHP interview questions that will ensure you hit it right:

Question: What is PHP?


Answer: PHP (Hypertext Preprocessor) is a general-purpose scripting language, mostly implemented
in C and C++, that is suited for web development. It is a highly performant language as the code need
not be compiled before execution. PHP is free and open-sourced and can be easily learned. It is also
cost-effective as most web hosting servers support PHP by default. PHP is one of the most popular
programming languages of 2020. Sample code:
<?PHP
echo 'Good morning';
?>

Question: What are the Features of PHP7.4?


Answer: Some new features in PHP7.4 are:
• Preloading to further improve performance.
• Arrays spread operator.
• One line arrow functions (short closures) for cleaner code.
• Typed properties in the class.
• Formatting numeric values using underscores.
• Extension development using FFI.
• Better type of variance.
Question: Explain the difference between $message and $$message?
Answer: $message is a regular variable, which has a fixed name and fixed value, whereas a $$message
is a reference variable, which stores data about the variable. The value of $$message can change
dynamically as the value of variable changes.

Question: Explain magic constants in PHP?


Answer: Magic constants start and end with double underscores and are predefined constants that
change their value based on context and usage. There are 9 magic constants in PHP:
__LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS__, __TRAIT__, __METHOD__,
__NAMESPACE__, ClassName::class

Question: Explain various data types of PHP?


Answer: There are different data types in PHP:
• String: a sequence of characters, e.g.," Hackr.io."
• Float: a floating-point (decimal) number, e.g., 23.456
• Integer: an integer, e.g. 12
• Boolean: represents two states – true, false.
• Object: stores values of different data types into single entity, eg. apple = new Fruit();
• Array: stores multiple values of same type, eg. array("red", "yellow", "blue")
• NULL: when no value is assigned to a variable, it can be assigned NULL. For example, $msg =
NULL;

Question: Explain isset() function?


Answer: The isset() function checks if the particular variable is set and has a value other than NULL.
The function returns Boolean – false if the variable is not set or true if the variable is set. The function
can check multiple values: isset(var1, var2, var3…)

Question: Explain the various PHP array functions?


Answer: There are many array functions, all of which are part of the PHP core:

Array Functions Description


array() creates an array.
array_diff() compares arrays and returns the differences in the values.
array_keys() returns all the keys of the array.
array_reverse() reverses an array.
array_search() searches a value and returns the corresponding key.
array_slice() returns the specific parts of the array.
array_sum() sums all the values of an array.
count() the number of elements of an array.
Question: Check more functions on the PHP manual page.
Answer: Explain the difference between indexed and associative array?

Indexed Array Associative Array


Has numeric keys or indexes. Each key has its value.
Indexes start with 0 and are automatically assigned. Keys are assigned manually and can be strings too.
example,
example, $empdetails = array(“Sam”=>1200, “Mike”=>1201, “M
$fruits = array(“orange”, “apple”, banana);
here, the individual values can be accessed as,
here, orange is $fruits[0], apple is $fruits[1] and $empdetails[“Sam”] = “1200”;
banana is $fruits[2]
Similarly, others

Question: Explain various PHP string functions?


Answer: PHP allows many string operations. Some popular string functions are:

Function Description Example Usage


output one or more echo "Welcome to hackr.io"
echo()
string
$mystr = “welcome to hackr.io”
explode(“ ”, $mystr)
break string into
explode()
array will render [0] = “welcome” and so on

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.

Question: Explain the difference between require and include?


Answer: Both require and include are constructs and can be called without parentheses: include
myfile.php
However, if the file that is to be included is not found, include will issue a warning, and the script will
continue to run. Require will give a fatal error, and the script will stop then and there. If a file is critical
to the script, then require should be used, else it can be used.

Question: How to upload files in PHP?


Answer: Firstly, PHP should allow file uploads; this can be done by making the directive file_uploads
= On
You can then add the action method as 'post' with the encoding type as 'multipart/form-data.'
<formaction="myupload.php"method="post"enctype="multipart/form-data">

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: How to create a database connection and query in PHP?


Answer: To create database connection:
$connection = new mysqli($servername, $username, $password);
where $servername, $username, $password should be defined beforehand by the
developer.
To check if the connection was successful:
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
Create database query:
$sql = "CREATE DATABASE PRODUCT";
if ($conn->query($sql) === TRUE) {
echo "Database successfully created";
} else {
echo "Error while creating database: " . $conn->error;
}

Question: Explain Cookies? How to create cookies in PHP?


Answer: Cookies stores data about a user on the browser. It is used to identify a user and is embedded
on the user's computer when they request for a particular page. We can create cookies in PHP using the
setcookie() function:
setcookie(name, value, expire, path, domain, secure, httponly);

here name is mandatory, and all other parameters are optional.


Example,
setcookie(“instrument_selected”, “guitar”)

Question: Explain the Importance of Parser in PHP?


Answer: A PHP parser is a software that converts source code that the computer can understand. This
means whatever set of instructions we give in the form of code is converted into a machine-readable
format by the parser. You can parse PHP code with PHP using the token_get_all function.

Question: Explain the constant() function and its purposes?


Answer: constant() is used to retrieve the value of a constant. It accepts the name of the constant as the
input:
constant(string $name)

The function returns a constant value, if available, else returns null.

Question: Can you provide an example of a PHP Web Application Architecture?


Answer:

Question: Define the use of .htaccess and php.ini files in PHP?


Answer: Both of them are used for making changes to the PHP settings.
• .htaccess – A special file that can be used to change or manage the behavior of a website.
Directing all users to one page and redirecting the domain’s page to https or www are two of the
most important uses of the file. For .htaccess to work, PHP needs to be installed as an Apache
module.
• php.ini – This special file allows making changes to the default PHP settings. Either the default
php.ini file can be edited, or a new file can be created with relevant additions and then saved as
the php.ini file. For php.ini to work, PHP needs to run as CGI.

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: Explain Path Traversal?


Answer: Path Traversal is a form of attack to read into the files of a web application. ‘../’ is known as
dot-dot-sequences. It is a cross-platform symbol to go up in the directory. To operate the web
application file, Path Traversal makes use of the dot-dot-slash sequences.
The attacker can disclose the content of the file attacked using the Path Traversal outside the root
directory of a web server or application. It is usually done to gain access token, secret passwords, and
other sensitive information stored in the files.
Path Traversal is also known as Directory Traversal. It enables the attacker to exploit vulnerabilities
present in the web file under attack.

Question: Explain the difference between GET and POST requests.


Answer: Any PHP developer needs to have an adequate understanding of the HTTP protocol. The
differences between GET and POST are an indispensable part of the HTTP protocol learning. Here are
the major differences between the two requests:
• GET allows displaying the submitted data as part of the URL. This is not the case when using
POST as during this time, the data is encoded in the request.
• The maximum number of characters handled by GET is limited to 2048. No such restrictions
are imposed on POST.
• GET provides support for only ASCII data. POST, on the other hand, allows ASCII, binary data,
as well as other forms of data.
• Typically, GET is used for retrieving data while POST is used for inserting and updating data.

Question: Explain the mail function and its syntax.


Answer: To directly send emails from a script or website, the mail() function is used in PHP. It has a
total of 5 arguments. The general syntax of a mail function is:
mail (to, subject, message, headers, parameters);
• to denotes the receiver of the email
• subject denotes the subject of the email
• the message is the actual message that is to be sent in the mail (Each line is separated using /n,
and the maximum character limit is 70.)
• headers denote additional information about the mail, such as CC and BCC (Optional)
• parameters denote to some additional parameter to be included in the send mail program
(Optional)
Answer: Memcached is an effective caching daemon designed specifically for decreasing database
load in dynamic web applications. Memcache module offers a handy procedural and object-oriented
interface to Memcached.
Memcache is a memory storage space, and it is possible to run Memcache on a single or several
servers. Hence, it is possible to share a single instance of Memcache between multiple projects.
It is possible to configure a client to speak to a distinct set of instances. Therefore, running two
different Memcache processes on the same host is also allowed. Despite running on the same host, both
of such Memcache processes stay independent, unless there is a partition of data.

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 is the comparison of objects done in PHP?


Answer: The operator ‘==’ is used for checking whether two objects are instanced using the same class
and have the same attributes as well as equal values. To test whether two objects are referring to the
same instance of the same class, the identity operator ‘===’ is used.

Question: How is typecasting achieved in PHP?


Answer: The name of the output type needs to be specified in parentheses before the variable that is to
be cast. Some examples are:
• (array) – casts to array
• (bool), (boolean) – casts to Boolean
• (double), (float), (real) – casts to float
• (int), (integer) – casts to integer
• (object) – casts to object
• (string) – casts to string

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 some common error types in PHP?


Answer: PHP supports three types of errors:
• Notices – Errors that are non-critical. These occur during the script execution. Accessing an
undefined variable is an instance of a Notice.
• Warnings – Errors that have a higher priority than Notices. Like with Notices, the execution of a
script containing Warnings remains uninterrupted. An example of a Notice includes a file that
doesn’t exist.
• Fatal Error – A termination in the script execution results as soon as such an error is
encountered. Accessing a property of a non-existing object yields a Fatal Error.

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 are the Traits in PHP?


Answer: The mechanism allows for the creation of reusable code in PHP-like languages where there is
no support for multiple inheritances. A trait can’t be instantiated on its own.

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: How do static websites differ from dynamic websites?


Answer: There are two types of websites, static and dynamic. Differences between the two are
enumerated as follows:
• Advantage – The main advantage of a static website is flexibility, whereas the main advantage
for a dynamic website comes in the form of a CMS
• Changes/Modification – Changes are made to the content of a static website only when the file
is updated and published i.e., sent to the webserver. Dynamic websites, on the other hand,
contains “server-side” code that allows the server to generate unique content when the webpage
is loaded
• Content – The content remains the same every time the page is reloaded for a static website.
Contrarily, the content belonging to a dynamic website is updated regularly
• Response – Static websites send the same response for every request whereas dynamic websites
might generate different HTML for different requests
• Technologies Involved – Mere HTML is used for building static websites while dynamic
websites are developed using several technologies, such as ASP.Net, JSP, Servlet, and PHP

Question: Please explain the use of the imagetypes() function?


Answer: The imagetypes() function gives the image format and types supported by the present version
of the GD-PHP.

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: What do you understand by typecasting and type juggling?


Answer: When a variable’s data type is converted explicitly by the user, it is known as typecasting. The
PHP programming language doesn’t support explicit type definition in variable declaration. Hence, the
data type of the variable is determined by the context in which the variable is used.
For example, if a string value is assigned to a $var variable, then it automatically gets converted to a
string. Likewise, if an integer value is assigned to $var, then it becomes an integer. This is called type
juggling.

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: How will you display text with PHP Script?


Answer: Either the echo statement or the print statement can be used for displaying text with a PHP
script. In usual scenarios, the former is preferred over the latter because it is slightly faster.

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.

Question: Can you explain PHP parameterized functions?


Answer: Functions with parameters are known as PHP parameterized functions. It is possible to pass
as many parameters as you’d like inside a function. Specified inside the parentheses after the function
name, these all parameters act as variables inside the PHP parameterized function.
Question: Can you explain the difference between mysqli_connect() and mysqli_pconnect()
functions?
Answer: Both mysqli_connect() and mysqli_pconnect() are functions used in PHP for connecting to a
MySQL database. However, the latter ensures that a persistent connection is established with the
database. It means that the connection doesn’t close at the end of a PHP script.

Question: Explain $_SESSION in PHP?


Answer: The $_SESSION[] is called an associative array in PHP. It is used for storing session
variables that can be accessed during the entire lifetime of a session.

Question: Explain the difference between substr() and strstr() functions?


Answer: The substr() function returns a part of some string. It helps in splitting a string part-by-part in
PHP. This function is typically available in all programming languages with almost the same syntax.
General syntax:
substr(string, start, length);

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: Explain the use of the $_REQUEST variable?


Answer: $_REQUEST is an associative array that, by default, contains the contents of the $_COOKIE,
$_GET, $_POST superglobal variables.
Because the variables in the $_REQUEST array are provided to the PHP script via COOKIE, GET, and
POST input mechanisms, it could be modified by the remote user. The variables and their order listed
in the $_REQUEST array is defined in the PHP variables_order configuration directive.

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: Is it possible to submit a form with a dedicated button?


Answer: Yes, it is possible to submit a form with a dedicated button by using the
document.form.submit() method. The code will be something like this:
<input type=button value=“SUBMIT” onClick=“document.form.submit()”>

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

100+ PHP Interview Questions and Answers To


Prepare 2019
35-45 minutes

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

Posted in Interview Questions,

Core PHP Interview Questions for Beginners


PHP is a recursive acronym for PHP Hypertext Preprocessor. It is a widely used open-source
programming language especially suited for creating dynamic websites and mobile API's.
Below PHP interview questions are helpful for 1 year, 2 years, 5 years experience PHP developer

Facts you Know about PHP


PHP is Originally Known as Personal Home Page
PHP is designed by Rasmus Lerdorf
PHP is written in C and C++
PHP first official launched June 1998
PHP is used for Creating dynamic websites, rest API's, Desktop Applications
PHP Current Version 7.3.4
Download PHP Interview Questions PDF
Below are the list of Best PHP Interview Questions and Answers

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;

public function __construct($name) {


$this->name = $name;
}

public function setLink(Foo $link){


$this->link = $link;
}

public function __destruct() {


echo 'Destroying: '. $this->name;
}
}
?>
PHP supports 9 primitive types
4 scalar types:
• integer
• boolean
• float
• string
3 compound types:
• array
• object
• callable
And 2 special types:
• resource
• NULL

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

NO, multiple inheritance is not supported 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);

// each client should remember their


session id for EXACTLY 1 hour
session_set_cookie_params(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 {
}

# include the class using namesapce


use Modules\Admin\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.

T_PAAMAYIM_NEKUDOTAYIM is scope resolution operator used as :: (double colon) .Basically, it


used to call static methods/variables of a Class.
Example usage:-

$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

$_SESSION['user_info'] = ['user_id' =>1,


'first_name' =>
'Ramesh', 'last_name' =>
'Kumar', 'status' =>
'active'];

// checking session

if (isset($_SESSION['user_info']))
{
echo "logged In";
}

// un setting remove a value from session

unset($_SESSION['user_info']['first_name']);

// destroying complete session

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.

There are 13 types of errors in PHP, We have listed all below


• E_ERROR: A fatal error that causes script termination.
• E_WARNING: Run-time warning that does not cause script termination.
• E_PARSE: Compile time parse error.
• E_NOTICE: Run time notice caused due to error in code.
• E_CORE_ERROR: Fatal errors that occur during PHP initial startup.
(installation)
• E_CORE_WARNING: Warnings that occur during PHP initial startup.
• E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
• E_USER_ERROR: User-generated error message.
• E_USER_WARNING: User-generated warning message.
• E_USER_NOTICE: User-generated notice message.
• E_STRICT: Run-time notices.
• E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
• E_ALL: Catches all errors and warnings.

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

stristr() does the same thing in Case-insensitive manner.

//PHP code to process uploaded file and moving it on server


if($_FILES['photo']['name'])
{
//if no errors...
if(!$_FILES['file']['error'])
{
//now is the time to modify the future file name and validate the
file
$new_file_name = strtolower($_FILES['file']['tmp_name']); //rename
file
if($_FILES['file']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}

//if the file has passed the test


if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.
$new_file_name);
$message = 'File uploaded successfully.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Something got wrong while uploading file: '.
$_FILES['file']['error'];
}
}

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

Code to post JSON Data in a URL using CURL in PHP


$url='https://www.onlineinterviewquestions.com/get_details';
$jsonData='{"name":"phpScots",
"email":"phpscots@onlineinterviewquestions.com"
,'age':36
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_close($ch);

Defining a Constant in PHP


define('CONSTANT_NAME',value);

func_get_args() function is used to get number of arguments passed in a PHP function.


Sample Usage:
function foo() {
return func_get_args();
}
echo foo(1,5,7,3);//output 4;
echo foo(a,b);//output 2;
echo foo();//output 0;

crypt(), Mcrypt(), hash() are used for encryption in PHP

Unlink: Is used to remove a file from server.


usage:unlink(‘path to file’);
Unset: Is used unset a variable.
usage: unset($var);

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

Calculating days between two dates in PHP


<?Php
$date1 = date('Y-m-d');
$date2 = '2015-10-2';
$days = (strtotime($date1)-strtotime($date2))/(60*60*24);
echo $days;
?>

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.

Difference between echo and print in PHP

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 = fopen("php://stderr", "w");

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

Uses and Application Areas of PHP


PHP scripts are used on popular operating systems like Linux, UNIX, Solaris, Windows, MAC OS,
Microsoft and on many other operating systems. It supports many web servers that include Apache and
IIS.
The use of PHP affords web developers the freedom to choose the operating system and the web server.
The following main areas of web development use the PHP programming language.
• Command line scripting In this area of web development, with just the use of PHP parser, the
PHP script is executed with no requirement of any server program or browser. This type of use
of the PHP script is normally employed for simple and easy processing tasks.
• Server-side scripting Server-side scripting is the main area of operation of PHP scripts in PHP.
The following are involved in Server-side scripting:
• Web server – It is a program that executes the files from web pages, from user requests.
• Web browser – It is an application that is used to display the content on WWW (World
Wide Web).
• PHP parser – It is a program that converts the human-readable code into a format that is
easier to understand by the computer.
• Desktop Application Development PHP is also used to create client-side application such as
desktop applications. They are usually characterized by the GUI (Graphic User Interface). The
client-side applications can be developed with knowledge of using the advanced features like
PHP-GTK.

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/

GD is an open source library for creating dynamic images.


• PHP uses GD library to create PNG, JPEG and GIF images.
• It is also used for creating charts and graphics on the fly.
• GD library requires an ANSI C compiler to run.
Sample code to generate an image in PHP
<?php
header("Content-type: image/png");

$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";

PEAR stand for Php Extension and Application Repository.PEAR provides:


• A structured library of code
• maintain a system for distributing code and for managing code packages
• promote a standard coding style
• provide reusable components.

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.

• Session and cookie both are used to store values or data.


• cookie stores data in your browser and a session is stored on the server.
• Session destroys that when browser close and cookie delete when set time expires.

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:
<&lt Order deny, allow Deny from all</&lt

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

Output: Key=Ben, Value=37 Key=Joe, Value=43 Key=Peter, Value=35


Example of ksort():
<?php
$age = array("Peter"=>"37", "Ben"=>"27", "Joe"=>"43");
ksort($age);
?>

Output: Key=Ben, Value=37


Key=Joe, Value=43
Key=Peter, Value=35

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,

then your command line will be:


C:\PHP\php.exe C:\PHP\sample-php-script.php

3. Press the enter key and your script will execute.

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';
}

echo Hello::$greeting; // outputs "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.

date_default_timezone_set() funtion is used to convert/change the time zones in PHP.


Example
date_default_timezone_set('Asia/Kolkata');

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 )

exec, passthru, system, proc_open, eval(),assert(),phpinfo,posix_mkfifo, posix_getlogin,


posix_ttyname are few sensible or exploitable functions in PHP.

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

Overriding and Overloading both are oops concepts.


In Overriding, a method of the parent class is defined in the child or derived class with the same name
and parameters. Overriding comes in inheritance.
An example of Overriding in PHP.
<?php

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

Top PHP Interview Questions & Answers in


2020 - Intellipaat
23-30 minutes
PHP is a broadly used open-source computer programming language that is best suited for building
mobile APIs and dynamic websites. This PHP Interview Questions blog is curated by industry experts
who have compiled a list of the most frequently asked PHP interview questions. Check out the
following PHP interview questions that will help you master this programming language and land a
lucrative job in this field:
Q1. Differentiate between static and dynamic websites.
Q2. What is PHP most used for?
Q3. Is PHP a case-sensitive scripting language?
Q4. What is the meaning of PEAR in PHP?
Q5. How is a PHP script executed?
Q6. What are the types of variables present in PHP?
Q7. What are the variable-naming rules you should follow in PHP?
Q8. What are the main characteristics of a PHP variable?
Q9. What is NULL in PHP?
Q10. How are constants defined in PHP?
The three categories into which this PHP Interview Questions blog is divided include the following:
1. Basic
2. Intermediate
3. Advanced

Go through this comprehensive tutorial to learn PHP:


Learn for free ! Subscribe to our youtube Channel.

Basic Interview Questions


1. Differentiate between static and dynamic websites.
Static Website Dynamic Website
The content cannot be manipulated after the
The content can be changed even at the runtime
script is executed
The content can be changed easily by manipulation
No way to change the content as it is predefined
and reloading

2. What is PHP most used for?


PHP has a plethora of uses for developers. Following are some of the most widely used concepts that
PHP offers:
• With PHP, it becomes very easy to provide restricted access to the required content of the
website.
• It allows users to access individual cookies and set them as per requirement.
• Database manipulation operations, such as addition, deletion, and modification, can be done
easily.
• Form handling, alongside features that involve file handling concepts and email integration, is
used widely.
• The system module allows users to perform a variety of system functions such as open, read,
write, etc.

3. Is PHP a case-sensitive scripting language?


The answer to this is both yes and no. Variables and their declaration in PHP are completely case
sensitive while function names are not.
For example, user-defined functions in PHP can be defined in uppercase but later referred to in
lowercase, and it would still function normally.

4. What is the meaning of PEAR in PHP?


PEAR stands for PHP Extension and Application Repository. It is one of the frameworks and acting
repositories that host all of the reusable PHP components. Alongside containing some of the PHP
libraries, it also provides you with a simple interface to automatically install packages.

5. How is a PHP script executed?


PHP scripts can be easily executed from the command-line interface (CLI). The syntax is as follows:
php filename.php
Here, filename refers to the file that contains scripts. The extension .php is needed alongside the
filename.

6. What are the types of variables present in PHP?


There are eight primary data types in PHP as shown below:
• Array: A named and ordered collection of data
• Boolean: A logical value (True or False)
• Double: Floating point numbers such as 5.1525
• Integer: Whole numbers without a floating point
• Object: An instance of classes, containing data and functions
• NULL: A special data type, supporting only the NULL data
• Resource: Special variables that hold references to external resources
• String: A sequence of characters such as, “Hello learners!”

7. What are the variable-naming rules you should follow in PHP?


There are two main rules that you have to follow when naming a variable in PHP. They are as follows:
• Variables can only begin with letters or underscores.
• Special characters such as +, %, -, &, etc. cannot be used.

8. What are the main characteristics of a PHP variable?


Following are some of the most important aspects of the usage of variables in PHP:
• Variables can be declared before the value assignment.
• A variable value assignment happens using the ‘=’ operator.
• Every variable in PHP is denoted with a $ (dollar) sign.
• The value of a variable depends on its latest assigned value.
• PHP variables are not intrinsic. There is no explicit declaration.

9. What is NULL in PHP?


NULL is a special data type in PHP used to denote the presence of only one value, NULL. You cannot
assign any other value to it.
NULL is not case sensitive in PHP and can be declared in two ways as shown below:
$var = NULL:

Or

$var = null;

Both of the above syntaxes work fine in PHP.

10. How are constants defined in PHP?


Constants can be defined easily in PHP by making use of the define() function. This function is used to
define and pull out the values of the constants easily.
Constants, as the name suggests, cannot be changed after definition. They do not require the PHP
syntax of starting with the conventional $ sign.

11. What is the use of the constant() function in PHP?


The constant() function is used to retrieve the values predefined in a constant variable. It is used
especially when you do not know the name of the variable.
12. What are the various constants predefined in PHP?
PHP consists of many constants, and following are some of the widely used ones:
• _METHOD_: Represents the class name
• _CLASS_: Returns the class name
• _FUNCTION_: Denotes the function name
• _LINE_: Denotes the working line number
• _FILE_: Represents the path and the file name

13. Differentiate between variables and constants in PHP.


Variable Constant
Variables can have changed paths Constants cannot be changed
The default scope is the current access Constants can be accessed throughout without any scoping
scope rules
The $ assignment is used for definition Constants are defined using the define() function
Compulsory usage of the $ sign at the
No need for the $ sign for constants
start

14. What does the phrase ‘PHP escape’ mean?


PHP escape is a mechanism that is used to tell the PHP parser that certain code elements are different
from PHP code. This provides the basic means to differentiate a piece of PHP code from the other
aspects of the program.

15. Differentiate between PHP4 and PHP5.


PHP4 PHP5
No support for static methods Allows the usage of static methods
Abstract classes cannot be declared Abstract classes can be declared
The method of call-by-value is used The method of call-by-reference is used
Constructors can have class names Constructors have separate names

16. How are two objects compared in PHP?


PHP provides you with the ‘==’ operator, which is used to compare two objects at a time. This is used
to check if there is a common presence of attributes and values between the objects in comparison.
The ‘===’ operator is also used to compare if both objects in consideration are referencing to the same
class.

17. What is the meaning of break and continue statements in PHP?


Break: This statement is used in a looping construct to terminate the execution of the iteration and to
immediately execute the next snippet of code outside the block of the looping construct.
Continue: This statement is used to skip the current iteration of the loop and continue to execute the
next iteration until the looping construct is exited.
18. What are some of the popular frameworks in PHP?
There are many frameworks in PHP that are known for their usage. Following are some of them:
• CodeIgniter
• CakePHP
• Laravel
• Zend
• Phalcon
• Yii 2

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.

20. How does JavaScript interact with PHP?


JavaScript is a client-side programming language, while PHP is a server-side scripting language. PHP
has the ability to generate JavaScript variables, and this can be executed easily in the browser, thereby
making it possible to pass variables to PHP using a simple URL.

Intermediate Interview Questions


21. Does PHP interact with HTML?
Yes, HTML and PHP interaction is the core of what makes PHP what it is. PHP scripts have the ability
to generate HTML mode and move around information very easily.
PHP is a server-side scripting language, while HTML is a client-side language. This interaction helps
bridge the gaps and use the best of both languages.

22. What are the types of arrays supported by PHP?


There are three main types of arrays that are used in PHP.
• Indexed arrays: These are arrays that contain numerical data. Data access and storage are
linear.
• Associative arrays: There are arrays that contain strings for indexing elements.
• Multidimensional arrays: These are arrays that contain more than one index and dimension.

23. How does the ‘foreach’ loop work in PHP?


The foreach statement is a looping construct used in PHP to iterate and loop through the array data
type. The working of foreach is simple; with every single pass of the value, elements get assigned a
value and pointers are incremented. This process is repeated until the end of the array.
The following is the syntax for using the foreach statement in PHP:
foreach(array)
{
Code inside the loop;
}

24. Differentiate between require() and require_once() functions.


require() require_once()
The inclusion and evaluation of files Includes files if they are not included before
Preferred for files with fewer functions Preferred when there are a lot of functions

25. What are the data types present in PHP?


PHP supports three types of data handling, and they are as shown in the following table:

Scalar Data Types Compound Data Types Special Data Types


• Boolean
• Integer • Array • NULL
• Float • Object • Resource
• String

26. How can a text be printed using PHP?


A text can be output onto the working environment using the following methods:
• Echo
• Print
The following code denotes the usage of both:
<?php echo "Using echo";
print "Using print"; ?>

27. Is it possible to set infinite execution time in PHP?


Yes, it is possible to have an infinite execution time in PHP for a script by adding the set_time_limit(0)
function to the beginning of a script.
This can also be executed in the php.ini file if not at the beginning of the script.

28. What is the use of constructors and destructors in PHP?


Constructors are used in PHP as they allow you to pass parameters when creating a new object easily.
This is used to initialize the variables for the particular object in consideration.
Destructors are methods used to destroy an object. Both of these are special methods provided in PHP
for you to perform complex procedures using a single step.
29. What are some of the top Content Management Systems (CMS) used in PHP?
There are many CMS that are used in PHP. The popular ones are as mentioned below:
• WordPress
• Joomla
• Magneto
• Drupal

30. How are comments used in PHP?


There are two ways to use comments in PHP. They are single-line comments and multi-line comments.
Single-line comments can be used using the conventional ‘#’ sign.
Example:
<?php
# This is a comment
echo "Single-line comment";
?>

Multi-line comments can be denoted using ‘/* */’ in PHP.


Example:
<?php
/*
This is
a
Multi-line
Comment
In PHP;
*/

echo "Multi-line comment";

?>

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.

32. Differentiate between an indexed array and an associative array.


Indexed arrays have elements that contain a numerical index value.
Example: $color=array("red","green","blue");

Here, red is at index 0, green at 1, and blue at 2.


Associative arrays, on the other hand, hold elements with string indices as shown below:
Example: $salary=array("Jacob"=>"20000","John"=>"44000","Josh"=>"60000");
33. What is the difference between ASP.NET and PHP?
ASP.NET PHP
A programming framework A scripting language
Compiled and executed Interpreted mode of execution
Designed for use on Windows Platform independent

34. What are sessions and cookies in PHP?


Sessions are global variables that are stored on the server in the architecture. Every single session is
tagged with a unique server ID that is later used to work with the storage and retrieval of values.
Cookies are entities used to identify unique users in the architecture. It is a small file that the server
plants into the client system. This is done to get useful information from the client for the development
of various aspects of the server.

35. Is typecasting supported in PHP?


Yes, typecasting is supported by PHP and can be done very easily. Following are the types that can be
cast in PHP:
• (int), (integer): Cast to integer
• (bool), (boolean): Cast to boolean
• (float), (double), (real): Cast to float
• (string): Cast to string
• (array): Cast to array
• (object): Cast to object

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.

37. Does PHP support variable length argument functions?


Yes, PHP supports the use of variable length argument functions. This simply means that you can pass
any number of arguments to a function. The syntax simply involves using three dots before the
argument name as shown in the following example:
<?php

function add(...$num) {

$sum = 0;

foreach ($num as $n) {

$sum += $n;

}
return $sum;

echo add(5, 6, 7, 8);

?>

Output: 26

38. What is the use of session_start() and session_destroy() functions?


In PHP, the session_start() function is used to start a new session. However, it can also resume an
existing session if it is stopped. In this case, the return will be the current session if resumed.
Syntax:
session_start();

The session_destroy() function is mostly used to destroy all of the session variables as shown below:
<?php

session_start();

session_destroy();

?>

39. How can you open a file in PHP?


PHP supports file operations by providing users with a plethora of file-related functions.
In the case of opening a file, the fopen() function is used. This function can open a file or a URL as per
requirement. It takes two arguments: $filename and $mode.
Syntax:
resource fopen ( string $filename , string $mode [, bool $use_include_path = false
[, resource $context ]] )

40. What are the different types of PHP errors?


There are three main types of errors in PHP. They are as follows:
• Notice: A notice is a non-critical error that is not displayed to the user.
• Warning: A warning is an error that is displayed to the user while the script is running.
• Fatal error: This is the most critical type of error. A fatal error will cause immediate
termination of the script.
Advanced Interview Questions
41. How can you get the IP address of a client in PHP?
The IP address of a client, who is connected, can be obtained easily in PHP by making use of the
following syntax:
$_SERVER["REMOTE_ADDR"];

42. What is the use of $message and $$message in PHP?


Both $message and $$message are variables in PHP. The difference lies in the name. While $message
is a variable with a fixed name, $$message is a variable with a name that is actually stored in
$message.
Consider the following example:
If $message consists of ‘var’, then $$message is nothing but ‘$var’.

43 Differentiate between GET and POST methods in PHP.


GET Method POST Method
The GET method can only send a maximum of 1024
There is no restriction on the data size
characters simultaneously
GET does not support sending binary data POST supports binary data as well as ASCII
QUERY_STRING env variable is used to access the The HTTP protocol and the header are used to
data that is sent push the data
The $_GET associative array is used to access the The $_POST associative array is used to access
sent information the sent information here

44. What is the use of lambda functions in PHP?


Being an anonymous function, the lambda function is used to first store data into a variable and then to
pass it as arguments for the usage in other methods or functions.
Consider the following example:
$input = array(2, 5, 10);
$output = array_filter($input, function ($x) { return $x > 2; });

The lambda function definition here:


function ($x) { return $x > 2; });

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.

46. What is the meaning of type hinting in PHP?


Type hinting is used in PHP when there is a requirement to explicitly define the data type of an
argument when passing it through a function.
When this function is first called, PHP will run a quick check to analyze the presence of all the data
types that are specified. If it is different, then the runtime will stop as an exception will be raised.

47. How is a URL connected to PHP?


Any URL can be connected to PHP easily by making use of the library called cURL. This comes as a
default library with the standard installation of PHP.
The term ‘cURL’ stands for client-side URL, allowing users to connect to a URL and pick up
information from that page to display.

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.

49. How does string concatenation work in PHP?


String concatenation is done easily in PHP by making use of the dot(.) operator. Consider the following
example:
<?php $string1="Welcome"; $string2="to Intellipaat"; echo $string1 . " " .
$string2; ?>

Output: Welcome to Intellipaat

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.

51. Compare PHP and Java.


Criteria PHP Java
Deployment area Server-side scripting General-purpose programming
Language type Dynamically typed Statically typed
Providing a rich set of APIs No Yes

52. How can we encrypt a password using PHP?


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:

53. Explain how to submit a form without a submit button.


A form can be posted or submitted without the button in the following ways:
• On the OnClick event of a label in the form, a JavaScript function can be called to submit the
form.
Example:
document.form_name.submit()

• Using a Hyperlink: On clicking the link, a JavaScript function can be called.


Example:
• A form can be submitted in the following ways as well without using the submit button:
• Submitting a form by clicking a link
• Submitting a form by selecting an option from the drop-down box with the invocation of
an onChange event
• Using JavaScript:
document.form.submit();

• Using header(“location:page.php”);

54. How can we increase the execution time of a PHP script?


• The default time allowed for a PHP script to execute is 30 seconds mentioned in the php.ini
file. The function used is set_time_limit(int sec). If the value passed is ‘0’, it takes unlimited
time. It should be noted that if the default timer is set to 30 seconds and 20 seconds is specified
in set_time_limit(), the script will run for 45 seconds.
• This time can be increased by modifying max_execution_time in seconds. The time must be
changed keeping the environment of the server. This is because modifying the execution time
will affect all the sites hosted by the server.
• The script execution time can be increased by:
• Using the sleep() function in the PHP script
• Using the set_time_limit() function
The default limit is 30 seconds. The time limit can be set to zero to impose no time limit
To know more about PHP, enroll in our Online PHP Training Course now!

55. What is Zend Engine?


Zend Engine is used internally by PHP as a compiler and runtime engine. PHP Scripts are loaded into
memory and compiled into Zend OPCodes.
These OPCodes are executed and the HTML generated is sent to the client.
The Zend Engine provides memory and resource management and other standard services for the PHP
language. Its performance, reliability, and extensibility have played a significant role in PHP’s
increasing popularity.

56. What library is used for PDF in PHP?


The PDF functions in PHP can create PDF files using PDFlib version 6. PDFlib offers an object-
oriented API for PHP5 in addition to the function-oriented API for PHP4.
There is also the » Panda module.
FPDF is a PHP class, which allows generating PDF files with pure PHP (without using PDFlib). F from
FPDF stands for Free: we may use it for any requirement and modify it to suit our needs. FPDF
requires no extension (except zlib to activate compression and GD for GIF support) and works with
PHP4 and PHP5.
57. What are the new features introduced in PHP7?
• Zend Engine 3 performance improvements and 64-bit integer support on Windows
• Uniform variable syntax
• AST-based compilation process
• Added Closure::call()
• Bitwise shift consistency across platforms
• (Null coalesce) operator
• Unicode codepoint escape syntax
• Return type declarations
• Scalar type (integer, float, string, and Boolean) declarations

58. What is htaccess? Why do we use it and where?


The .htaccess files are configuration files of Apache Server that provide a way to make configuration
changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a
particular document directory; the directives apply to that directory and all subdirectories thereof.
These .htaccess files are used to change the functionality and features of the Apache web server.
For instance:
• The .htaccess file is used for URL rewrite.
• It is used to make the site password-protected.
• It can restrict some IP addresses so that on these restricted IP addresses, the site will not open.

59. What are magic methods?


Magic methods are member functions that are available to all the instances of a class. Magic methods
always start with ‘__’, for example, __construct(). All magic methods need to be declared as public.
To use a method, it should be defined within the class or the program scope. Various magic methods
used in PHP5 are:
• __construct()
• __destruct()
• __set()
• __get()
• __call()
• __toString()
• __sleep()
• __wakeup()
• __isset()
• __unset()
• __autoload()
• __clone()
60. What is meant by PEAR in PHP?
PEAR is an acronym for PHP Extension and Application Repository. The purpose of PEAR is to
provide:
• A structured library of open-sourced code for PHP users
• A system for code distribution and package maintenance
• A standard style for writing code in PHP
• PHP Foundation Classes (PFC)
• PHP Extension Community Library (PECL)
• A website, mailing lists, and download mirrors to support the PHP/PEAR community

61. Explain soundex() and metaphone().


The soundex() function calculates the soundex key of a string. A soundex key is a 4-character long
alphanumeric string that represents the English pronunciation of a word. The soundex() function can be
used for spelling applications.
<?php
$str= “hello”;
Echo soundex($str);
?>

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

62. What is Smarty?


Smarty is a template engine written in PHP. Typically, these templates will include variables—like
{$variable}—and a range of logical and loop operators to allow adaptability within the templates.
63. What is Memcache?
Memcache is a technology that caches objects in memory such that a web application can get to them
really fast. It is used by sites, such as Digg, Facebook, and NowPublic, and is widely recognized as an
essential ingredient in scaling any LAMP.

64. How can we execute a PHP script using a command line?


We just have to run the PHP CLI (Command-line Interface) program and provide the PHP script file
name as the command-line argument, for example, php myScript.php, assuming php as the command
to invoke the CLI program.
We have to keep in mind that if our PHP script is written for the Web CGI interface, it may not execute
properly in the command-line environment.
techbeamers.com

PHP Interview Questions and Answers for 1+


Yr. Experienced
userMeenakshi Agarwal
12-15 minutes
PHP developers are still in high demand for web application development. And there are more and
more high-end enterprise level websites getting created using PHP. Hence, we are adding 15 more PHP
interview questions and answers for the experienced web developers. In our last post, you might have
seen that we’d published the 30 PHP questions for beginners.
All of you might be aware of the fact that Web development market is growing like anything. And
especially the web programmers are the primary beneficiary of this growth. Hence, most of them tend
to learn technologies like PHP, HTML/CSS, JavaScript, AngularJS, and NodeJS. To turn them into a
better programmer, we’d started this series of web developer interview questions.
Starting with our first post on the 50 most essential AngularJS interview questions, we later had
taken up other web development topics like NodeJS, CSS/HTML, and now PHP. Our team has studied
the latest trends and the patterns of the questions asked in the interviews. All of this helps us serve you
better and achieve our goal of making you succeed in job interviews.

PHP Interview Questions and Answers for Experienced

PHP Interview Questions and Answers


Q-1. What is the difference between unlink and unset function in PHP?

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&#91;'element'&#93;); //remove a single element in an array
unset($val1, $val2, $val3); // remove multiple variables
?>

Q-2. Explain PHP Traits?

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

Let say there exists a class Welcome.


class Welcome
{
public function welcome()
{
echo "Welcome","\n"
}
}

To include its functionality in Message class, we can extend it as.


class Message extends Welcome
{
}

$obj = new Message;


$obj->welcome();

Let’s say there exists another class named Goodmorning.


class Goodmorning
{
public function goodmorning()
{
echo "Good Morning","\n";
}
}

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

It produces the following output.


I said Welcome
Welcome
and you said Good Morning
Good Morning

Q-3. How can we display the correct URL of the current webpage?

Answer.
<?php
echo $_SERVER['PHP_SELF'];
?>

Q-4. Why we use extract() in PHP?

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)

Let’s see an example.


<?php
$varArray = array("course1" => "PHP", "course2" => "JAVA","course3" => "HTML");
extract($varArray);
echo "$course1, $course2, $course3";
?>

Q-5. What is the default timeout for any PHP session?

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

Q-8. What is PDO in PHP?

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

Returns an array that contains May, June, July.


The explode() function splits the String using a String delimiter.
For Example.
explode(and May and June and July);

Also returns an array that contains May, June, July.


Q-12. What is the use of ini_set() in PHP?

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

echo ini_get('mysql.connect_timeout'); // output 100

Q-13. How to change the file permissions in PHP?

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

Q-14. What is the use of urlencode() and urldecode() in PHP?

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 )

It is a convenient way for passing variables to the next page.


The use of urldecode() function is to decode the encoded string. It decodes any %## encoding in the
given string (inserted by urlencode.)
Following is the Syntax.
urldecode (string $str )
Q-15. Which PHP Extension helps to debug the code?

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.

Summary – PHP Interview Questions and Answers for


Experienced
We wish the above PHP interview questions and answers could help step up performance during job
interviews. And you could grow in your professional career as a web developer.
If you have anything to share with us or like to suggest a topic of your choice, then do let us know via
comments.
Also if you liked this post, then do connect us on Facebook/Twitter.
Happy Learning,
TechBeamers
placement.freshersworld.com

PHP Interview Questions


7-8 minutes
1. Who is the father of PHP ?
Rasmus Lerdorf is known as the father of PHP.

2. What is the difference between $name and $$name?


$name is variable where as $$name is reference variable like $name=sonia and $$name=singh so
$sonia value is singh.

3. What are the method available in form submitting?


GET and POST

4.How can we get the browser properties using PHP?


<?php
echo $_SERVER[‘HTTP_USER_AGENT’].”\n\n”;
$browser=get_browser(null,true);
print_r($browser);
?>

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

10. What is the functionality of the function strstr and stristr?


strstr() returns part of a given string from the first occurrence of a given substring to the end of the
string.
For example:strstr("user@example.com","@") will return "@example.com".
stristr() is idential to strstr() except that it is case insensitive.
11. What are encryption functions in PHP?

CRYPT(), MD5()

12. How to store the uploaded file to the final location?


move_uploaded_file( string filename, string destination)

13. Explain mysql_error().


The mysql_error() message will tell us what was wrong with our query, similar to the message we
would receive at the MySQL console.

14. What is Constructors and Destructors?


CONSTRUCTOR : PHP allows developers to declare constructor methods for classes. Classes which
have a constructor method call this method on each newly-created object, so it is suitable for any
initialization that the object may need before it is used.
DESTRUCTORS : PHP 5 introduces a destructor concept similar to that of other object-oriented
languages, such as C++. The destructor method will be called as soon as all references to a particular
object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.

15. Explain the visibility of the property or method.


The visibility of a property or method must be defined by prefixing the declaration with the keywords
public, protected or private.
Class members declared public can be accessed everywhere.
Members declared protected can be accessed only within the class itself and by inherited and parent
classes.
Members declared as private may only be accessed by the class that defines the member.

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

17. What are the differences between require and include?


Both include and require used to include a file but when included file not found
Include send Warning where as Require send Fatal Error

18. What is use of header() function in php ?


The header() function sends a raw HTTP header to a client.We can use herder()
function for redirection of pages. It is important to notice that header() must
be called before any actual output is seen.
19. List out the predefined classes in PHP?
Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter

20. What type of inheritance that PHP supports?


In PHP an extended class is always dependent on a single base class,that is, multiple inheritance is not
supported. Classes are extended using the keyword 'extends'.

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

22. What is the difference between explode and split?


Split function splits string into array by regular expression. Explode splits a string into array by string.
For Example:explode(" and", "India and Pakistan and Srilanka");
split(" :", "India : Pakistan : Srilanka");
Both of these functions will return an array that contains India, Pakistan, and Srilanka.

23. How do you define a constant?


Constants in PHP are defined using define() directive, like define("MYCONSTANT", 100);

24. How do you pass a variable by value in PHP?


Just like in C++, put an ampersand in front of it, like $a = &$b;

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

26. How do you call a constructor for a parent class?


parent::constructor($value)

27. What’s the special meaning of __sleep and __wakeup?


__sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.

28. What is the difference between PHP and JavaScript?


javascript is a client side scripting language, so javascript can make popups and other things happens
on someone’s PC. While PHP is server side scripting language so it does every stuff with the server.

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.

31. What are default session time and path?


default session time in PHP is 1440 seconds or 24 minutes
Default session save path id temporary folder /tmp

32. for image work which library?


we will need to compile PHP with the GD library of image functions for this to work. GD and PHP
may also require other libraries, depending on which image formats you want to work with.

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

Top 101+ PHP Interview Questions and Answers


23-29 minutes
Here are the list of most frequently asked PHP Interview Questions and Answers in technical
interviews. These questions and answers are suitable for both freshers and experienced professionals at
any level. The questions are for intermediate to somewhat advanced PHP professionals, but even if you
are just a beginner or fresher you should be able to understand the answers and explanations here we
give.
Q1) What is PHP?
PHP is a server side scripting language. It requires a web server to perform execution like Apache, IIS
etc. It helps to create a dynamic web applications. PHP is a market leader in-terms of usage. It holds
more than 82% of total web market share as of 2015.
Q2) Who is the father of PHP?
Rasmus Lerdorf. He created PHP in the year of 1994.
Q3) Acronym of PHP?
Now PHP stands for “PHP : Hypertext Preprocessor“. Before PHP 4 it was called as “Personal Home
Page Tools”.
Q4) Explain the difference between static and dynamic websites?
Static Websites : A webpage or website which was developed by using HTML alone.
Dynamic Websites : A webpage or website which was developed by using any dynamic languages like
PHP, ASP.NET, JSP etc
Q5) What is the name of scripting engine in PHP?
ZEND Engine 2 is the name of the scripting engine that powers PHP.
Q6) What are the methods of form submitting in PHP?
We can use GET (or) POST for form submission in PHP.
Q7) What is a session?
A session is a logical object enabling us to preserve temporary data across multiple PHP pages. A PHP
session is no different from a normal session. It can be used to store information on the server for future
use. However this storage is temporary and is flushed out when the site is closed.
Q8) What is the method to register a variable into a session?
< ?php session_register($name_your_session_here); ?>
Q9) What are the encryption functions in PHP?
md5() – Calculate the md5 hash of a string
sha1() – Calculate the sha1 hash of a string
hash() – Generate a hash value
crypt() – One-way string hashing
Q10)What are the different types of errors in PHP?
There are 3 types of errors in PHP.
Notices : These are the non-critical errors. These errors are not displayed to the users.
Warnings : These are more serious errors but they do not result in script termination. By default, these
errors are displayed to the user.
Fatal Errors : These are the most critical errors. These errors may be a cause of immediate termination
of script.
Q11) What is the difference between $besant and $$besant?
$besant stores variable data while $$besant is used to store variable of variables.
$besant stores fixed data whereas the data stored in $$besant may be changed dynamically.
Q12) How do you connect MySQL database with PHP?
There are two methods to connect MySQL database with PHP. Procedural and Object Oriented style.
Q13) Difference echo() and print()?
Echo can output one or more string but print can only output one string and always returns 1.
Echo is faster than print because it does not return any value.
Q14) Differentiate between require and include?
Require and include both are used to include a file, but if file is not found include sends warning
whereas require sends Fatal error.
Q15) What is the use of count() function in PHP?
count() function is used to count total elements in the array, or something an object.
Q16) What is the difference between session and cookie?
The main difference between session and cookies is that cookies are stored on the user’s computer
while sessions are stored on the server side.
Cookies can’t hold multiple variables on the other hand Session can hold multiple variables.
You can manually set an expiry for a cookie, while session only remains active as long as browser is
open.
Q17) How can you retrieve a cookie value?
echo $_COOKIE [“cookie_name”];
Q18) What is the use of header() function in PHP?
The header() function is used to send a raw HTTP header to a client. It must be called before sending
the actual output. For example, you can’t print any HTML element before using this header function.
Q19) What is the array in PHP?
Array is used to store multiple values in single name. In PHP, it orders in keys and values pairs. It is not
a datatype dependent in PHP.
Q20) How can you submit a form without a submit button?
Possible only by using JavaScript. You can use JavaScript submit() function to submit the form without
explicitly clicking any submit button.
Q21) Explain the importance of the function htmlentities
The htmlentities() function converts characters to HTML entities.
Q22) What is MIME?
MIME – Multi-purpose Internet Mail Extensions.
MIME types represents a standard way of classifying file types over Internet.
Web servers and browsers have a list of MIME types, which facilitates files transfer of the same type in
the same way, irrespective of operating system they are working in.
A MIME type has two parts: a type and a subtype. They are separated by a slash (/).
MIME type for Microsoft Word files is application and the subtype is msword, i.e. application/msword.
Q23) How can we increase the execution time of a php script?
By default the PHP script takes 30secs to execute. This time is set in the php.ini file. This time can be
increased by modifying the max_execution_time in seconds. The time must be changed keeping the
environment of the server. This is because modifying the execution time will affect all the sites hosted
by the server.
Q24) What is Type juggle in php?
Type Juggling means dealing with a variable type. In PHP a variables type is determined by the context
in which it is used. If an integer value is assigned to a variable, it becomes an integer.
E.g. $var3= $var1 + $var2
Here, if $var1 is an integer. $var2 and $var3 will also be treated as integers.
Q25) What is the difference between mysql_fetch_object() and mysql_fetch_array()?
mysql_fetch_object() returns the result from the database as objects while mysql_fetch_array() returns
result as an array. This will allow access to the data by the field names. E.g. using mysql_fetch_object()
field can be accessed as $result->fieldname and using mysql_fetch_array() field can be accessed as
$result->[‘fieldname’]
Q26) What is the difference between the functions unlink and unset?
The function unlink() is to remove a file, where as unset() is used for destroying a variable that was
declared earlier.
unset() empties a variable or contents of file.
Q27) What is Joomla in PHP?
Joomla is an open source content management system. Joomla allows the user to manage the content of
the web pages with ease.
Q28) What is the difference between preg_split() and explode()?
preg_split — Split string by a regular expression
< ?php // split the phrase by any number of commas or space characters, // which include ” “, \r, \t, \n
and \f $keywords = preg_split(“/[\s,]+/”, “hypertext language, programming”); print_r($keywords); ?>
explode — Split a string by string
< ?php // Example 1 $pizza = “piece1 piece2 piece3 piece4 piece5 piece6″; $pieces = explode(” “,
$pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2 ?>
Q29) How to upload files using PHP?
– Select a file from the form using <input type=”file”>
– Specify the path into which the file is to be stored.
– Insert the following code in php script to upload the file.
move_uploaded_file($_FILES[“file”][“tmp_name”], “myfolder/” . $_FILES[“file”][“name”]);
Q30) Describe functions strstr() and stristr()?
Both the functions are used to find the first occurrence of a string. Parameters includes: input String,
string whose occurrence needs to be found, TRUE or FALSE (If TRUE, the functions return the string
before the first occurrence.)
stristr() is similar to strstr(). However, it is case-insensitive.
Q31) Explain the purpose of output buffering in PHP
Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes
through your script. With output buffering, your HTML is stored in a variable and sent to the browser
as one piece at the end of your script.
Advantages of output buffering for Web developers
– Turning on output buffering alone decreases the amount of time it takes to download and render our
HTML because it’s not being sent to the browser in pieces as PHP processes the HTML.
– All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one
variable.
– If you’ve ever encountered the message “Warning: Cannot modify header information – headers
already sent by (output)” while setting cookies, you’ll be happy to know that output buffering is your
answer.
Q32) How can we know the number of days between two given dates using PHP?
Object oriented style:
$datetime1 = new DateTime(‘2009-10-11’);
$datetime2 = new DateTime(‘2009-10-13’);
$interval = $datetime1->diff($datetime2);
echo $interval->format(‘%R%a days’);
Procedural style:
$datetime1 = date_create(‘2009-10-11’);
$datetime2 = date_create(‘2009-10-13’);
$interval = date_diff($datetime1, $datetime2);
echo $interval->format(‘%R%a days’);
Q33) What is the difference between PHP and JavaScript?
While JS is used for client side scripting (except in node.js) and PHP is used for server side scripting.
Simply, JavaScript codes are executed by your web browser, like the catchy animations or simple
calculations . Your browser does all the processing. While PHP runs on the server, where your webpage
is stored. The server computer does all PHP processing and it sends the result to your browser.
Q34) What does ODBC do in context with PHP?
PHP supports many databases like dBase, Microsft SQL Server, Oracle, etc. But, it also supports
databases like filePro, FrontBase and InterBase with ODBC connectivity. ODBC stands for Open
Database connectivity, which is a standard that allows user to communicate with other databases like
Access and IBM DB2.
Q35) What is difference between require_once(), require(), include()?
Difference between require() and require_once(): require() includes and evaluates a specific file, while
require_once() does that only if it has not been included before (on the same page).
So, require_once() is recommended to use when you want to include a file where you have a lot of
functions for example. This way you make sure you don’t include the file more times and you will not
get the “function re-declared” error.
Difference between require() and include() is that require() produces a FATAL ERROR if the file you
want to include is not found, while include() only produces a WARNING.
There is also include_once() which is the same as include(), but the difference between them is the
same as the difference between require() and require_once().
Q36) PHP being an open source is there any support available to it?
PHP is an open source language, and it is been said that it has very less support online and offline. But,
PHP is all together a different language that is being developed by group of programmers, who writes
the code. There is lots of available support for PHP, which mostly comes from developers and PHP
users.
Q37) How php concatenation works?
Two strings can be joined together by the use of a process called as concatenation. A dot (.) operator is
used for this purpose. Example is as follows:
$string1 = “Hello”;
$string2 = ” World!”;
$stringall = $string1.$string2;
echo $stringall;
Q38) What is the use of super-global arrays in PHP?
Super global arrays are the built in arrays that can be used anywhere. They are also called as auto-
global as they can be used inside a function as well. The arrays with the longs names such as
$HTTP_SERVER_VARS, must be made global before they can be used in an array. This
$HTTP_SERVER_VARS check your php.ini setting for long arrays.
Q39) What is the use of $_SERVER and $_ENV?
$_SERVER and $_ENV arrays contain different information. The information depends on the server
and operating system being used. Most of the information can be seen of an array for a particular server
and operating system. The syntax is as follows:
foreach($_SERVER as $key =>$value) { echo “Key=$key, Value=$value\n”; }
Q40) Write a statement to show the joining of multiple comparisons in PHP?
PHP allows multiple comparisons to be grouped together to determine the condition of the statement. It
can be done by using the following syntax:
comparison1 and|or|xor comparison2 and|or|xor comparison3 and|or|xor.
The operators that are used with comparisons are as follows:
1. and: result in positive when both comparisons are true.
2. or: result in positive when one of the comparisons or both of the comparisons are true.
3. xor: result in positive when one of the comparisons is true but not both of the comparisons.
Example:
$resCity == “Reno” or $resState == “NV” and $name == “Sally”
Q41) Differences between GET and POST methods ?
We can send 1024 bytes using GET method but POST method can transfer large amount of data and
POST is the secure method than GET method .
Q42) How to declare an array in php?
$arr = array(‘apple’, ‘grape’, ‘lemon’);
Q43) What is use of in_array() function in php ?
in_array() used to checks if a value exists in an array
Q44) How to set cookies in PHP and Retrieve a Cookie Value? Setting Cookie in PHP
setcookie(“cookie_name”, “cookie_value”, time()+(60*60*24*5));
Retriving Cookie in PHP
echo $_COOKIE[“cookie_name”];
Q45) 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’];
Q46) what types of loops exist in php?
for, while, do while and foreach
Q47) How we can retrieve the data in the result set of MySQL using PHP?
mysql_fetch_row()
mysql_fetch_array()
mysql_fetch_object()
mysql_fetch_assoc()
Q48) What is the use of explode() function ?
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.
Q49) What is the use of mysql_real_escape_string() function?
It is used to escapes special characters in a string for use in an SQL statement
Q50) 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.
Q51) How to redirect a page in php?
The following code can be used for it,
header(“Location:page_to_redirect.php”); exit();
Q52) How stop the execution of a php script ?
exit() function is used to stop the execution of a page
Q53) How to find the length of a string?
strlen() function used to find the length of a string
Q54) 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.
Q55) What is the use of isset() in php?
This function is used to determine if a variable is set and is not NULL
Q56) Purpose of method attribute in 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.
Q57) Define Object-Oriented Methodology?
Object orientation is a software/Web development 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
Q58) How do you define a constant?
Using define() directive, like define(“CONSTANTNAME”,150)
Q59) 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 :
mail($to,$subject,$message,$headers);
Q60) 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.
Q61) How to delete a file from the system
unlink() – deletes the given file from the file system.
Q62) How to get the value of current session id?
session_id() – function returns the session id for the current session.
Q63) What is sql injection?
SQL injection is a malicious code injection technique. It exploiting SQL vulnerabilities in Web
applications
Q64) Is multiple inheritance supported in PHP?
PHP includes only single inheritance, it means that a class can be extended from only one single class
using the keyword ‘extended’.
Q65) What is the meaning of a final class and a final method?
‘final’ is introduced in PHP5. Final class means that this class cannot be extended and a final method
cannot be overrided.
Q66) How comparison of objects is done in PHP5?
We use the operator ‘==’ to test is two object are instanced from the same class and have same
attributes and equal values. We can test if two object are refering to the same instance of the same class
by the use of the identity operator ‘===’.
Q67) What is needed to be able to use image function?
GD library is needed to be able execute image functions.
Q68) What is the use of the function ‘imagetypes()’?
imagetypes() gives the image format and types supported by the current version of GD-PHP.
Q69) What are the functions to be used to get the image’s properties (size, width and height)?
The functions are getimagesize() for size, imagesx() for width and imagesy() for height.
Q70) 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.
Q71) 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.
Q72) What is the function file_get_contents() usefull for?
file_get_contents() lets reading a file and storing it in a string variable. (Shortcut of fopen + fread +
fclose)
Q73) How is it possible to know the number of rows returned in result set?
The function mysql_num_rows() returns the number of rows in a result set.
Q74) What is the static variable in function useful for?
A static variable is defined within a function only the first time and its value can be modified during
function calls.
Q75) What is the most convenient hashing method to be used to hash passwords?
It is preferable to use crypt() which natively supports several hashing algorithms or the function hash()
which supports more variants than crypt() rather than using the common hashing algorithms such as
md5, sha1 or sha256 because they are conceived to be fast. hence, hashing passwords with these
algorithms can vulnerability.
Q76) How is the ternary conditional operator used in PHP?
It is composed of three expressions: a condition, and two operands describing what instruction should
be performed when the specified condition is true or false as follows:
Any_Question_Returns_Boolean ? What_if_True : What_if_False;
Q77) What does accessing a class via :: means?
:: is used to access static methods that do not require object initialization. (Scope Resolution Operator)
Q78) Are Parent constructors called implicitly inside a class constructor?
No, a parent constructor have to be called explicitly as follows:
parent::constructor($value)
Q79) What’s the difference between __sleep and __wakeup?
__sleep returns the array of all the variables that need to be saved, while __wakeup retrieves them.
Q80) 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.
Q81) When sessions ends?
Sessions automatically ends when the PHP script finishs executing, but can be manually ended using
the session_write_close().
Q82) What is the difference between session_unregister() and session_unset()?
session_unregister() unregisters the global variable named name from the current session.
The session_unset() function frees all session variables currently registered.
Q83) What does $_SERVER means?
$_SERVER is an array including information created by the web server such as paths, headers, and
script locations.
Q84) What does $_FILES means?
$_FILES is an associative array composed of items sent to the current script via the HTTP POST
method.
Q85) 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.
Q86) What does the scope of variables means?
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.
Q87) 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).
Q88) 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.
Q89) 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.
Q90) 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.
Q91) What is the default session time in php?
The default session time in php is until closing of browser
Q92) 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.
Q93) How can we get the browser properties using PHP?
echo $_SERVER[‘HTTP_USER_AGENT’];
(or)
$browser = get_browser();
foreach ($browser as $name => $value) {
echo “$name $value
\n”;
}
Q94) How to store the uploaded file to the final location?
Files in PHP can be uploaded using move_uploaded_file(string filename, string destination);
Q95) What is Constructors and Destructors?
CONSTRUCTOR : PHP allows developers to declare constructor methods for classes. Classes which
have a constructor method call this method on each newly-created object, so it is suitable for any
initialization that the object may need before it is used.
DESTRUCTORS : PHP 5 introduces a destructor concept similar to that of other object-oriented
languages, such as C++. The destructor method will be called as soon as all references to a particular
object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.
Q96) What is MVC?
MVC stands for Model, View, and Controller. PHP MVC is an effective way to manage the code into 3
different layers.
Model: Model represents the information in application.
View: View represents the visual representation of information and data that you have entered in the
application.
Controller: Controller is actually how and in which way you want to read the information in
application.
Q97) What is meant by nl2br()?
New Line to HTML Break
echo nl2br(“Hello \n World”);
Ans :
Hello
World
Q98) What is the maximum length of a table name, a database name, or a field name in MySQL?
Database name – 64 characters
Table name – 64 characters
Column name (field name) – 64 characters
Q99) Get size of a file using php?
filesize() function returns the size of the specified file.
Q100) Function for merging two arrays?
array_merge() function merges one or more arrays into one array.
(or)
simply we can do
$output = $array1 + $array2;
Q101) What is PDO classes?
The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing
databases in PHP. It is a data-access abstraction layer, so no matter what database we use the function
to issue queries and fetch data will be same. Using PDO drivers we can connect to database like DB2,
Oracle, PostgreSQL etc.
learning.shine.com

Top 25 PHP Interview Questions & Answers-


Talent Economy
5-6 minutes
Find out the top 25 PHP Interview Questions & Answers for fresher and experienced candidates. These
interview questions will help to clear the job interview panel and get the PHP job easily.

1. What do you mean by PHP?


It is a web language based on scripts that permit developers to enthusiastically create generated web
pages.
2. Tell me PHP version which is actually used?
Version 7.1 or 7.2 is the suggested version of PHP.
3. Tell me the way to run the interactive PHP shell from the command line interface?
Use the PHP CLI program with the option-" a" as follows:
Php-a
4. Do you think multiple inheritance support in PHP?
PHP supports only particular inheritance; it means that a class can be comprehensive from only one
single class using the keyword 'extended'.
5. How can PHP and HTML interact?
It is likely to generate HTML through PHP scripts, and it is probable to pass pieces of information from
HTML to PHP.
6. What is the use of the function "imagetypes()"?
Image types () gives the image format and kinds supported by the present version of GD-PHP.
7. Define the way to display text with a PHP script?
In this two methods are possible:
<!--?php echo "Method First"; print "Method Second"; ?-->
8. How are failures in execution handled with include () and require () functions?
If the function requires () cannot contact the file, then it ends with an incurable error. However, include
() function gives a caution, and the PHP script continues to perform.
9. Tell the rules for naming a PHP variable?
The following rules are needed:
• A variable name can comprise of numbers, letters, underscores but you cannot use characters
like + , – , % , ( , ) . & , etc.
• Variable names start with a letter character.
10.How can it be possible to set an infinite execution time for PHP script?
The set_time_limit (0) new at the beginning of a script sets to unlimited the execution time to not have
the PHP error 'maximum implementation time exceeded.' We can also specify this in the php.ini file.
11.What is the way export data into an excel file?
The most frequent and used way is to get data into a format supported by Excel. For example, it is
likely to write a .csv file, to prefer, comma as a partition between fields and then to open the file with
Excel.
12.What is the way to handle the result set of MySQL in PHP?
The effect set can be handled using mysqli_fetch_array, mysqli_fetch_assoc, mysqli_fetch_object or
mysqli_fetch_row.
13.What is the method to check the value of a given variable is a number?
It is likely to use the enthusiastic function, is numeric () to make sure whether it is a number or not.
14.What does the unlink () function mean?
The unlink () function is devoted to file system handling. It deletes the file given as entry.
15.Name some frameworks in PHP?
Some of the frameworks in PHP are:
• Symfony
• CakePHP
• CodeIgniter
• Yii 2
• Zend framework
16.Define overloading and overriding in PHP?
Overloading is essential functions that have comparable signatures, yet have diverse parameters.
Overriding is only relevant to result in classes, where the parent class has distinct a method, and the
derived class wishes to override that method. In PHP, you can only overload methods using the magic
method __call.
17.How can we automatically escape incoming data?
We have to allow the Magic quotes entry in the configuration file of PHP.
18.Define a variable accessible in the function of a PHP script?
This feature is likely using the global keyword.
19.How is constantly defined in a PHP script?
The define () directive lets us major a constant as follows:
define ("ACONSTANT", 123);
20.How can a variable be passed by reference?
To be able to exceed a variable by position, we use an ampersand in front of it, as follows $var1 =
&$var2
21.When a conditional statement end with endif?
When the unique if was followed by: and then the code block without braces.
22.What does accessing a class via:: means?
:: is used to contact static methods that do not need object initialization.
23.How can you propagate a session id?
You can spread a session-id via cookies or URL parameters.
24.When do sessions end?
Sessions automatically end when the PHP script ends executing but can be physically ended using the
session_write_close().
25.What does the scope of variables mean?
The range of a variable is the context within which it is clear. Mostly, all PHP variables only have a
particular scope. This specific scope spans built-in and required files as well.
So, these are the following interview questions & answers for PHP jobs; candidates should go through
it and search more before moving ahead for a job interview.
Related Articles:
• Top 12 Cake PHP Interview Questions & Answers
• Top 15 Php MySQL Interview Questions 2020
zuaneducation.com

PHP Interview Questions and Answers for


Freshers 2018
By Mani Kandan
20-25 minutes
In this article, we have provided the significant PHP interview questions and answers for freshers
who will be going for a job interview as a PHP developer. These PHP interview questions have been
designed uniquely to get you familiar with the nature of questions you may face during your interview
for the subject of PHP Programming Language.
It will help you to prepare for technical interviews and online selection tests conducted during
campus placement for freshers and job interviews for professionals. We hope you get these PHP
interview questions and answers helpful and it will also help you to expand your essential PHP skills.
Why should you read this article?

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 Interview Questions and Answers For Freshers


Let’s have a look at important PHP Interview Questions and Answers for freshers.
1. What is PHP?
PHP is a widely-used, open-source server-side scripting language. PHP is an acronym for “PHP:
Hypertext Preprocessor.” It allows the developers to develop dynamic web applications. PHP has
various frameworks and CMS for developing dynamic and interactive websites.
2. What types of loops exist in PHP?
for, while, do while and foreach.
3. How do you display the output directly to the browser?
To display the output directly to the browser, I will use the special tags <?= and ?>.

| Related: Top Benefits and Importance of PHP Language


4. Describe which programming language does PHP parallel to?
The PHP syntax relates Perl and C.
5. How to create a MySQL connection?
mysql_connect(servername,username,password);
6. How to select a database?
mysql_select_db($db_name);
7. What is PEAR?
PEAR means “PHP Extension and Application Repository.” It is a framework and distribution system
for reusable PHP components. It extends PHP and gives a higher level of programming for all web
developers. PEAR is divided into three different classes that are: PEAR Core Components, PEAR
Packages, and PECL Packages. The PEAR Packages include functionality giving for authentication,
networking, and file system features and tools for working with HTML and XML templates.
8. What is the use of “ksort” in php?
In PHP, Ksort has used to sort an array by key in reverse order.
9. What are the data types of PHP?
Integers, Doubles, Booleans, Arrays, Objects, NULL, Strings.
10. Which PHP version is actually used today?
Nowadays, PHP 7 is the actually used version.
PHP Interview Tip:
“During the interview of a potential candidate, I am aiming to understand how updated they are with
the new language features as well as their level of understanding of basic operations. In my opinion,
this will define how good a… Click To Tweet

| Related: Amazing Websites to Learn PHP Language Online


11. What is NULL?
NULL is a particular type which contains only one value: NULL. If you need any variable to set
NULL, just assign it.
12. What is the use of Constant Function?
A constant function is used to return the constant value.
13. What is the correct way to start and complete a PHP block of code?
There is the two most common and correct ways to start and complete a PHP script. That is : <?php
[ — PHP code—- ] ?> and <? [— PHP code —] ?>

14. What is a numeric array?


Numeric array − An array with a numeric index. The values are stored and accessed in a linear fashion.
15. Does PHP support multiple inheritances?
PHP supports only single level of inheritance. A class can be inherited from a single class using the
keyword ‘extended.’
16. Describe what is the major difference between PHP 4 and PHP 5?

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.

| Related: Top Benefits and Importance of PHP Language


21. How to send a mail in PHP?
You can send an e-mail in PHP with mail() function or SMTP details.
22. Explain what the meaning of a final class and a final method is?
‘final’ is initiated in PHP 5. Final class implies that this class can’t be enlarged and a final method can’t
be overridden.
23. How can you break PHP script?
I can use exit() function for that.
24. What is the default page in web server?
Most of the times it will be index page.
25. Explain how a comparison of objects done in PHP 5 is?
I can use the operator ‘==’ to test two objects are mentioned from the corresponding class and have
equal attributes and similar values. I can test if two objects are referring to the same instance of the
corresponding class by the control of the identity operator ‘===’.
26. What are the different types of errors in PHP?
There are 4 basically types of error in PHP.
Parse Error – Commonly caused due to syntax mistakes in codes.
Fatal Error – These are basically runtime errors which are caused when you try to access what cannot
be done.
Warning Error – This error occurs when you try to include a file that is not present.
Notice Error – This error occurs when you try to utilize a variable that has not been declared.
27. What is session and why do we use it?
A session is a super global variable that preserves data across subsequent pages. Session uniquely
defines all users with a session ID. So it supports building a customized web application where user
tracking is required.
28. Describe how PHP and HTML can interact?
Also, it is possible to make HTML into PHP scripts, and it is possible to transfer information from
HTML to PHP.

| Related: Amazing Websites to Learn PHP Language Online


29. Explain which type of operation is required when passing values into an URL?
To pass values by an URL, then you require to encode and to decode them applying urlencode () and
htmlspecialchars().
30. What is cookie and why do we use it?
A cookie is a small piece of information stored in a client browser. It is a technique utilized to identify a
user using the information stored in their browser. Utilizing PHP, we can both set and get COOKIE.
31. What function do we use to find length of string, and length of array?
For finding a length of string we apply strlen() function and for array we use count() function.
32. Describe how PHP and Javascript can interact?
The PHP and Javascript could not directly interact because PHP is a server-side scripting language and
Javascript is a client-side scripting language. But, we can change variables, because PHP can generate
JavaScript code to be performed by the web browser and it is likely to pass particular variables behind
to PHP into the URL.
33. How can we modify the value of a constant?
We cannot alter the value of a constant.
34. What is the difference between unset() and unlink() function?
unset() function is used to destroy a variable whereas unlink() function is used to destroy a file.
35. Explain which is required to be able to utilize image function?
The GD library is required to be able to do image functions. It also helps to execute more image
functions.
36. What is the difference between ID and class in CSS?
The difference between an ID and Class is that an ID can be utilized to identify one element, whereas a
class can be used to identify more than one.
37. What is AJAX?
AJAX (Asynchronous JavaScript and XML) is a technique which enables updating parts of a web page,
without reloading the entire page. Data is exchanged asynchronously in a small amount of data with the
server.
38. What is the use of ‘imagetypes()’ function?
A function imagetypes() provides the image format and types carried by the latest version of GD-PHP.
39. What is jQuery?
jQuery is a fast, small, and feature-rich JavaScript library. It is an easy-to-use API. It makes things like
HTML document traversal and manipulation, animation, event handling and Ajax much simpler across
a more number of browsers.
40. What is the difference between SQL and Mysql?
SQL(Structured Query Language) is a programming language created for managing data held in a
Relational Database Management System. Mysql is an open source, relational database management
System.

| Related: Top Benefits and Importance of PHP Language


41. Describe what the functions to be utilized to get the image properties (Height, Width, and
Size) are?
There are three functions are used to get image properties. That functions are:
imagesy() for getting image height.
imagesx() for getting image width.
getimagesize() for getting image size.
42. What is JOIN in MySQL? What are the different types of join?
MySQL JOINS are utilized to retrieve data from multiple tables. It is performed whenever two or more
tables are joined in a SQL statement. There are various types of MySQL joins: INNER JOIN, LEFT
JOIN, RIGHT JOIN and OUTER JOIN.
43. What is the use of “echo” in PHP?
In PHP, echo is used to print data on the webpage.
Example: <?php echo ‘Car insurance’; ?>
44. Explain how failures in execution are worked with include() and require() functions?
There are some failures when using functions include() and require(). If the function require() can’t
access the file then it stops with a fatal error. But, the include() function provides a warning, and the
PHP script proceeds to perform.
45. How to include a file to a PHP page?
We can include a file utilizing “include() ” or “require()” function with file path as its parameter.
46. What’s the difference between include and require?
If the file is not found by require(), it will cause a fatal error and stop the execution of the script. If the
file is not found by include(), a warning will be issued, but execution will continue.
47. Describe how you can display information of a variable and readable through a human with
PHP?
I can use print_r() function to display a human-readable result.
48. How to declare an array in PHP?
Ex: var $arr = array(‘apple’, ‘grape’, ‘lemon’);
49. What is the use of ‘print’ in PHP?
It is not actually a real function, it is a language construct. So you can utilize without parentheses with
its argument list.

| Related: Amazing Websites to Learn PHP Language Online


50. Explain the PHP error what means ‘Parse error in PHP – unexpected T_variable at line x’?
This error is a PHP syntax error which is revealing that trouble at the line x stops parsing and
performing the program.
51. How to Retrieve a Cookie Value?
Ex: echo $_COOKIE[“user”]
52. What is SQL injection?
SQL injection is a malicious code injection technique that might destroy your database. It exploiting
SQL vulnerabilities in Web applications. It is one of the most common web hacking techniques.
53. What should you do to be capable to export data into an Excel file?
The most comprehensive way is to take data into a format supported by Excel. For example, it is likely
to write a .csv file, to choose for instance comma as a separator between fields and then to open the file
in Excel.
54. Describe what the default session time in PHP is?
In PHP. the default session time is until the closing of the browser

|Related: How to Start a Career in PHP


55. How to destroy a cookie in PHP?
There is not a way to directly delete a cookie. Just use the setcookie function with the expiration date in
the past, to trigger the removal mechanism in your web browser.
56. How to enlarge the execution time of a PHP script?
It is possible to enlarge the execution time of a PHP script by utilizing the set_time_limit function. It
enables to enlarge the execution time of a PHP script.
57. Explain how you can pass the variable by the navigation between the pages in PHP?
I can pass the variable in the navigation by applying cookies, sessions or hidden form fields.
58. How to submit a form with a dedicated button in PHP?
The document.form.submit() function helps to submit the form. For example: <input type=button
value=”SUBMIT” onClick=”document.form.submit()”>
59. Explain the difference between the functions stristr() and strstr() in PHP?
strstr() and stristr both are used to find the first occurrence of the string. stristr( ) is case insensitive, and
it is an identical to superglobal() except that it is case insensitive. The strstr() – Find first occurrence of
a string.
60. Explain how you can define whether a variable is set?
I can use a boolean function. It is set defines if a variable is set and is not NULL.

| Related: Top Benefits and Importance of PHP Language


61. Explain how to parse a configuration file?
It is possible to parse a configuration file by using the parse_ini_file() function. It enables us to load in
the ini file defined in the filename and returns the settings in it in an associative array. The time you run
your script already processes it.
62. What is the use of goto statement?
Php also supports operator goto statement – which is the operator of unconditional transition. It can be
placed to support jumping inside the PHP program. It applied to go into another area of the code.
63. Explain unset() function?
The function unset() is used for variable management. It will generate a variable undefined.
64. What function is used to escape data before storing into the database?
The function addslashes allows us to escape data before storing inside the database.
65. How do you remove escape characters from a string?
I can use stripslashes function. It allows us to remove the escape characters before apostrophes in a
string.
66. Explain how can you automatically escape incoming data?
I can allow the Magic quotes entry in the configuration file of PHP. I will be helping you to escape
incoming data.
67. Explain the get_magic_quotes_gpc() function?
get_magic_quotes_gpc() function shows us whether the magic quotes is switched on or not.
68. How do you remove the HTML tags from data in PHP?
I can use strip_tags() function to remove HTML tags. It allows us to remove a string from the HTML
tags.

|Related: How to Start a Career in PHP


69. Explain how you can determine a variable accessible in functions of a PHP script?
It is possible by utilizing the global keyword.
70. Describe how it is possible to return a value from a function in PHP?
It is possible to return a value by using the instruction ‘return $value;’.
71. Explain which cryptographic extension present generation and verification of digital
signatures?
The extension PHP-OpenSSL gives some cryptographic operations including the generation and
verification of digital signatures.
72. Explain how you can pass a variable by reference?
I can use an ampersand in front of it, as follows $var1 = &$var2. It will help to pass a variable.
73. Describe how it is possible to cast types in PHP?
It has to be described in parentheses before the variable which is to be cast as follows:
* (string) – cast to string
* (int), (integer) – cast to integer
* (array) – cast to an array
* (float), (double), (real) – cast to float
* (bool), (boolean) – cast to boolean
* (object) – cast to object
* (float), (double), (real) – cast to float
74. Describe when a conditional statement is ended with endif?
A conditional statement will end when the original if was followed by : and then the code block without
any braces.
75. Explain how the ternary conditional operator is applied in PHP?
The ternary operator is a set of three expressions: a condition, and two operands defining what
instruction need to be executed when the named condition is true or false like below:
Expression_1? Expression_2 : Expression_3;

| Related: Amazing Websites to Learn PHP Language Online


76. What is the use of func_num_args() function?
In PHP, the func_num_args() function is utilized to provide the number of parameters passed inside a
function.
77. What is rand() function in PHP?
The rand() function is used to generate random numbers.
78. Explain the difference between __sleep and __wakeup method in PHP?
The __sleep method returns the array of all the variables that should be saved, while __wakeup method
retrieves them.
79. Describe a session?
The definition of a session is a logical object allowing us to store temporary data over various PHP
pages.
80. Explain how to initiate a session in PHP?
session_start() function allows us to activating a session.
81. Explain how is it possible to create a session id?
Generating a session id through cookies or URL parameters is possible.
82. What are MAGIC Constants in PHP?
PHP gives a large number of predefined constants to any script which it runs known as magic
constants.
|Related: How to Start a Career in PHP
83. Explain the meaning of a Persistent Cookie in PHP?
It is also called as a Permanent cookie. A persistent cookie is permanently saved in a cookie file on the
computer.
84. How to know uploaded file size?
Using $_FILES[‘file’][‘size’] statement to know uploaded filesize in PHP.
85. What is $GLOBALS?
The $GLOBALS is a PHP superglobal variable. It can be utilized instead of a global keyword to access
variables from global scope.
86. What is $_SERVER?
The $_SERVER is an array adding information created by the web server. For example headers, paths,
and script locations.
87. What is $_FILES?
The $_FILES is an associative array created for items sent to the current script through the HTTP
POST method.
88. What is $_ENV?
In PHP, $_ENV is used to return the environment variables from the web server. It is an associative
array of variables sent to the latest PHP script through the environment method. To set real
environment variables, you need to use putenv().
89. What is the use of file_get_contents() function?
The function file_get_contents() is used to read a file and store it in a string variable.
90. Explain how you can connect to a MySQL database from a PHP script?
To connect a MySQL database, i can use mysql_connect() function.
<!–?php $database = mysql_connect(“HOST”, “USER_NAME”, “PASSWORD”);
mysql_select_db(“DATABASE_NAME”,$database); ?–>
91. Explain how it is possible to know the number of rows returned in the result set?
It is possible to know using mysql_num_rows() function. It returns the number of rows in the result set.
92. Explain which function provides us the number of modified entries by a query?
The function mysql_affected_rows() returns the number of entries modified by an SQL query.

|Related: How to Start a Career in PHP


93. Explain the difference between mysql_fetch_object() and mysql_fetch_array() in PHP?
This will provide access to the data through the field names. In PHP, the function mysql_fetch_object()
will get the first single matching record where mysql_fetch_array() will get all matching records from
the table in an array.
94. How can you verify the value of a provided variable is a number?
I can use is_numeric() function to verify whether it is a number or not.
95. How can you examine the value of a given variable is alphanumeric?
I can use ctype_alnum function to verify whether it is an alphanumeric value or not.
96. How do you verify if a provided variable is empty?
I can verify if a given variable is empty by using empty() function.
97. Explain the unlink() function?
The function unlink() is applied for file system handling. It just deletes the file given as entry.
98. When did sessions end?
The sessions will automatically end when the PHP script stops executing. However, it can be manually
finished by utilizing the session_write_close().
99. Explain how you can pass a variable by reference?
I can use an ampersand in front of it, as follows $var1 = &$var2. It will help to pass a variable.
100. Describe when a conditional statement is ended with endif?
A conditional statement will end when the original if was followed by : and then the code block without
any braces.

|Related: How to Start a Career in PHP

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 ?

• What are the interview questions in php for freshers ?

• PHP interview questions for 5 year experienced


candidates ?

• Web developer interview questions ?


1. What is PHP?
PHP is a server side scripting language commonly used for web applications. PHP has many
frameworks and cms for creating websites.Even a non technical person can cretae sites using its
CMS.WordPress,osCommerce are the famus CMS of php.It is also an object oriented
programming language like java,C-sharp etc.It is very eazy for learning
2. What is the use of "echo" in php?
It is used to print a data in the webpage, Example: <?php echo 'Car insurance'; ?> , The
following code print the text in the webpage
3. How to include a file to a php page?
We can include a file using "include() " or "require()" function with file path as its parameter.
4. What's the difference between include and require?
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.
5. require_once(), require(), include().What is difference between them?
require() includes and evaluates a specific file, while require_once() does that only if it has not
been included before (on the same page). So, require_once() is recommended to use when you
want to include a file where you have a lot of functions for example. This way you make sure
you don't include the file more times and you will not get the "function re-declared" error.
Object 1

6. Differences between GET and POST methods ?


We can send 1024 bytes using GET method but POST method can transfer large amount of data
and POST is the secure method than GET method .
7. What is the purpose of the superglobal variable called $_SERVER ?
$_SERVER is an array and it holds the information about paths, headers, and script locations.
8. How to Detecting request type in PHP ?
By using $_SERVER['REQUEST_METHOD'] method

9. How to declare an array in php?


Eg : var $arr = array('apple', 'grape', 'lemon');
10.How can PHP interact to Javascript ?
PHP cannot interact with javascript directly, since php is server side programming language
when javascript is a client side programming language. However we can embbed the php
variable values to a javascript code section when it complile at the server or javascript can
communicate to a php page via http calls
NB: Javascript can run at the server side as well using Node.js Server
11.How to manipulate image files using php ?
GD is library that providing image manipulation capabilities to php, so that we can do so many
things such as crop, merge, change grayscale and much more with GD functions
12.How to manipulate video files using php ?
There is no inbuilt library available in php, However there are some open source libraries that
providing these features
FFmpeg is a complete, cross-platform solution to record, convert and stream audio and video.
We can install this extension in php and use to do variety of tasks
13.What is cron jobs ?
Cron jobs are scheduled tasks, executed on regular time intervals set by the developer. They
work by running preferred scripts. We can set the time intervals for running these scripts. Its not
a part of php compiler, We have several ways to do this based on the platform or the hostign
control panel type
14.How to sent a POST request from php ( Without using any html ) ?
You could use cURL, that allows you to connect and communicate to many different types of
servers with many different types of protocols such as http, https, ftp etc.
15.How to create a directory if it doesn't already exist ?
<?php
if (!file_exists('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
?>
16.How to delete an element from an array ?
If you want to just delete a single element you can use unset() or alternatively
array_splice().

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();
}
?>

Example (MySQLi Object-Oriented)

<?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";
?>

Example (MySQLi Procedural)

<?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";
?>

28.What are prepared statements?


A prepared statement or a parameterized statement is a feature used to execute the same SQL
queries repeatedly with high efficiency. It consists of two stages: prepare and execute. Prepared
statements reduce parsing time because preparation on the query is done only once while the
statement is executed multiple times. It is very useful against SQL injections because parameter
values won't alter objective of the statement.
29.How to execute an sql query? How to fetch its result ?
Example (MySQLi Object-oriented)

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql); // execute sql query

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)

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = mysqli_query($conn, $sql); // execute sql query

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

$stmt = $db->query('SELECT id FROM Employee');


$row_count = $stmt->rowCount();
echo $row_count.' rows selected';

Method 2: Statements With Parameters

$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");


$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
30.Write a program using while loop
<?php
$x = 1;

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
}

• Using MySQLi (for MySQL):


$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name
= ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}

If you're connecting to a database other than MySQL, there is a driver-specific second


option that you can refer to (e.g. pg_prepare() and pg_execute() for PostgreSQL). PDO
is the universal option.
97.How to fix “Headers already sent” error in PHP ?
No output before sending headers. there should not be any output (i.e. echo.. or HTML codes)
before the header(.......);command. remove any white-space(or newline) before <?php and
after ?> tags. After header(...); you must use exit;
98.How to return JSON from a PHP Script ?
We have to set the Content-Type header with application/json as the value and print a valid
JSON data using echo method
For example
<?php
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);

99.How can we fix "Memory size Exhausted" errors ?


You can fix it at run time or can be set required size on the php.ini file
ini_set('memory_limit', '512M'); // In a php script at run time

100.When to use self over $this?


Use $this to refer to the current object. Use self to refer to the current class. In other words, use
$this->member for non-static members, use self::$member for static members.
101.How to redirect the user to one page to another using php ?
we have a special php function called header, can be used to do the same
header("Location: new-page.php");. We already defined the step for the same in
our blog post How to php redirect

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

• What are the ways to integrate css in a web page


There are three ways to integrate css in a web page
• Inline : It is used to Apply some styles to an element including its child elements using
style attribute
• Embedded : We can write group of styles with in the html <style></style> tag
• Linked/ Imported : We can specify an external stylesheet url using the following code
<link rel="stylesheet" type="text/css" href="custom.css" />

• Listout some widely using CSS Measurement Units


• px - Defines a measurement in screen pixels.
• % - Defines a measurement as a percentage relative to another value, mainly an
enclosing element.
• em - It is a relative measurement for the height of a font used in em spaces in a web
page. Because 1em unit is equivalent to the size of a given font, if you assign a font to
10pt, each "em" unit would be 10pt; thus, 2em would be 20pt.
• vh - 1% of viewport height, Viewport measurements are very useful when developing a
responsive web page or Hybrid App.
• vw - 1% of viewport height.
• vw - 1% of viewport height.

• Which property allows you to control the shape or appearance of the


marker of a list?
The list-style-type allows you to control the shape or appearance of the marker.

• Which property specifies whether a long point that wraps to a second


line should align with the first line or start underneath the start of the
marker of a list?
The list-style-position specifies whether a long point that wraps to a second line should align
with the first line or start underneath the start of the marker.

• Which property specifies an image rather than a bullet point or


number for the marker of a list?
The list-style-image specifies an image for the marker rather than a bullet point or number.

• Which property serves as shorthand for the styling properties of a


list?
The list-style serves as shorthand for the styling properties.

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

• Which property specifies the bottom padding of an element?


The padding-bottom specifies the bottom padding of an element.

• Which property specifies the top padding of an element?


The padding-top specifies the top padding of an element.

• Which property specifies the left padding of an element?


The padding-left specifies the left padding of an element.

• Which property specifies the right padding of an element?


The padding-right specifies the right padding of an element.

• Which property serves as shorthand for the all the padding


properties of an element?
The padding serves as shorthand for the all the padding properties.
• Which property allows you to specify the type of cursor that should
be displayed to the user?
The cursor property of CSS allows you to specify the type of cursor that should be displayed to
the user.

• Which value of cursor property changes the cursor based on context


area it is over?
auto − Shape of the cursor depends on the context area it is over. For example, an 'I' over text, a
'hand' over a link, and so on.

• Which property is used to set all the outlining properties in a single


statement?
The outline property is used to set all the outlining properties in a single statement.

• Which property is used to set the height of a box?


The height property is used to set the height of a box.

• Which property is used to set the width of a box?


The width property is used to set the width of a box.

• Why is @import only at the top?


@import is preferred only at the top, to avoid any overriding rules. Generally, ranking order is
followed in most programming languages such as Java, Modula, etc. In C, the # is a prominent
example of a @import being at the top.

• What is contextual selector?


Selector used to select special occurrences of an element is called contextual selector. A space
separates the individual selectors. Only the last element of the pattern is addressed in this kind
of selector. For e.g.: TD P TEXT {color: blue}

• How html5 is different from html4?


HTML5 is an upgraded version of html4.01 and introduced some new features such as Audio,
Video, Canvas, Drag & Drop, Storage, Geo Location, Web Socket etc and also introduced some
new html tags such as article, section, header, aside and nav etc which help to create the page
layout faster. HTML 5 will handle the inaccurate syntax of the tags and it simplified the doctype
and character set declaration. It also deprecated some html tags like center, font, strike,
acronym, applet etc.

• How browsers detect the html version of a webpage?


We must declare the doctype at the top of the page, it is an instruction to the web browser about
what version of HTML the page is written in.
• Write down the Doctype declaration of html5 and html4
html5
<!DOCTYPE html>

html4
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

• What are the new form attributes in HTML5 ?


Placeholder, novalidate, autocomplete, required , autofocus, pattern, list, multiple,
formnovalidate etc

• What are the different units for expressing a length in css?


rem, vh, vw, ex, ch, em, %, px, in, cm, mm, pt and pc

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

• What is character encoding in HTML ?


Character encoding is a rule for how to interpret raw zeroes and ones into real characters. There
are two main character encoding representations used in html documnets such as UTF-8, and
ISO-8859-1. The default character set for HTML5 is UTF-8. The following syntax is used to set
the character encoding in an html document <meta charset="UTF-8">
• What is HTML Entities ?
HTML Entities are some special words which is used to replace the reserved characters or some
other characters that are not present on your keyboard can also be replaced by entities in your
HTML, For example if you need to display < ( 'Less than' symbol ) In your html document,
You can use &lt; Entity

• What is mean by Responsive Web Site ?


It will looks good in all screen resolutions device type. We can utilize css media quries to re-
arrange the with of an element also we can hide or display any elements in a web page.
Bootstrap is a widely using css framework to make responsive web pages quikly

• List out some HTML5 tags


header, footer, main, nav, section, article, aside etc..

• What is the use of HTML5 Canvas element ?


It is used to draw graphics on a web page by the help of javascript.

• What is the use of 'placeholder' attribute in HTML5?


It is used to display some text with in a textbox or textarea and the text will disappear when user
start typing in that box

You might also like