Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Interview questions about PHP 2022

PHP stands for PHP: Hypertext Preprocessor is a widely used open-source server-side scripting language especially suited for creating dynamic websites and mobile APIs.

PHP supports many databases like MySQL, Solid, PostgreSQL, Oracle, Sybase, generic ODBC, etc. PHP code is embedded within HTML.

It is used to manage dynamic content, session tracking, databases, and also to build an entire e-commerce site.
By default, most of the web hosting servers support PHP and thus it contributes to cost-effectiveness.

Scope of PHP

PHP stands as one of the top languages because of its ability to have a large impact on the outcome with very little code. This amount of efficiency has been the requirement for the past few years in the industry.

On seeing this, companies are investing a good amount of money in hiring proficient PHP developers to fit these shoes and work effectively.

Today, this article will walk you through the most commonly asked PHP interview questions for freshers and experienced in the industry.

Crack your next tech interview with confidence!
Take a free mock interview, get instant feedback and recommendation
Attempt Now
PHP Interview Questions For Freshers

1. Differentiate between variables and constants in PHP

Few difference between variables and constants in PHP are given below:
Variables Constants
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.

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

When you work with an application, you open it, do some modifications, and then you close it. This is much like a Session. The computer knows who you are. It knows when the application is started and ended by you.

But on the internet, the webserver does not know who you are or what you do, because the HTTP address doesn’t maintain a state. This problem is solved using session variables by storing user information to be used across multiple pages (e.g. username, favorite color, etc).

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.

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


4. Explain the difference between $message and $$message.

The main difference between the $message and $$message is given below:
$message $$message
$message is a regular variable. $$message is a reference variable.
It has a fixed name and stores a fixed value. It stores data about the variable.
Data stored in $message is fixed. The value of the $$message can change dynamically as the value of the variable changes.

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

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

Types of PHP Variables

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

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

The following two rules are needed to be followed while naming a PHP variable:
  • A variable must start with a dollar symbol, followed by the variable name. For example: $price=100; where price is a variable name.
  • Variable names must begin with a letter or underscore.
  • A variable name can consist of letters, numbers, or underscores. But you cannot use characters like + , – , % , & etc.
  • A PHP variable name cannot contain spaces.
  • PHP variables are case-sensitive. So $NAME and $name both are treated as different variables.

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

The main difference between echo and print in PHP are given below:
echo print
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.

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

Intermediate Interview Questions

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

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

12. Explain the importance of Parser in PHP?

A PHP parser is 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.

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

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

Indexed Array

An array with a numeric key is known as the indexed array. Values are stored and accessed in linear order.

Indexed Array

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.

Associative Array

Multidimensional Array

An array containing one or more arrays within itself is known as a multidimensional array. The values are accessed using multiple indices.

Multidimensional Array

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

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

16. Does JavaScript interact with PHP?

JavaScript is a client-side programming language, whereas 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.

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

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

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

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

20. 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. It is used to identify a user and is embedded on the user’s computer when they request a particular page. Each time a similar PC asks for a page with a program, it will send the cookie as well.

After verifying the user’s identity in encrypted form, cookies maintain the session id generated at the back end. It must reside in the browser of the machine. You can store only string values not object because you cannot access any object across the website or web apps.

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

21. What is the difference between ASP.NET and PHP?

The main difference between ASP.NET and PHP are given below:
ASP.NET PHP
A web application framework. A server-side scripting language.
It is designed for use on Windows. It is Platform independent
Code is compiled and executed. Interpreted mode of execution.
It has a license cost associated with it. PHP is open-source and freely available.

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

The PHP parsing engine needs a way to differentiate PHP code from other page elements. The mechanism to achieve this is known as ‘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, InterviewPreparation.”

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

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 “InterviewPreparation.”‘

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

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

23. Explain Path Traversal

Path traversal is a form of attack to read into the files of a web application. ‘../’ (dot-dot-sequences) is a cross-platform symbol to go up in the directory. 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.

For a classic directory traversal attack, the attacker may try to access the system file /etc/passwd (assuming a UNIX/LINUX system). If the application receives the value of the file parameter from the URL and passes it to a system call, it would traverse the relative path ../../etc/passwd starting from /var/www and ask the system to load the password file.

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.

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

