104 Advanced PHP Interview Questions And Answers for freshers and experienced candidates

Spread the love

Core interview questions and answers for PHP for freshers as well as experienced candidates!

Have you lately wanted to test your PHP skills or learn for an important interview? Have you been dreading the interview as well as the questions that might be thrown at you? If your answer to both the questions is an unequivocal YES, then you have come to the right place. In this post, we share with you some most frequently asked and the most common Core PHP interview questions that come with code samples and detailed answers.

It is no secret that the demand for skilled PHP individuals for jobs is growing with every passing day. There are some common questions that people preparing or searching for these PHP jobs have to face on a regular basis. Therefore, irrespective of whether you are a fresher or an established professional in the PHP domain, if you have an interview coming up and wish to establish yourself as a successful and knowledgeable PHP developer, this article is your ticket to enhancing your chances of landing a PHP job in a hassle-free manner.

Therefore, if you plan to embark on a career in the domain of PHP and also wish to delve deeper into the skills that are related to the programming language, now is probably the best time to dive right in. So, read on to find the questions and answers that could land you the job of your dreams!

  1. What is PHP?

PHP is a recursive acronym that stands for Hypertext Preprocessor. It is a web language that is based on scripts, and that enables developers to create, and design generated web pages dynamically. PHP can easily be known as one of the most popular and used server-side scripting languages that are used to develop web applications. Developers use PHP for the creation of dynamic content by embedding HTML. They can also use this web language to handle sessions, communicate with a database server, etc. This open-source programming language is widely used and is specifically suited for the creation of mobile APIs and dynamic websites.

  1. What does PHP stand for?

PHP stands for Hypertext Preprocessor.

  1. PHP resembles which programming language?

The syntax of PHP resembles Perl and C.

  1. What is the full form of PEAR?

PEAR stands for PHP Extension and Application Repository. This is an extension of PHP that offers a higher level of programming than PHP to web developers.

  1. State the most used versions of PHP.

Version 7.1 or 7.2 is usually the most recommended and used versions of PHP.

  1. How can you execute a complete PHP script perfectly from the command line?

In order to execute a complete PHP script perfectly from the command line, all you need to do is utilize the PHP Command Line Interface or CLI and then mention the script’s file name that is to be executed in the following manner:

Php script.php

  1. What is the right way to run an interactive PHP shell from the CLI?

In order to do that, you must use the program of PHP CLI with the following option:

PHP – a

  1. What is the most common and correct way to begin as well as end a PHP block of code?

A PHP script can be started and finished in the two most common ways as shown below:

<? [— PHPcode —]?>and <?php [   — PHP code—-]?>

  1. How is it possible to display the output to the browser directly?

In order to display the output in a direct manner to the browser, it is crucial to use the special tags‘?>.’ and ‘<? =.’

  1. How do we differentiate PHP4 as well as PHP5?

The main difference between the two is that in PHP5, there are several additional Object-Oriented Programming or OOP features.

  1. Does PHP support multiple inheritances?

No! PHP only supports one inheritance. This means that only one class can extend a class with the use of the keyword ‘extended.’

  1. How can you define the final method and final class?

The word “final” presents itself in PHP5. In this context, the final class refers to the class that cannot be extended. The final method is one that cannot be overridden.

  1. How do you compare objects in PHP?

The operator ‘==’ is used in order to test two different objects that have been instanced from a similar class as well as those that have equal values and the same attributes. It can also be tested whether or not two different objects are referred to as a similar instance belonging to the same class. It can be done by using the identity operator ‘===.’

  1. How do HTML and PHP interact?

You can generate HTML via PHP scripts and can even pass information to PHP from HTML.

  1. What kind of operation do you need to pass values through a URL or a form?

If you wish to pass values through a URL or a form, you must encode as well as decode them with the use of urlencode() and htmlspecialchars().

  1. How do JavaScript and PHP interact?

