PHP Interview Questions and Answers 2023

Top PHP Interview Questions and Answers

PHP is a widely-used general-purpose scripting language that can be embedded into HTML. It is quite popular for web development as well because it can generate dynamic content.

 

It is an open-source scripting language. PHP code is executed on the server and then the subsequent plain HTML is sent to the client/browser, without exposing the actual code. It is so popular and powerful that applications like WordPress, Drupal, and Facebook are written in PHP.

 

In this article, we covered Basic PHP Interview Questions, Intermediate PHP Interview Questions, and Advanced PHP Interview Questions.

 

Basic PHP Interview Questions

  1. In Which areas is PHP primarily used?
  2. Why is PHP so popular?
  3. Do you need to compile PHP programs before execution like C++?
  4. What are magic methods in PHP?
  5. What is the application of the symbol "@" in PHP?
  6. List top PHP CMS platforms.
  7. What is the difference between $message and $$message?
  8. What are some drawbacks of PHP?
  9. Which rules are used for naming PHP variables and constants?
  10. Is it possible to perform multiple inheritances in PHP?
  11. Share some commonly used array functions.
  12. What do you understand about PEAR in PHP?
  13. State the differences between variables and constants in PHP.
  14. Explain different types of PHP variables.
  15. How can we compare objects in PHP?
  16. Mention differences between print and echo.

 

Intermediate PHP Interview Questions

  1. What are Headers() in PHP?
  2. What is the difference between session and cookie in PHP?
  3. What are the different frameworks in PHP?
  4. Which method is used for hashing passwords in PHP?
  5. How does PHP differ from ASP.NET?
  6. How is Final Class different from Final Method?
  7. How does PHP interact with HTML?
  8. What do you mean by htaccess? Discuss its application.
  9. How do you register a variable in PHP session()?
  10. What do you mean by Memcache?
  11. Explain the different types of arrays in PHP.
  12. Explain the different error types in PHP
  13. What is a random function in PHP?
  14. What are include() and require() functions in PHP?
  15. How can we create cookies in PHP?
  16. What is ‘escaping to PHP’?
  17. How to redirect a page in PHP?
  18. Explain $_SESSION in PHP?

 

Advanced PHP Interview Questions

  1. How require() function differs from require_once?
  2. What is the difference between session_start() and session_destroy() function?
  3. What are the major steps for creating a new database using MySQL and PHP?
  4. What is type hinting in PHP?
  5. How Get method is different from the Post method?
  6. How can you create a simple REST API in PHP?
  7. How do you create cookies in PHP?
  8. Discuss runtime exceptions and compile time exceptions.
  9. Can you perform password encryption in PHP?
  10. How can we terminate the script execution in PHP?
  11. How can we connect to a URL in PHP?
  12. Why is callback used in PHP?
  13. Will it be possible to extend the execution time of PHP?
  14. Explain major differences between for loop and foreach loop.

Final Thought

 

Basic PHP Interview Questions and Answers

 

1. In Which areas is PHP primarily used?

PHP is primarily used in designing and developing web applications such as websites, Content Management Systems (CMS) systems, Customer Relationship Management (CRM) systems, and other similar systems. PHP offers excellent support for building small and large mobile applications, web products, and databases. The server-side application logic of PHP enables it to dominate the tech industry. Some great examples of tech startups and companies which have designed their websites using PHP are Facebook, Wikipedia, Slack, Tumblr, MailChimp, WordPress, and Etsy.


Explore our careers section for PHP Job Openings

 

The below five points illustrate why PHP is so popular:

  • PHP scripts are open-source scripting languages and are directly executable on the server. It allows you to integrate logic while building web page content and managing it. Also, you can easily download its compilers and extensions.
  • PHP has a cross-platform feature which means you can run applications on an array of operating systems like Windows, Mac OS, Unix, Linux and browsers
  • PHP is a flexible and compatible scripting language. You can use this with all modern servers like Apache, Netscape, Microsoft IIS, Tornado, Xitami, Caudium, and iPlanet.
  • PHP offers numerous out-of-the-box extensions, resources, and functionalities so you can quickly interact with the databases and use various back-end databases such as MongoDB, MySQL, and PostgreSQL.
  • PHP codes are reusable, which allows you to reuse those codes and save your time and effort in any SDLC process.

 