25. What are the steps to create a new database using MySQL and PHP?

The 4 main steps used to create a new MySQL database in PHP are given below:
  • A connection establishment is done to the MySQL server using the PHP script.
  • 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 will be executed one after the other.

26. What is the use of session_start() and session_destroy() functions in PHP?

The session_start() function is used to start a new session. Also, it can resume an existing session if it is stopped. In this particular case, the return will be the current session if resumed.

Syntax:

session_start();

The session_destroy() function is used to destroy all of the session variables as given below:


session_start();
session_destroy();
?>

27. What is Memcache and Memcached in PHP? Is it possible to share a single instance of a Memcache between several projects of PHP?

Memcached is an efficient caching daemon designed specifically for decreasing database load in dynamic web applications. Memcache offers a handy procedural and object-oriented interface to Memcached.

Memcache is a memory storage space. We can run Memcache on a single or several servers. Therefore, it is possible to share a single instance of Memcache between multiple projects.

It is possible to configure a client to speak to a separate set of instances. Therefore, it is allowed to run two different Memcache processes on the same host. Despite running on the same host, both of such Memcache processes stay independent, unless there is a partition of data.

28. What are the different ways of handling the result set of MySQL in PHP?

There are 4 ways of handling the result set of MySQL in PHP. They are:
  • mysqli_fetch_array(): Returns the current row of the result set as an associative array, a numeric array, or both.
  • mysqli_fetch_assoc(): Returns the current row of the result set as an associative array.
  • mysqli_fetch_object(): Returns the current row of a result set, as an object.
  • mysqli_fetch_row(): Returns result row as an enumerated array.

29. How to connect to a URL in 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. cURL make use of libcurl(client-side URL Transfer Library) which supports many protocols like FTP, FTPS, HTTP/1, HTTP POST, HTTP PUT, HTTP proxy, HTTPS, IMAP, Kerberos etc. It allows you to connect to a URL and retrieve and display information from that page – like the HTML content of the page, HTTP headers, and their associated data, etc.

Steps for connecting with URL using PHP cURL POST are given below:

  • Initialize cURL session.
  • Define your URL where you want to post the request. We can directly enter this URL into the URL section inset option parameter or we can assign it to an object.
  • Now, define the cURL options that you want to execute with the post option.
  • After setting all the functions then it’s time to execute our cURL.
  • After this, close the cURL and echo your object to check their response.
//Step 1 To initialize curl
     $ch = curl_init();
//Step 2 To set url where you want to post
     $url = ‘http://www.localhost.com’;
//Step 3 Set curl functions which are needs to you
     curl_setopt($ch,CURLOPT_URL,$url);
     curl_setopt($ch,CURLOPT_POST,true);
     curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
     curl_setopt($ch,CURLOPT_POSTFIELD,’postv1 = value1&postv2 = value2’);
//Step 4 To execute the curl
     $result = curl_exec($ch);
//Step 5 Close curl
     curl_close($ch);

30. How to create API in PHP?

API stands for Application Programming Interface. It defines the functions and variables. Communication between the database via PHP extensions is handled by API.

Now, REST API is the web architecture that uses HTTP protocol for exchanging data between two functions that means your application or system. Now, let us have a look at how to create REST API in PHP by considering the example of accessing data from a database using PHP script.

Step 1 – Create a database: To create a database run the query given below:

CREATE DATABASE phptest;

Step 2 – Create a table: After creating a database, you have to create a table with dummy data. To create a table run the query given below:

CREATE TABLE IF NOT EXISTS `transactions` 
(
   `id` int(20) NOT NULL AUTO_INCREMENT,
   `order_id` int(50) NOT NULL,
   `amount` decimal(9,2) NOT NULL,
   `response_code` int(10) NOT NULL,
   `response_desc` varchar(50) NOT NULL,
   PRIMARY KEY (`id`),
   UNIQUE KEY `order_id` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ;

Step 3 – Create a Database Connection: Create a db.php file and paste the below-given database connection in it. Make sure to update these credentials with your database credentials.

// Enter your Host, username, password, database below.
$con = mysqli_connect("localhost","root","","phptest");
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    die();
}
?>