JavaScript and PHP cannot interact directly because JavaScript is a client-side language, and PHP is a server-side language. That said, it is possible to exchange variables because PHP can generate a JavaScript code that the browser can execute. It is equally possible to pass some particular variables via the URL back to PHP.

  1. How can one use an image function?

You need the GD library in order to execute an image function.

  1. The function ‘imagetypes()’ is used for what purpose?

This function offers the image format as well as the types that are supported by GD-PHP’s current version.

  1. If you wish to obtain the properties of an image such as its size, height, and width, what functions will you use?

You will use imagesx() for width, getimagesize() for size and imagesy() for height.

  1. How do include () as well as require () functions help in handling failures in execution?

If a file cannot be accessed by the function require(), then it might end with a rather fatal error. That said, the function include() gives out a warning. Also, in this case, the PHP script continues its execution.

  1. State the difference between require_once() and require().

The functions require_once() and require() have the same objective, and they also perform a similar task. The only difference between the two is that require_once() function also checks and verifies whether or not the PHP script has already been included prior to executing it. The functions include() and include_once() also have the same function.

  1. How is it possible to display a text in addition to a PHP script?

This can be done using two methods:

print “Method 1”; ?–>

or

<!–?php echo “Method 2”

  1. How is it possible to display information of any variable which is also readable by a human being with the help of PHP?

In order to be able to do this or display a result that is human-readable, the function print_r() is used.

  1. How can you set an infinite execution time when it comes to a PHP script?

The function set_time_limit(o) is present at the start of a script. This sets the time of execution to infinite so that there is no PHP error such as ‘maximum execution time exceeded.’ In addition to that, you can also mention it in the php.ini file.

  1. What is the difference between “echo” and “print?”

Although echo and print are not ‘functions,’ constructions of the language (such as if, while or list()), the main difference is that print can behave like a function.Since it returns the value 1, it is possible that an instruction print is participating in complex expressions where echo would generate an error. This leads us to deduce that print is somewhat slower than echo since it loses time to take care of returning the value. In my opinion, logic tells me that the longer the text to be displayed, the less one should notice the difference in speed between one construction and another. On the other hand, perhaps less critical is the fact that echo supports the syntax echo “text,”“text,” … and “print no.”

  1. Describe the fatal error.

Fatal errors are errors that can seriously compromise the operation of a program and therefore, to prevent significant problems, the execution is aborted, and the program stops functioning completely. It is the highest error level.

  1. How are fatal errors classified?

Depending on where the error is generated, several types of fatal errors can be distinguished that are identified with the following constants:

E_ERROR: Critical error generated at runtime. The PHP interpreter engine generates them.

E_CORE_ERROR: Critical error that occurs during the initial PHP startup. The PHP core generates them.

E_COMPILE_ERROR: Critical error that occurs at compile time and is generated by the Zend Engine.

E_USER_ERROR: Critical error generated by the trigger_error() function used by the developer to generate custom fatal errors.

E_RECOVERABLE_ERROR: This is a recoverable critical error, a potentially dangerous one but that does not leave the program in an unstable state. The important thing about these types of errors is that they can be captured if an error manager has been defined (set_error_handler ()) and here, the programmer can decide what to do, whether to continue with the execution or not. If an error handler has not been defined, the E_RECOVERABLE_ERROR will be treated as E_ERROR, and the program will be aborted.

In addition to that, there are some recurring traps that you could find, and you should also take into account:

Parameters: There are parameters in functions that we do not specify because they are omitted, but in a labor test, we should not think in that way. The employer will evaluate every aspect of our behavior to predict possible future errors. Let’s not forget to put the connection variable xxxx_quey ( $ query, $ connection). We know that it is not always necessary, but it is better to use it anyway.

Login: This is quite common. Never forget that session_start () should go to the beginning of the code and not print anything before.

Arrangements: This has touched me recently, a typical trap, they declare a variable as an array $ var [] = 1, and print as variable echo $ var;