3. Do you need to compile PHP programs before execution like C++?

No, you don't need to compile PHP programs before execution, like C++, because PHP is an interpreted language. This interpretation feature allows you to make changes in the source code and test the changes without compiling the codes into binary forms. This makes for fasterPHP code execution with high-performance outcomes. The in-built memory management feature also helps to negate the impact of the additional runtime load overhead associated with the interpreter.

 

4. What are magic methods in PHP?

Any function that starts with two underscores (__) is known as PHP's magic function or method. Here, the symbols (2 underscores) are triggers to respond to the PHP events. These methods reside in the PHP class. Programmers are free to define the method as per their requirements.

Method name
__construct()
__destruct()
__call()
__callstatic()
__get()
__set()
__isset()
__unset()
__sleep()
__wakeup()
__toString()
__invoke()
__clone()
__debuginfo()

 

5. What is the application of the symbol "@" in PHP?

The main application of PHP's symbol "@" is to suppress the error message. You can utilize this symbol to ignore the expression which usesthis symbol as a prefix. In other words, PHP manages error if it happens in the statement started with @.

 

6. List top PHP CMS platforms.

A user-friendly CMS platform can help you make excellent and functional websites and web apps. The right CMS plays a critical role in developing applications.

  • WordPress
  • Magento
  • Drupal
  • Joomla
  • Opencart
  • OctoberCMS
  • ExpressionEngine
  • Craft CMS
  • PyroCMS
  • TYPO3

Click here for more info on each CMS platform.

 

7. What is the difference between $message and $$message?

$message $$message
It is a standard variable that stores variable data. It is a reference variable that stores data of variables.
It stores afixed value. It does not store anyfixed value. Thismeans you can change the value.

 

8. What are some drawbacks of PHP?

In spite of all the benefits, PHP does have some drawbacks.

  1. It is suitable for small to medium size web applications, not for big content-based web projects.
  2. There might be Security issues because it is an open-source language. When a new and inexperienced person develops web applications using PHP, it also increases the chances of security vulnerabilities.
  3. There is a limited number of specialized features in PHP. For instance, unlike Python, it does not support libraries integrating machine learning.

Check this link to get the answer in detail.

 

9. Which rules are used for naming PHP variables and constants?

Like all other programming languages, PHP follows the standard naming rules to define variables and constants.

  • Every variable must start with the dollar ($) followed by either a letter or underscore. However, do note that you may not use other special characters besides the listed.
  • Names cannot include spaces.
  • You can use letters, understands, or numbers in the names but not special characters like &, +, -. %.
  • Variables are case-sensitive. As such, you should take careful note of this when naming variables.

 

10. Is it possible to perform multiple inheritances in PHP?

No, it is not possible to perform multiple inheritances in PHP. However, shouldyou want to use this feature, you can use traits rather than classes. Traits are special classes. You cannot initiate traits but extend multiple traits at the same time.


Test your PHP coding skills here

 

11. Share some commonly used array functions.

PHP offers various built-in array functions to support multiple operations, including searching, sorting, merging, and many more. The following table highlights some crucial functions.

Array functions What it does
max() Find the maximum value in the array
min() Find the minimum value in the array
range() Generates a number range as an array
sort() Arrange the array elements
explode() Splits the string into array elements
Implode() Join array elements into array
count() Counts the array elements
array_merge() Combine two arrays into one array

You can click here to learn more about array functions.

PHP follows the OOPs concepts. Click this link to know more about OOPs.

 

12. What do you understand about PEAR in PHP?

PEAR means PHP Extension and Application Repository. It is a community-driven framework/library which provides:

  • A structured library of PHP code.
  • Standard reusable components.
  • Standard coding style.
  • Framework for distribution of code and package maintenance.

 

13. State the differences between variables and constants in PHP.

