Php Interview Questions and Answers
Basic Level PHP Interview Questions :-
Q. What is PHP?
PHP is a web language based on scripts that allow developers to dynamically create generated web pages.
Q. What do the initials of PHP stand for?
PHP means PHP: Hypertext Preprocessor.
Q. Which programming language does PHP resemble?
PHP syntax resembles Perl and C
Q. 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.
Q. 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.
Q. How to run the interactive PHP shell from the command line interface?
Just use the PHP CLI program with the option -a as follows:
Q. 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:
Q. 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 .
Q. 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.
Q. What is the difference between static and dynamic websites?
|Static Websites||Dynamic Websites|
|In static websites, content can’t be changed after running the script. You cannot change anything in the site as it is predefined.||In dynamic websites, content of script can be changed at the run time. Its content is regenerated every time a user visits or reloads.|
Q. 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:
Q. 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.
Q. 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.
Q. 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.
Q. What are the different types of PHP variables?
There are 8 data types in PHP which are used to construct the 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.
Q. 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.
Q. 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.
Q. 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.
Q. 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.
Q. 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 –
Q. What are the differences between PHP constants and variables?
|There is no need to write dollar ($) sign before a constant||A variable must be written with the dollar ($) sign|
|Constants can only be defined using the define() function||Variables can be defined by simple assignment|
|Constants may be defined and accessed anywhere without regard to variable scoping rules.||In PHP, functions by default can only create and access variables within its own scope.|
|Constants cannot be redefined or undefined.||Variables can be redefined for each path individually.|
Q. Name some of the constants in PHP and their purpose.
- _LINE_ – It represents the current line number of the file.
- _FILE_ – It represents the full path and filename of the file. If used inside an include,the name of the included file is returned.
- _FUNCTION_ – It represents the function name.
- _CLASS_ – It returns the class name as it was declared.
- _METHOD_ – It represents the class method name.
Q. 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.
Q. What is the difference between PHP4 and PHP5?
Q. 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.
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.
Q. 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'.
Q. 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
Q. 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 ‘===’.
Q. 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().
Q. 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.
Q. What is needed to be able to use image function?
GD library is needed to execute image functions.
Q. What is the use of the function 'imagetypes()'?
imagetypes() gives the image format and types supported by the current version of GD-PHP.
Q. 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.
Q. Name some of the popular frameworks in PHP.
Some of the popular frameworks in PHP are:
- Yii 2
- Zend Framework
Q. What are the data types in PHP?
PHP support 9 primitive data types:
|Scalar Types||Compound Types||Special Types|
Q. 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:
Q. 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.
Q. 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.
Q. 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.
Q. 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.
foreach (array as value)
code to be executed;
Q. What are the different types of Array in PHP?
There are 3 types of Arrays in PHP:
- Indexed Array – An array with a numeric index is known as the indexed array. Values are stored and accessed in linear fashion.
- 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.
- Multidimensional Array – An array containing one or more arrays is known as multidimensional array. The values are accessed using multiple indices.
Q. 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 –
It will give the following output–
My $variable will not print! My name will print
Q. How to concatenate two strings in PHP?
To concatenate two string variables together, we use the dot (.) operator.
This will produce following result −
Q. 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.
Q. 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())
Q. How can I display text with a PHP script?
Two methods are possible:
Q. 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().
Q. 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.
Q. 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.
Q. 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.
Q. What is the function file_get_contents() useful for?
file_get_contents() lets reading a file and storing it in a string variable.
Q. 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:
Q. 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
Q. 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.
Q. 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.
Q. 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.
Q. 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.
Q. 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'
Q. 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:
Q. 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.
Q. 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.
Q. 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.
Q. What does the unlink() function mean?
The unlink() function is dedicated for file system handling. It simply deletes the file given as entry.
Q. What does the unset() function mean?
The unset() function is dedicated for variable management. It will make a variable undefined.
Q. How do I escape data before storing it in the database?
The addslashes function enables us to escape data before storage into the database.
Q. 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.
Q. How can we automatically escape incoming data?
We have to enable the Magic quotes entry in the configuration file of PHP.
Q. 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.
Q. Is it possible to remove the HTML tags from data?
The strip_tags() function enables us to clean a string from the HTML tags.
Q. 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:
Q. How can we define a variable accessible in functions of a PHP script?
This feature is possible using the global keyword.
Q. How is it possible to return a value from a function?
A function returns a value using the instruction 'return $value;'.
Q. 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.
Q. 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.
Q. How is a constant defined in a PHP script?
The define() directive lets us defining a constant as follows:
define ("ACONSTANT", 123);
Q. 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
Q. 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.
Q. 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
Q. When is a conditional statement ended with endif?
When the original if was followed by: and then the code block without braces.
Q. 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;
Q. 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.
Q. 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.
Q. What does accessing a class via :: means?
:: is used to access static methods that do not require object initialization.
Q. In PHP, objects are they passed by value or by reference?
In PHP, objects passed by value.
Q. Are Parent constructors called implicitly inside a class constructor?
No, a parent constructor have to be called explicitly as follows:
Q. 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.
Q. What is faster?
1- Combining two variables as follows:
$variable1 = 'Hello '; $variable2 = 'World'; $variable3 = $variable1.$variable2;
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.
Q. what is the definition of a session?
A session is a logical object enabling us to preserve temporary data across multiple PHP pages.
Q. How to initiate a session in PHP?
The use of the function session_start() lets us activating a session.
Q. How can you propagate a session id?
You can propagate a session id via cookies or URL parameters.
Q. 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.
Q. When do sessions end?
Sessions automatically end when the PHP script finishes executing but can be manually ended using the session_write_close().
Q. 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.
Q. What does $GLOBALS mean?
$GLOBALS is associative array including references to all variables which are currently defined in the global scope of the script.
Q. What does $_SERVER mean?
$_SERVER is an array including information created by the web server such as paths, headers, and script locations.
Q. What does $_FILES means?
$_FILES is an associative array composed of items sent to the current script via the HTTP POST method.
Q. 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.
Q. 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.
Q. 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.
Q. What does $_ENV mean?
$_ENV is an associative array of variables sent to the current PHP script via the environment method.
Q. What does $_COOKIE mean?
$_COOKIE is an associative array of variables sent to the current PHP script using the HTTP Cookies.
Q. 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.
Q. 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.
Q. 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.
Q. 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.
Q. 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).
Q. 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.
Q. 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.
Q. 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.
Q. What does the expression Exception::__toString means?
Exception::__toString gives the String representation of the exception.
Q. 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.
Q. How can we determine whether a variable is set?
The boolean function isset determines if a variable is set and is not NULL.
Q. 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.
Q. what is the difference between for and foreach?
for is expressed as follows:
for (expr1; expr2; expr3)
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.
Q. 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:
Q. 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.
Q. Is it possible to protect special characters in a query string?
Yes, we use the urlencode() function to be able to protect special characters.
Q. 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).
Q. What is the difference between characters 34 and x34?
34 is octal 34 and x34 is hex 34.
Q. 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.
Q. 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.
Q. Is it possible to destroy a cookie?
Yes, it is possible by setting the cookie with a past expiration time.
Q. What is the default session time in PHP?
The default session time in php is until the closing of the browser
Q. 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.
Q. 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.
Q. 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.