Heads: I know that many of you will not take it into account, but it is essential to understand this from the heads (which is not the same as XD header), a common mistake is this: echo «you will be redirected»; header (“Location: these_dispatched.php”);

Cookies: A good reason to be fired is the use of unnecessary cookies. We know that cookies have a bad reputation, and end users can disable them.

  1. ‘Parse error in PHP – unexpected T_variable at line x’ is a PHP error, but what does it mean?

It is, in simple terms, a PHP syntax error. It expresses an error at line x, and it stops parsing and/or executing the program.

  1. The function file_get_contents() is useful for what?

The function file_get_contents() allows users to read a file as well as store it properly in a string variable.

  1. How is it possible to connect from a PHP script to a MySQL database?

In order to connect from a PHP script to a MySQL database, it is necessary to utilize the function of mysqli_connect() as shown below:

<!–?php $database = mysqli_connect(“HOST”, “USER_NAME”, “PASSWORD”); mysqli_select_db($database,”DATABASE_NAME”); ?–>

  1. The function mysql_pconnect() is used for what purpose?

The function mysql_pconnect() makes sure that a persistent connection is achieved to the database. This means that the connection will not close even if/when the PHP script comes to an end. PHP 7.0, as well as above, do not support this function.

  1. How does PHP handle the result set of MySQL?

PHP can handle the result set of MySQL by using mysqli_fetch_assoc, mysqli_fetch_array, mysqli_fetch_row, or mysqli_fetch_object.

  1. How can you know the total number of rows that are returned in a result set?

The mysqli_num_rows() function helps in returning all the rows in a specific result set.

  1. What is the function that provides us with the total number of entries that have been affected by a query?

The function mysqli_affected_rows() helps us by returning the total number of entries that have been affected by an SQL query.

  1. State the difference betweenmysqli_fetch_array() and mysqli_fetch_object().

The function of mysqli_fetch_object()assists by collecting the very first single matching record. On the other hand, the function of mysqli_fetch_array() helps in collecting all the matching records in an array from the table.

  1. How is it possible to access all the data with the GET method that has been sent via the URL?

In order to access this data using the GET method, you must use the $_GET array, as shown below:

www.url.com?var=value

Thereafter, the function$variable = $_GET[“var”]; will contain the ‘value.’

  1. How is it possible to access all the data that has been sent via the URL using the POST method?

In order to access all the data that has been sent in this manner, you must use the array of $_POST. For instance, if you have a form field known as ‘var’ on the form, the moment at which a user clicks on the icon of ‘submit’ in order to submit the form, it will become possible for you to access the particular value using$_POST[“var”];

  1. How is it possible to verify that the value of a specific variable that is given is a number?

You can use is_numeric() as a dedicated function in order to check whether or not the value is a number.

  1. How is it possible to verify that the value of a particular variable that is given is alphanumeric?

You can use the dedicated function of ctype_alnum in order to verify whether or not the value of the variable is alphanumeric.

  1. How is it possible to verify whether or not a particular variable that has been given is empty?

In order to verify whether or not a variable possesses a value, you must use the function of empty().

  1. The function of unlink() stands for what?

The function of unlink() is meant for the file system handling. Using this function, you can delete all the given files as entries.

  1. The function unset() stands for what?

The function of unset() is meant for variable management. Using this function, you can make a specific variable undefined.

  1. How can we escape data prior to storing it all into a database?

The function of addslashes allows us to escape all kinds of data prior to storing it into a database.

  1. How can we remove escape characters when it comes to a string?

The function of striplashes allows us to remove escape characters prior to apostrophes in a string.

  1. How is it possible to escape the incoming data automatically?

In order to escape the incoming data automatically, it is crucial to enable the entry of “Magic quotes” in PHP’s configuration file.

  1. The function of get_magic_quotes_gpc() means what?