Variables Constants
Variables can change values during program execution. Constants remain unchanged(constant) during program execution.
Use of a dollar sign ($) is required before their name. Use of a dollar sign($) is not required before their name.
E.g., $book = “PHP Interview Questions For Beginners”; E.g., define(“book”, ”PHP Interview Questions For Beginners”);
Can be defined by using an assignment(=) operator. Cannot be defined by using an assignment(=) operator. Requires use of define() function to define it.

 

14. Explain different types of PHP variables.

  • Integer: It is a non-decimal signed number(positive or negative).
  • Float (Double): It is a decimal number or exponential number.
  • Boolean: It can be either True or False.
  • String: It is a string of characters.
  • Array: It is a collection of similar types of data stored under a single name.
  • Object: It has methods and data as a single unit called class.
  • NULL: It is a special data type which can store only one value- NULL.
  • Resource: It is a special data type which stores reference to external resources.

 

15. How can we compare objects in PHP?

There are two ways to compare objects in PHP:

  • Comparison operator(==)

Checks if two objects are instances of a class with the same property values, i.e. same attributes and values.

 

  • Identity operator(===)

Checks if two objects are referencing the same instance of a class.

 

The below table summarises the return value of both operators:

Deciding Factor Comparison operator(==) returns Identity operator(===) returns
Two objects referencing the same object instance. True True
Objects with the same properties True False
Objects with different properties False False

 

16. Mention differences between print and echo.

print echo
Outputs only one string Outputs one or more strings
Syntax: print ($argument1) Syntax: echo ($argument1, $argument2...)
Slower than echo Faster than print
Returns 1 Returns nothing
Parentheses are not required to pass more than one value Parentheses are used for passing more than one value

Read more with examples here.


Explore our careers section for PHP Job Openings

 

Intermediate PHP Interview Questions and Answers

 

17. What are Headers() in PHP?

The in-built header() function in PHP is used to send a raw HTTP header. As we know, any HTTP function's primary purpose is to manipulate the information sent to the client or browser by the web server before the output has been sent. Thus, the HTTP header provides the required information about the object sent in the message body.

You should consider the following points beforeusing Header().

Call it before any actual output is sent from any resource. Because reading code with functions like include, require, or file access has empty lines or spaces become output before Header() is called.

 

Syntax:

Header(string $header, bool $replace = true, int $response_code = 0)

Here (Know each parameter as follow:)

  • String – A mandatory parameter that represents string which specifies the header string to send
  • Replace – An optional parameter to specify whether the header should replace previous or add a second header.
  • Response_code – Another optional parameter is used for forcing the HTTP response code to the specified value.

 

A session and cookie both aim to store the information somewhere. Below, we list the differences between the both of them:

Session Cookie
Session stores the information on the server. By doing this, it allows you to use the different pages of the website to store sessions. The cookie stores the information on the user's specific device or simple words on the browser. It is a small text file.
A session starts when the user logs into a specific network application/program and logs out. It means all data in the session is lost whenever the web browser gets closed. Whenever a user visits the website for the first time, it sends cookies (data packets) to the user's device to collect information. You can store a cookie for weeks, months, or years.
Session values are more secure than cookies as they have been stored in an encrypted form and decoded only on the server side. Cookies are less secure as they are stored in text form, and anyone can read them.

 

19. What are the different frameworks in PHP?

PHP frameworks permit you to build PHP web applications using available built-in code libraries. Faster development time, less coding, libraries, greater security, and best practices are some of the reasons why frameworks are particularly attractive for web development. Here are some of the popular and widely-used frameworks:

  • Laravel
  • Symfony
  • CodeIgniter
  • Zend Framework
  • Yii Framework
  • CakePHP
  • Slim
  • Phalcon
  • FuelPHP
  • Fat-free framework

Click this link to learn all these frameworks and other factors that must be considered while choosing frameworks.

 

20. Which method is used for hashing passwords in PHP?

In PHP, password_hash() creates a password hash. It creates a new password hash using a robust one-way hashing algorithm.

Syntax:

Password_hash(string $password, string|int|numm $algo, array $options = []): string

