Welcome to PHP Interview Questions with answers and detailed explanations. These questions will help you in your preparation for technical interviews and online selection tests conducted during campus placement for freshers and job interviews for professionals.

What is PHP?

PHP is an acronym for “PHP: Hypertext Preprocessor” · PHP is a widely-used, open-source scripting language · PHP scripts are executed on the server. PHP allows writing dynamically generated web pages efficiently and quickly. The syntax is mostly borrowed from C, Java and Perl. PHP is free to download and use.

PHP interview questions for freshers

Who is known as the father of PHP?

Rasmus Lerdorf

What was the old name of PHP?

The old name of PHP was Personal Home Page.

What is the name of scripting engine in PHP?

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

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

What are the popular frameworks in PHP?

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

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

How a variable is declared in PHP?

A PHP variable is the name of the memory location that holds data. It is temporary storage.

$variableName=value;  

What are the different loops in PHP?

For, while do-while and foreach.

Differentiate between variables and constants in PHP

Few differences between variables and constants in PHP are given below:

VariablesConstants
The value of a variable can be changed during the execution.The constant value can’t be changed during script execution.
Variables require compulsory usage of the $ sign at the start.No dollar sign ($) is required before using a constant.
It is possible to define a variable by simple assignment.Constants can’t be defined by simple assignments. They are defined using the define() function.
The default scope is the current access scope.Constants can be accessed throughout without any scoping rules.

What is a session in PHP?

A session in PHP is a way to store information to be used across multiple pages of an entire website. The information is not stored on the user’s computer, unlike cookies. In a temporary directory on the server, a file will be created by the session where registered session variables and their values are stored. This information will be available to all pages on the site during that visit.

By default, session variables will last until the user closes the browser.

So Session variables hold single user information and are available to all pages in one application.

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

<?php  
Session_register($ur_session_var);  
?>

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.

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.

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:

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )  

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

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.

How to delete file in PHP?

The unlink() function is used to delete a file in PHP.

bool unlink (string $filename)      

How can you send email in PHP?

The mail() function is used to send email in PHP.

bool mail($to,$subject,$message,$header);    

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.

How to stop the execution of PHP script?

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

Explain PHP split() function.

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

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

$_SERVER["REMOTE_ADDR"];  

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.

What does PEAR stands for?

PEAR stands for “PHP Extension and Application Repository”. PEAR is a framework and repository for all of the reusable PHP components.

PEAR provides a higher level of programming for web developers. It contains all kinds of PHP code snippets and libraries. It also provides you with a command-line interface to automatically install packages.

Is PHP a case-sensitive language?

PHP can be considered as a partial case-sensitive language. The variable names are completely case-sensitive but function names are not. Also, user-defined functions are not case-sensitive but the rest of the language is case-sensitive.

For example, user-defined functions in PHP can be defined in lowercase but later referred to in uppercase, and it would still function normally.

What are the different types of variables present in PHP?

There are 8 primary data types in PHP which are used to construct the variables. They are:

  • Integers: Integers are whole numbers without a floating-point. Ex: 1253.
  • Doubles: Doubles are floating-point numbers. Ex: 7.876
  • Booleans: It represents two logical states- true or false.
  • NULL: NULL is a special type that only has one value, NULL. When no value is assigned to a variable, it can be assigned with NULL.
  • Arrays: Array is a named and ordered collection of similar type of data. Ex: $colors = array(“red”, “yellow”, “blue”);
  • Strings: Strings are a sequence of characters. Ex: “Hello InterviewBit!”
  • Resources: Resources are special variables that consist of references to resources external to PHP(such as database connections).
  • Objects: An instance of classes containing data and functions. Ex: $mango = new Fruit();

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

The main difference between echo and print in PHP are given below:

echoprint
echo can output one or more strings.print can only output one string and it always returns 1.
echo is faster than print because it does not return any value.print is slower compared to echo.
If you want to pass more than one parameter to echo, a parenthesis should be used.Use of parenthesis is not required with the argument list.

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.

Tell me some of the disadvantages of PHP

The cons of PHP are:

  • PHP is not suitable for giant content-based web applications.
  • Since it is open-source, it is not secure. Because ASCII text files are easily available.
  • Change or modification in the core behavior of online applications is not allowed by PHP.
  • If we use more features of the PHP framework and tools, it will cause poor performance of online applications.
  • PHP features a poor quality of handling errors. PHP lacks debugging tools, which are needed to look for warnings and errors. It has only a few debugging tools in comparison to other programming languages.

How can PHP and HTML interact?

PHP scripts have the ability to generate HTML, and it is possible to pass information from HTML to PHP.

PHP is a server-side language whereas HTML is a client-side language. So PHP executes on the server-side and gets its results as strings, objects, arrays, and then we use them to display its values in HTML.

This interaction helps bridge the gaps and use the best of both languages.

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

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 (__).

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.

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.