The function of get_magic_quotes_gpc() helps by informing us whether or not the magic quotes are switched on.

  1. Can we remove the HTML tags when it comes to data?

The function of strip_tags() allows us to remove HTML tags from data or a clean a string from HTML tags.

  1. The static variable present in function is used for what purpose?

We can define a static variable within a specific function only for the first time. Its value can be changed during different function calls as shown below:

<!–?php function testFunction() { static $testVariable = 1; echo $testVariable; $testVariable++; } testFunction();              //1 testFunction();                 //2 testFunction();           //3 ?–>

  1. How can we return a value properly from a function?

To do that, you will have to use the instruction ‘return $value;’ to be able to return the value from a specific function.

  1. How is it possible to define a variable that is accessible in a PHP script’s functions?

You can use the global keyword to enable or use this feature.

  1. Describe the most convenient method of hashing that can be used in order to hash passwords.

You can use crypt() preferably. It supports many hashing algorithms natively. Alternatively, you can also use the function of hash() that supports significantly more variants than crypt() instead of using all the standard algorithms of hashing such as sha256 or sha1 as they are quite fast. Therefore, hashing passwords in conjunction with all these algorithms are able to create vulnerability.

  1. Using which cryptographic extension can you get the verification and generation of digital signatures?

The extension of PHP-OpenSSL offers many cryptographic operations that include the verification and generation of digital signatures.

  1. How do you define a constant in a PHP script?

In order to define a constant in a PHP script, you can use the directive of define() as shown below:

define (“ACONSTANT”, 123);

  1. Can a comparison of a string “13” and an integer 12 work in PHP?

It is possible to compare 12 and “13” in PHP because they cast everything easily to the type of integer.

  1. How is it possible to pass by reference a variable?

In order to pass by reference a variable, you can use an ampersand ahead of it in the following manner: $var1 = &$var2.

  1. How can you cast different types in PHP?

You must specify the name of the type of output in parentheses prior to the variable that you mean to cast. You can do it, as shown below:

* (int), (integer) – cast to integer

* (float), (double), (real) – cast to float

* (bool), (boolean) – cast to Boolean

* (array) – cast to array

* (string) – cast to string

* (object) – cast to object

  1. In which case does a conditional statement end with endif?

In the case the original “if” is followed by a “:” and the code block is used without braces, it ends with endif.

  1. How do you use the ternary condition operator in PHP?

The ternary condition operator comprises of three distinct expressions: a condition, as well as two operands that describe the exact instruction that must be performed in case the mentioned condition, is either true or false as shown below:

Expression_1?Expression_2 : Expression_3;

  1. Describe the use of the function of func_num_args() in PHP.

The function of func_num_args() can give several parameters to the number that is passed into a specific function.

  1. In case the variable $var2 is set to the var1 character and the variable $var1 has been set to 10, what will the value of $$var2 be?

In this case, the value of $$var2 will be 10.

  1. What does it mean when you say “to access a class through ::?”

You can access static methods using :: that do not need object initialization.

  1. Are objects passed by reference or by value in PHP?

Objects are passed by value in PHP.

  1. Do we call parent constructors inside a class instructor implicitly?

No! You must call a parent constructor explicitly, as shown below:

parent::constructor($value)

  1. State the difference between _wakeup and _sleep.

_wakeup retrieves the array of the complete list of variables which require to be saved whereas _sleep returns them.

  1. Which of the two is quicker? Combining two variables like this: 2- $variable3 = “$variable1$variable2”; or $variable1 = ‘Hello ‘; $variable2 = ‘World’; $variable3 = $variable1.$variable2;

The $variable3 contains “Hello World.” Hence, the first code will be quicker as compared to the second one, especially when it comes to large sets of data.

  1. How do you define a session?

A session can be defined as a logical object that allows us to preserve all the temporary data across many PHP pages.

  1. How can you start a session in PHP?

You can activate a session in PHP by using the function of session_start().

  1. How is it possible to propagate a session ID?