Here are supporting algorithms:

  • PASSWORD_DEFAULT – It uses the bcrypt algorithm to create the hash.
  • PASSWORD_BCRYPT – It uses the CRYPT_BLOWFISH to create the hash.
  • PASSWORD_ARGON2I – It uses Argon2i hashing algorithm to create the hash.
  • PASSWORD_ARGON2ID – It uses Argon2id hashing algorithm to create the hash.

 

21. How does PHP differ from ASP.NET?

PHP ASP.NET
It is an open-source and server-side programming language for web application development. It is an open-source and server-side web application development tool and framework.
It is an independent platform, and you can use it on various platforms. You can use it only on Windows.
It is best to use this language for developing websites for small to medium business websites, application systems and independent software vendors. It is best to use it to design enterprise-level websites and systems, ERP apps, and console applications.
It is easy to learn and implement. It is a little bit tough to learn and implement.
It is free and open-source; hence question marks can be raised on how secure apps developed with it are It is expensive, which makes the product implementation expensive too.

 

22. How is Final Class different from Final Method?

Final is one of the essential concepts of the object-oriented programming language. It is used in inheritance implementation. Whether its Final Class or its Final Method, the keyword determines the respective class or method. When you do not want to inherit classes or avoid overriding functions, you need to use the "final" keyword. The same applies to PHP.

Final Class

When the keyword "Final" is used in the class, it cannot be extended. This results in a class with zero child classes.

Final Method

When the keyword "Final" is used in the method, the method in child classes cannot be overridden. This means that the definition of the method cannot be changed once it is set.

To summarize, Final classes cannot be extended, whereas Final methods cannot be altered!

For more details, please refer to the official documentation.

 

23. How does PHP interact with HTML?

The fact is that PHP and HTML can easily interact with each other because PHP can quickly generate HTML, whereas HTML can pass information to PHP. There are many ways through which PHP can interact with HTML. But, you can divide it into two main ways.

  • The first way is to embed the PHP code in the HTML file itself with the .html extension.
  • The second way is to merge the PHP and HTML tags in .PHP files.

Both are simple to implement; however you should take note of functions while integrating.

 

24. What do you mean by htaccess? Discuss its application.

The htaccess or "Hypertext Access" is a configuration file. The core usage of this file is to set server configurations. It can override the specific settings of the Apache Web Server or execute other functions which might impact the website. Simply put, the file controls user access rights to specific files and directories. Here are some of its applications:

  • Make changes to the website, such as authorization changes, error handlings, user permissions, and redirects to the specific URL address.
  • Redirect the "www" to "non-www" and vice versa orpermanent/temporary redirection to a specific addressthrough 301 redirects.
  • Block a specific IP address or ranges of IP addresses
  • Customize the error page (404 not found) by defining your custom errors
  • Perform authentication to restrict folder access
  • Deny access from specific domains.

To execute any of these, all you have to do is code it into the .htaccess file.

 

25. How doyou register a variable in PHP session()?

You can register a variable in PHP session() using the session_register() function. You must pass 'username' to the function by setting a value in $_SESSION Global. By doing this, you can avoid the problem of deprecation as well.

Don't use the function like this:

$name = ‘dummy’;

Session_register(name);

Use the function like this

$_SESSION[‘name’] = ‘dummy’;

 

26. What do you mean by Memcache?

Memcache is a memory caching system. Memcache module provides an object-oriented and procedural interface to Memcached, another distributedmemory caching system. Memcache primarily decreases database load in dynamic web applications by caching the database queries and reducing the number of database calls.

This distributed memory caching system increases the website speed by storing the database objects in the dynamic memory. Doing this reduces the pressure on a server whenever an external data source makes a read request.

Why it is preferred:

  • Decreases the web pages response time
  • Enhances the user’sexperience by improving on the data access time

If you want to utilize this feature on PHP, enable the PHP Memcache extensions and configure it from the source. Get complete setup instructions and a step-by-step guide here.

Practicing your technical skills is a must. Here's a link where you can practice your programming skills.


Test your PHP coding skills here

 