What does isset() function?

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

What are the methods to submit form in PHP?

There are two methods GET and POST.

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

What is the purpose of @ in PHP?

In PHP, @ is used for suppressing error messages. If any runtime error occurs on the line which consists @ symbol at the beginning, then the error will be handled by PHP.

Explain the importance of Parser in PHP?

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

You can parse PHP code with PHP using the token_get_all() function.

What are the different types of Array in PHP?

There are 3 main types of arrays that are used in PHP:

  • Indexed Array: An array with a numeric key is known as the indexed array. Values are stored and accessed in linear order.
  • Associative Array: An array with strings for indexing elements is known as the associative array. Element values are stored in association with key values rather than in strict linear index order.
  • Multidimensional Array: An array containing one or more arrays within itself is known as a multidimensional array. The values are accessed using multiple indices.

Explain the main types of errors.

The 3 main types of errors in PHP are:

  • Notices: Notices are non-critical errors that can occur during the execution of the script. These are not visible to users. Example: Accessing an undefined variable.
  • Warnings: These are more critical than notices. Warnings don’t interrupt the script execution. By default, these are visible to the user. Example: include() a file that doesn’t exist.
  • Fatal: This is the most critical error type which, when occurs, immediately terminates the execution of the script. Example: Accessing a property of a non-existent object or require() a non-existent file.

What are traits?

Traits are a mechanism that lets you create reusable code in PHP and similar languages where multiple inheritances are not supported. It’s not possible to instantiate it on its own.

A trait is intended to reduce the limitations of single inheritance by enabling a developer to reuse sets of methods freely in many independent classes living in different hierarchies of class.

How does the ‘foreach’ loop work in PHP?

The foreach statement is a looping construct that is used in PHP to iterate and loop through the array data type.

This process is repeatedly done until the end of the array has been reached.

The syntax for using the foreach statement in PHP is given below:

foreach($array as $value)
{
   Code inside the loop;
}

What is the most used method for hashing passwords in PHP?

The crypt() function is used for this functionality as it provides a large number of hashing algorithms that can be used. These algorithms include sha1, sha256, or md5 which are designed to be very fast and efficient.

What is the difference between the include() and require() functions?

include() function

This function is used to copy all the contents of a file called within the function, text wise into a file from which it is called.

When the file is included cannot be found, it will only produce a warning (E_WARNING) and the script will continue the execution.

require() function:

The require() function performs same as the include() function. It also takes the file that is required and copies the whole code into the file from where the require() function is called.

When the file is included cannot be found, it will produce a fatal error (E_COMPILE_ERROR) and terminates the script.

What are cookies? How to create cookies in PHP?

A cookie is a small record that the server installs on the client’s computer. They store data about a user on the browser. Each time a similar PC asks for a page with a program, it will send the cookie as well.

By default, cookies are URL particular. For example, Gmail cookies are not supported by Yahoo and vice versa. Cookies are temporary and transitory by default. Per site 20 cookies can be created in a single website or web app. 50 bytes is the initial size of the cookie and 4096 bytes is the maximum size of the cookie.

In PHP, we can create cookies using the setcookie() function:

setcookie(name, value, expire, path, domain, secure, httponly);

Here name is mandatory and the remaining parameters are optional.

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

What is the meaning of ‘escaping to PHP’?

Escaping a string means reducing ambiguity in quotes used in that string.

For example, when you’re defining a string, you surround it in either double quotes or single quotes:
“Hello, InterviewBit.” 

But what if I include double quotes within the string?
“Hello “InterviewBit.”” 

Now I have ambiguity – the interpreter doesn’t know where does my string end. If I want to keep my double quotes, I have various options. I could use single quotes around my string:
‘Hello “InterviewBit.”‘ 

Or I can escape my quotes:
“Hello \”InterviewBit.\”” 

Any quote that is preceded by a slash is escaped and understood to be part of the value of the string.

Explain Path Traversal

Path traversal makes use of this symbol to operate the web application file. The attacker can reveal 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 to secret passwords, tokens, and other sensitive information stored in the files.

Path Traversal is also called “Directory Traversal”. It allows the attacker to exploit vulnerabilities present in the web file under attack.

Let’s take a simple example. Consider we have a “Show File” button that opens up some URL.

This technique is also called a dot-dot-slash attack, because it usually uses the special characters ../ (or \.. on Windows) to climb to a higher-level directory.

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

The final keyword in a declaration of the method indicates that the method cannot be overridden by subclasses. A class that is declared as final cannot be subclassed.

This is especially useful when we are creating an immutable class like the String class. Only classes and methods may be declared final, properties cannot be declared as final

PHP Interview Questions For Experienced

PHP & MySQL Interview Questions

Free PDF Download: PHP Interview Questions & Answers

Download PDF: PHP Interview Questions & Answers