It is possible to propagate a session ID through URL parameters or cookies.

  1. How can you define a persistent cookie?

A persistent cookie can be defined as a cookie that has been stored permanently in a cookie file on the computer of the browser. Cookies are temporary by default, and they are also erased when the browser is closed.

  1. When do sessions usually end?

Sessions end automatically once the PHP script completes its execution. However, you can end them manually as well by using the session_write_close() function.

  1. State the difference betweensession_unset() and session_unregister().

The function of session_unregister() is used to unregister a global variable when it comes to the current session. On the contrary, the function of session_unset() helps in freeing all the session variables.

  1. What is the meaning of $GLOBALS?

$GLOBALS is an associative array that includes all the references to all the variables that are currently defined in the script’s global scope.

  1. What is the meaning of $_SERVER?

$_SERVER can be defined as an array that includes all the information that has been created by the web server. This includes script locations, headers, and paths.

  1. What do you mean by $_FILES?

$_FILEScan be defined as an associate array that is composed of all the sent items to the current script through the method of the HTTP POST.

  1. State the difference between $_FILES[‘userfile’][‘tmp_name’] and $_FILES[‘userfile’][‘name’].

$_FILES[‘userfile’][‘tmp_name’] is thetemporary filename given to the file that is stored on the server.

$_FILES[‘userfile’][‘name’]is the file’s original name that is present on the client machine.

  1. How do we get the error in case we experience a problem in uploading a file?

The error code is present in $_FILES[‘userfile’][‘error’]  that is associated with the file that has been uploaded.

  1. How is it possible to modify a file’s maximum size that is to be uploaded?

The maximum size of a specific file that is to be uploaded can be changed by modifyingupload_max_filesize in php.ini.

  1. What is the meaning of $_ENV?

$_ENV can be defined as an associative array of variables that are sent to the existing PHP script through the method of environment.

  1. What is the meaning of $_COOKIE?

$_COOKIE can be defined as an associative array of variables that are sent to the existing PHP script with the help of HTTP Cookies.

  1. What is the meaning of “scope of variables?”

Scope of variables can be defined as the contexts within which they are defined. All PHP variables have only one scope for the most part. This one scope spans all the required as well as included files.

  1. State the difference between ‘LOGICAL AND’ and ‘BITWISE AND’ operator.

$a & $b: This represents the bits that are set both in $a and $b.

$a and $b: This will be TRUE if $a and $b both are TRUE.

  1. Describe the two fundamental string operators.

Concatenation operator or (‘.’) is the first-string operator that returns the concatenation of its left and right arguments. The second-string operator is (‘.=’)that appends the right argument to the left argument.

  1. What is the meaning of the array operator ‘===’?

$a === $b is TRUE if both $a and $b possess the same value/key pairs in an identical order and of identical types.

  1. State the difference between $a !== $b and $a != $b.

!== represents non-identity i.e. TRUE in the case of $a being unidentical to $b. != represents inequality i.e. TRUE in the case of $a being unequal to $b.

  1. How is it possible to ascertain if a specific PHP variable belongs to an instantiated object coming from a certain class?

In order to determine if a specific PHP variable belongs to an instantiated object coming from a certain class, ‘instanceof’ is used.

  1. What is the function of the goto statement?

You can place the goto statement to allow jumping inside a PHP program. A label points a target which is followed by a colon. A goto statement specifies the instruction that is followed by the target label.

  1. State the difference between Exception::getLine and Exception::getMessage.

Exception::getLine allows us to get the line in where the exception has taken place and Exception::getMessage allows us to get the Exception messages.

  1. What is the meaning of the expression Exception::_toString?

The expression Exception::_toString demonstrates the String representation of an exception.

  1. How can you parse a configuration file?

To parse a configuration file, the function of parse_ini_file() is usedto load the ini file that is mentioned in the filename.

  1. How is it possible to ascertain if a variable is set?