27. Explain the different types of arrays in PHP.

PHP has three types of arrays:

  • Indexed/ Numeric: The indexes are numeric and arrays are linear.
Example: 

$organs[0]="heart";   

$organs[1]="lungs";   

$organs[2]="liver";   

$organs[3]="kidneys";

 

  • Associative: The index is a string and arrays are not linear. Each value stores named keys(user-defined strings). Which is in the form of key-value pairs.
Example: 

$temperature["London"]="68";   

$temperature["Frankfurt"]="73";   

$temperature["Rome"]="85";

 

  • Multidimensional: Each array element stores a single or multiple arrays. It is an array of arrays.
Example: 

$salary = array( 

            "Rob" => array ( 

            "Jan" => 45000, 

            "Feb" => 38000,  

            "Mar" => 41000 

            ), 

     

            "Sarah" => array ( 

            "Jan" => 48000, 

            "Feb" => 49000, 

            "Mar" => 47000 

            ) 

      );

 

28. Explain the different error types in PHP

  • Fatal Error

It is the most serious type of error, which causes program termination. The compiler compiles the code but cannot catch such fatal errors.

Example: Using an undeclared function in the program.

 

  • Warning

They do not interrupt the program run, however, they are also generated when some file is missing. They are less serious than a fatal error.

Example: Calling a missing file.

 

  • Notice

It is less serious than a warning and is non-critical. It allows execution of the program.

Example: Script is accessing an undefined variable

 

  • Parse or Syntax Error

Happens due to incorrect syntax in the code, it is a very common error. Compiler catches these types of errors during compilation.

Example: missed semicolon, parentheses etc.

 

29. What is a random function in PHP?

The rand() function in PHP is used to generate random integers. The return value of the function is an integer.

Syntax:

  • rand(): Without any limit, it generates integers between zero and getrandmax() function.
  • rand(min, max): Generates random numbers within the specified limit.

Example:

If you want to generate random numbers between 1 to 100,  then use the rand function as below. It will generate random numbers inclusive of 1 and 100.

rand(1,100)

NOTE: The range provided by min and max should be within getrandmax(),

i.e.,( max-min) <= getrandmax(). Otherwise poor quality random numbers will be returned.

 

30. What are include() and require() functions in PHP?

These functions help us to include PHP files in the code before execution. The include() and require() functions provide file inclusion property, which helps to reduce the redundant coding effort and size. The PHP code files which are already existing can be included(copied) in the current code file by these two functions.

Syntax: 

<?php include 'filename.php';?> 
<?php require 'filename.php';?>

 

Difference: include() and require() functions in PHP

include() require()
Use it when the file is not required by the code. Because the script will continue execution if the file is not found. Use it when the file is required by the code. Because the execution will be terminated if the file is not found.
If the file is not found, it will produce a warning E_WARNING and the script execution will continue. If the file is not found, it will produce a fatal error E_COMPILE_ERROR, and stop the script.

 

Note: The best scenarios to use require() function are for files having library functions, configuration variables such as database configuration etc. Basically, the files which are mandatory or essential for the successful code run.

Examples here.

 

31. How can we create cookies in PHP?

We can use the setcookie() function to create cookies in PHP.

Syntax:

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

Returns TRUE or FALSE based on success or failure.

Example code: 

<?php 

$cookie_name = "user"; 

$cookie_value = "Jenny Klaus"; 

setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day 

?>

 

32. What is ‘escaping to PHP’?

Escaping is used in PHP to reduce the ambiguity of program interpreters.

 

For example, there is a string which is mentioned in the program, we will write it within double quotes as - “I am a String”. Now, imagine we want to put more double quotes into it as- “I am a ”String””. This will cause ambiguity to the interpreter since it will not know where the string is ending.

 

For such cases, we use escape sequences using a backslash (\). We will place a backslash before the double quote, where we want to stand it for itself. In this way, the interpreter will process the double quotes as is and not as the end of the string.

 

Example: “I am a \”String\””

 

33. How to redirect a page in PHP?