Step 4 – Create a REST API File: Create an api.php file and copy the following script in it.


header("Content-Type:application/json");
if (isset($_GET['order_id']) && $_GET['order_id']!="") 
{
include('db.php');
$order_id = $_GET['order_id'];
$result = mysqli_query($con,
       "SELECT * FROM `transactions` WHERE order_id=$order_id");
if(mysqli_num_rows($result)>0)
       {
    $row = mysqli_fetch_array($result);
    $amount = $row['amount'];
           $response_code = $row['response_code'];
           $response_desc = $row['response_desc'];
    response($order_id, $amount, $response_code, $response_desc);
    mysqli_close($con);
}
       else
       {
     response(NULL, NULL, 200,"No Record Found");
}
}
else
{
response(NULL, NULL, 400,"Request is invalid");
}
function response($order_id,$amount,$response_code, $response_desc)
{
$response['order_id'] = $order_id;
$response['amount'] = $amount;
$response['response_code'] = $response_code;
       $response['response_desc'] = $response_desc;
$json_response = json_encode($response);
echo $json_response;
}
?>

The above code will accept the GET request and return output in the JSON format.

Now you can get an output as given below:

Output File

This is how you can create REST API in PHP.

31. What is PDO in PHP?

PDO stands for PHP Data Object. PDO is a set of PHP extensions that provide a core PDO class and database, specific drivers. The PDO extension can access any database which is written for the PDO driver. There are several PDO drivers available which are used for FreeTDS, Microsoft SQL Server, IBM DB2, Sybase, Oracle Call Interface, Firebird/Interbase 6 and PostgreSQL databases, etc.

It gives a lightweight, vendor-neutral, data-access abstraction layer. Hence, no matter what database we use, the function to issue queries and fetch data will be the same. And, it focuses on data access abstraction instead of database abstraction.

32. Differentiate between GET and POST

The difference between GET and POST are given below:
GET POST
GET method is used for requesting data from a specified resource. POST is used for sending the data to the server as a package in a separate communication with the processing script.
Data is sent in the form of URL parameters which are strings of name-value pairs separated by ampersands(&) Data sent through the POST method will not be seen in the URL
GET method cannot be used for sending binary data like images or word documents The POST method can be used to send ASCII as well as binary data like images and word documents
This method must not be used if you have any sensitive information like a password to be sent to the server. Sensitive information can be sent using this method.
It can be used for submitting the form where the user can bookmark the result. Submissions by form with POST cannot be bookmarked.
You can use this method only for data that is not secure. Data sent through this method is secure.
GET method is not safer since parameters may be stored in web server logs or browser history. POST method is safer than GET because the parameters are not stored in web server logs or browser history.

33. Explain type hinting in PHP

In PHP, type hinting is used to specify the expected data type (arrays, objects, interface, etc.) for an argument in a function declaration. It was introduced in PHP 5.

Whenever the function is called, PHP checks if the arguments are of a user-preferred type or not. If the argument is not of the specified type, the run time will display an error and the program will not execute.

It is helpful in better code organization and improved error messages.

Example usage:

//sendEmail() function argument $email is type hinted of Email Class. It means to call this function you must have to pass an email object otherwise an error is generated.
function sendEmail (Email $email)
    {
      $email->send();
    }
?>

34. How to terminate the execution of a script in PHP?

To terminate the execution of the script in PHP, the exit() function is used. It is a built-in function that outputs a message and then terminates the current script.

The message which you want to display is passed as a parameter to the exit() function. Script termination will be done by this function after displaying the message. It is an alias of die() function. It doesn’t return any value.

Syntax: exit(message)

Where the message is a parameter to be passed as an argument. It defines a message or status.

Example: The code given below will print a message and exit the current script.

$site = "https://www.interviewbit.com//";
fopen($site,"r")
or exit("Unable to connect to $site");
?>

The post Interview questions about PHP 2022 appeared first on Interview Preparation.



This post first appeared on Interview Preparation, please read the originial post: here

Share the post

Interview questions about PHP 2022

×

Subscribe to Interview Preparation

Get updates delivered right to your inbox!

Thank you for your subscription

×