It is possible to ascertain if a variable is set by using the boolean function of isset, which helps in determining whether a variable is set and not NULL.

  1. State the difference between the functions stristr() and strstr().

The string function of strstr returns a part of the allString from OCC’s first occurrence to the end of the allString. It is a case-sensitive function. On the other hand, stristr() is similar to strstr(), only it is not case sensitive.

  1. State the difference between foreach and for.

You can express, as shown below:

for (expr1;  expr2; expr3)

You can execute the first expression at the beginning once. Expr2 can be evaluated in each iteration. The loop continues if it is TRUE and all the statements present inside for are executed. The execution of the loop comes to an end if the evaluation is FALSE. Test expr3 when each iteration ends. That said, foreach offers an easy and straightforward manner to iterate over arrays. It is used only with objects and arrays.

  1. Can we submit a form using a dedicated button?

You can use the function of document.form.submit()in order to submit the form.

  1. State the difference between eregi_replace() and ereg_replace().

The function of eregi_replace() resembles the function of ereg_replace(). The only difference between them is that the former ignores case distinction when it comes to matching alphabetic characters.

  1. Can you protect special characters when it comes to a query string?

Yes, you can protect special characters when it comes to a query string using the function of urlencode().

  1. State the three distinct class of errors that can take place in PHP.

The three class of errors that can take place in PHP are warnings (serious errors), notices (non-critical errors), and fatal (critical errors).

  1. State the difference between the characters\x34 and\034.

\x34 is hex 34 whereas \034 is octal 34.

  1. Can you extend the time of execution of a PHP script?

You can use the function of set_time_limit(int seconds) which will allow you to extend the time of execution of a PHP script. It is also pertinent to mention here that 30 seconds is the default limit.

  1. Can you destroy a cookie?

Yes, you can by setting a past expiration time on the cookie.

  1. Can you use the COM element in PHP?

Yes. You can use the COM element in PHP scripts as it is already given as a framework.

  1. Is it possible for you to share a single instance when it comes to a Memcache between many PHP projects?

Yes, you can share a single instance when it comes to a Memcache between many PHP projects. It is essential to understand that Memcache is nothing but a memory storage space. In addition to that, you can also run Memcache on several servers if you want. It is also possible for you to configure your client so that you can speak to a specific set of instances.Therefore, it is possible for you to run two distinct Memcache processes on a similar host. Yet, they are both completely independent. That said, in case you have partitioned all your data, it becomes crucialto know the precise instance from which to get the data or to put into.

  1. Describe how it is possible to update Memcached while making changes to PHP.

While making changes to PHP, you can update Memcache in two ways:

  • By clearing the cache proactively when an update or insert is made
  • By resetting the cachewhich is quite identical to the first method, only you reset the values after an update or insert instead of merely deleting the keys and then waiting for the subsequent request of data in order to refresh the cache.
  1. What is the meaning of public scope, private scope, protected scope, and static scope?

Public Scope represents classes, methods, and variables that are declared to be public and can be accessed by you from anywhere. Private Scope represents classes, methods, and variables that have been declared private and can only be accessed by the parent class. Protected Scope represents classes, methods, and variables that have been declared to be protected and can be accessed only by the child and parent classes. Finally, Static Scope represents the variable that has been declared to be static, and it is able to keep the value even if you lose the scope.

  1. Define PDO.

PDO stands for PHP Data Objects. PDO is a lightweight PHP extension. It uses a consistence interface in order to access the database. With the use of PDO, it becomes easy for a developer to switch between database servers without any hassle. That said, it does not support the entirety of the advanced features that are offered by the MySQL server.

Final Words

This was a comprehensive article with all the relevant PHP interview questions that you can come face to face with. With these questions in your corner, you can definitely count on an increase in your confidence level. Although a PHP interview can be pretty challenging, if you have a complete grasp of these questions, nothing will faze you at the time of the interview!