PHP redirect is a server-side solution to redirect the user to a different page using the header() function.

  • It is a secure and fast process of redirection from one page to another.
  • The header function should be written before HTML and DOCTYPE tags.
  • Syntax: header( $header, $replace, $http_response_code )
  • The response codes are set to provide more information about redirection.
    • 302: If not specified, the default value of the response code is 302, which is temporary redirection.
    • 301: Permanent redirection
Example: 

<?php 

header("Location: http://www.redirect.com/another-page.php"); 

exit(); 

?>

 

Without a header() function the page can be redirected using JavaScript. However, this is going to be slower as compared to the header() function.

 

34. Explain $_SESSION in PHP?

PHP creates a session to store and pass the information between pages. This session data is stored on the server, unlike cookies which get stored on the user's system.

 

Available session variables are stored in a superglobal associative array called $_SESSION in PHP.

 

They are stored as a key-value pair in the array. These values are available for access during the lifetime of a session.

 

We can set and get the session variables using this array.

  • Example set variable:

$_SESSION["login"] = "Claura"; 

 

  • Example get variable:

echo $_SESSION["login"]; 


Explore our careers section for PHP Job Openings

 

Advanced PHP Interview Questions and Answers

 

35. How require() function differs from require_once?

The primary purpose of both functions is to include PHP files into other PHP files. But, both functions have a minor difference. Let's understand that difference:

Require(): This function allows us to include files multiple times in a single PHP file. You have to take care of the file's location because if the function does not find the file on the mentioned locations, it throws error and halts the execution.

Require_once(): The function allows us to include files multiple times in a single PHP file, but the PHP server includes that file only once. In simple terms, after including a file the first time, if you again include it, the compiler ignores it. Just like the Require() function, you have to take care of the file's location to prevent any fatal error and execution halt.

 

36. What is the difference between session_start() and session_destroy() function?

PHP session() allows you to store and use the information on different pages. You should always remember that as soon as the browser is closed, session() automatically gets destroyed. Let’s see how session_start() is different from the session_destroy():

Session_start() Session_destroy()
It creates or resumes the session. It destroys the session.
Its main job is creating a session or resuming the current one according to a session identifier passed through a GET, POST request, or a cookie. Its main job is to destroy all the information associated with the current session. It does not unset any of the global variables associated with the session or unset the session cookie.

It has one parameter, which is optional. Its syntax:

Session_start (array $options = []): bool

It does not have any parameters. It's the syntax:

Session_destroy()

It returns true if the session starts successfully; otherwise, it returns false. It returns true on success or false on failure.

 

37. What are the major steps for creating a new database using MySQL and PHP?

It is easy to create a new MySQL database in PHP. By executing a query, you can create a database. Here is how the process works:

  • First step: Connection establishment
    Establish the connection to the MySQL server using PHP script. The server establishes and validates the connection.
  • Second step: Write queries
    Write a SQL query for further verification after validation in the first step. Now, write other queries for creating the database and storing them into string variables.
  • Third step: Execution
    Executes queries one by one to complete the process of database creation.

Check out the syntax in the below image:

 

PHP Interview Questions - creating a new database using MySQL and PHP

Image Credit: PHP_cookbook and here you can also find the various ways to execute queries

 

38. What is type hinting in PHP?

As the name suggests, type hinting in PHP is like giving hints to a specific function. PHP 5 brought this concept to specify data types for function arguments in function declarations. The expected data types could be objects, arrays, interfaces, etc. Whenever the function has been called, PHP checks if the arguments are of a user-preferred type or not. The runtime will generate an error if the argument is not of the specified type, and PHP will halt the program execution.

For instance, if you previously mentioned an integer datatype as the datatype of the function arguments in the function declaration and attempt to pass float or other data instead of an integer value, you'll get the error "value must only be integer".

The 2 main benefits of type hinting:

  • Code optimization
  • Improved error messages

 

39. How Get method is different from the Post method?

The server-side scripting language, PHP, uses Get and Post methods for sending and receiving the information to and from the server. The following table highlights the difference between Get and Post methods:

Get Post
It sends the information by sending a request from a specified resource. It sends information using an HTTP header.
It is the best way to use this to send general information which is non-sensitive. It is the best way to use it for sending sensitive information.
You can send only limited information (1500 characters) using this method. You can send unlimited information through this method.
You can easily see information in the URL. Since information is non-visible in the URL thus, you can't see them.
It is less secure than the Post method. It is most secure than Get method.
You can bookmark the data and other information. You can't bookmark any data.

 

40. How can you create a simple REST API in PHP?

REST stands for Representational State Transfer which refers to system architecture to define methods for accessing web services. The primary function of the REST API is to build a system which can be used by other mobile or web applications. CRUD ( Create, Read, Update, Delete) operations have been used for creating Rest API. REST uses Get, Post, Put, and Delete requests to implement these operations. Like Get- Read; Post-Create; Put- Update; Delete-Delete. It generates output data in varied formats such as Extensible Markup Language (XML), JavaScript Object Notation (JSON), and Command Separated Value (CSV).

There are three simple steps for creating Rest API

  • Create a database and table (use query – Create a table or Create database)
  • Establish a database connection (use query – Connect)
  • Create a REST API file. (see the image to know the sample script which has used Get request and output format is JSON)

 

PHP Interview Questions - create a simple REST API in PHP

Image Credit: Allphtrick

 

41. How do you create cookies in PHP?

A cookie is a file that the server embeds on the user's computer to track user information such as username, email address, phone number, etc. Always remember that, whenever you request a page from the same device, the server sends the cookie as well. In PHP, you can create a cookie using setcookie() function. You must call the cookie before a script generates any outcome.

Syntax

setcookie(name, value, expire, path, domain, secure):

Here

  • Name – mandatory argument to set the name
  • Value – Optional argument to set the value
  • Expire – Optional argument to set the expiry timestamp of the cookie
  • Path – Optional argument to specify cookie path on the server
  • Domain – Optional argument to specify the domain for which cookie is available
  • Secure – Optional argument to ensure the secure connection using HTTP only

See the following images to understand various examples of setting cookies. You can see a cookie which contains the user's email address.

 

PHP Interview Questions - How to create cookies in PHP

Image Credit: PHP Beginner's Guide

 

42. Discuss runtime exceptions and compile time exceptions.

The exception is an important OOPs concept to define any logical or runtime error. It could be either runtime exception or compile time. In PHP, any class, function, object, or user-defined function can throw exceptions.

Runtime Exception:

This exception is a runtime exception which occurs during runtime. It can happen even after the successful compilation and execution of the codes. The main reasons behind this exception are invalid user inputs, invalid API communications, increased size of storage media, or other similar events.

For example, you have defined an integer variable in code but input a float number at runtime. It would execute codes but would not generate the outcome. You must use the Try-catch block to catch this exception and manage them appropriately.

Compile Time Exception:

This exception is compiled time exception, which occurs during code writing and compiling. It happens because of coding mistakes, or you have made syntax or semantic mistakes in the code. For example, undeclared variables, missing parenthesis or commas, or other similar cases. To execute code successfully, you must catch the compile time exception and fix the code.

 

43. Can you perform password encryption in PHP?

Yes, you can perform password encryption in PHP using many ways. The primary objective of PHP encryption is to protect the data. It uses hashing algorithms to convert the data into encrypted text. You need to use specific decryption processes to decode the data again.

The function password_hash() is used to protect and verify the passwords. A generic step of password encryption is as follows:

  • Create a Unique Encryption Key (DEK)
  • Scramble the information utilizing unique key encryption
  • Move the DEK to the cloud for encryption which would return an encrypted data key (KEK)
  • Save the KEK and encrypted data
  • Use generated key (DEK)

Three ways of password encryption in PHP

  • Hashing – A simplest way to encrypt passwords using Hash. It takes an input value and converts it into a fixed-length outcome which is called "hash", "hash value", or "message digest". It should be used for storing user passwords.
  • Secret Key Encryption – Another simple way to encrypt a password using one key only. It is also called symmetric encryption, which uses a shared secret (single key) to encrypt and decrypt the data. This means the sender and receiver use the same key to ensure data privacy.
  • Envelope encryption – It is not used widely for encryption. The central concept of this encryption is to put the required data in a virtual envelope after encryption, lock it for the receiver(s), put the receiver(s) address, and mention the lock and other key identifiers on the outside of the envelope.

Check this link to get the codes of each encryption.

Databases play a crucial role in PHP. Take a look at this link to find out about different database concepts.

 

44. How can we terminate the script execution in PHP?

The exit() function is an in-built PHP function which is used to terminate script execution. It outputs a message first and then terminates the script.

  • The shutdown functions and object destroyers are independent of the exit() function and they will be executed even if the script is terminated.
  • Whatever string is passed to the exit() function, it will be displayed before termination.
  • It can be called without parentheses because it is a language construct.

Syntax:

exit(string $status = ?): void

If status is a string, it will be displayed just before termination.

exit(int $status): void

If status is an integer, it will be used as an exit status and will not be printed.


Test your PHP coding skills here

 

45. How can we connect to a URL in PHP?

To connect to a URL, we can use cURL (Client for URLs), a default library in PHP. The client issues a GET request and receives the information which has been asked, such as headers, HTML, etc. There are cURL functions available to support these actions they are:

  • curl_init(): To initialise the cURL session
  • curl_setopt(): To set all options for transfer
  • curl_exec(): To execute the session
  • curl_close(): To close the session

Below example shows use of cURL for downloading contents of a remote website into a local file.

<?php 

$handle = curl_init(); 

$url = "https://www.ladygaga.com"; 

  

// Set the url 

curl_setopt($handle, CURLOPT_URL, $url); 

// Set the result output to be a string. 

curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); 

  

$output = curl_exec($handle); 

  

curl_close($handle); 

  

echo $output; 

?>

 

46. Why is callback used in PHP?

A callback function is a function which can be passed as an argument into another function. They are denoted by a callable type and their name is passed in the calling function as an argument.

Example: Pass a callback to PHP’s array_map function.

<?php 

function my_callback($item) { 

  return strlen($item); 

} 

$strings = ["apple", "orange", "banana", "coconut"]; 

$lengths = array_map("my_callback", $strings); 

print_r($lengths); 

?>  

 

47. Will it be possible to extend the execution time of PHP?

The maximum execution time is defined by max_execution_time directive.

After PHP reaches the maximum execution time, a fatal error will be generated and PHP will timeout and exit.

Fatal error: Maximum execution time of 30 seconds exceeded in example.php

If the execution time is not set then the default value is 30 seconds. There are below ways to increase the execution time:

 

48. Explain major differences between for loop and foreach loop.

For loop Foreach loop
It is executed over variables Executed on Arrays - associative and numerical
Executes till the given condition is true Executes till the given condition is true
Syntax:
for ( initialisation; condition; increment)
{
Code to be executed;
}
Syntax:
foreach ($array as $value)
{
Code to be executed;
}

 

Final Thought

We hope these questions and answers have helped you gain a deeper understanding of PHP. Practice and implementation will help you develop your PHP skills. Sign up for our community to get updates on the latest trends in tech, job opportunities, and practice your tech skills. Share your queries in the comment.


Explore our careers section for PHP Job Openings

 

Other Backend Technology Interview Questions and Answers

C Programming Language Interview Questions | .NET Core Interview Questions | NumPy Interview Questions | API Interview Questions | FastAPI Python Web Framework | Java Exception Handling Interview Questions | OOPs Concepts in Java Interview Questions | Java Collections Interview Questions | System Design Interview Questions | Data Structure Concepts | Node.js Interview Questions | Django Interview Questions | React Interview Questions | Microservices Interview Questions | Key Backend Development Skills | Data Science Interview Questions | Python Interview Questions | Java Spring Framework Interview Questions

Responses

  1. This is a lifeline when you go blank during an online interview. Just keep it open on your screen 👩‍💻🤓🧑‍💻✌️

Comments are closed.

HACKERBUCK AWARDED