PHP Interview Questions

PHP Interview Questions | Freshers & Experienced

  • Ketan Chauhan
  • 12th Apr, 2021
  • 1046 Followers

Key Features of Php

Below are few major features of Php

Simple and Easy

Platform independent

Real-Time Access Monitoring

Flexibility

Case-Sensitive

Open Source

Error Reporting

Fast and efficient performance

Object-oriented features

PHP Interview Questions

Q1. What is mvc in PHP?

MVC is a design pattern for creating applications that separate Business logic (Controller) and Application data (Models) from the USER interface (View). MVC is an acronym of Model, View Controller.

Q2. Write a program to upload files using curl

Q3. What is name of max execution time constant in php?

max_execution_time is of the constant that is used to increase the execution time of a script in PHP.

Q4. What is difference between echo and print in PHP?

 There is a small difference between Echo and Print in PHP. 

 These are - 

  1. Echo has no return value while Print has a return value of 1.
  2. The Echo is marginally faster in comparison to Print.
  3. Echo can output one is more strings while Print can output only 1 string.
  4. Echo is a language constructor while Print is a function.

In PHP, print and echo are both used to print statements but with a small difference.

  • PHP print – It takes only one argument and has a return value of 1. It can use with or without parenthesis.
//example 
<?php 
print "PHP print statement"; 
?> 

  • PHP echo – It can be used to print more than one argument separated by a comma and does not return any values. It can also be used with or without parenthesis. In PHP, echo is faster to execute than print.
//example 
<?php 
$x = 5; 
$y = 5; 
echo $x + $y; 
?>

Q5. What is HTML DOM?

DOM (Document Object Model) is a Object Model for HTML. The Document Object Model (DOM) defines the logical structure of documents and the way a document is accessed and manipulated.

Q6. How to create cookies via Ajax in PHP?

Q7. What is sql injection? What you do to prevent SQL Injection in PHP?

The injection attacks that are used to possibly lead to the execution of an otherwise highly malicious SQL statement is known as SQL Injection.

The reports can control a database server behind a web application to cross its security measures. It can be used toad, modify and delete records in the application database. It can also be used to gain unauthorized access to your most sensitive data or information. These attacks are the most prevalent, oldest and very risky and dangerous web application vulnerabilities.

It can be prevented in PHP by using prepared statements and parameterized queries. These SQL statements are sent to and parsed by the application database server separately from any parameters.in this way, it makes it impossible for attackers to inject a malicious SQL INJECTION.

Q8. Explain scope levels in PHP.

There are 3 different levels of Scopes are available in PHP. They are.

  • Public: Public scopes allow you to access all data and functions of a Class.
  • Private: Private scopes don't allow you to access the private data and functions of a Class.
  • Protected: Protected scopes only allows its derived class to access the Protected data and functions of a Class.

Q9. Find the longest palindrome in a string

Q10. What is difference between session and cookie?

The Major difference between sessions and cookies are - 

  1.  Sessions are stored in Server Side while Cookies are sotred in Client Side.
  2.  Sessions are stored unlimited amount of Data while Cookies are Stored limited amount of Data.
  3.  Sessions are holding multiple variables while Cookies are not holding multiple varibles.
  4.  Sessions are more secure than Cookies.
  5.  Sessions values are not easily accessible While Cookies values are easily accessible.
  6.  Sessions can not disabled by visitor while cookies can disabled by the visitor.

Q11. How to get IP address of user in PHP?

In your code simply use  $_SERVER['REMOTE_ADDR'] to get the IP address of the client or User.

PHP provides an easy way to get the user's IP address. You need to use the $_SERVER variable and REMOTE_ADDR to get the IP address of a user in PHP.

//Command to get the IP address 
Echo ‘User IP address’ .$_SERVER[‘REMOTE_ADDR’];

Q12. What is the full form of PHP?

The full form of PHP is Hypertext preprocessor (earlier called personal home page)

Q13. How to create object of Interface?

Q14. What is cross site scripting and how it can be prevented?

Q15. Write pyramid structure without using PHP function ?

Q16. What is difference between XAMPP, WAMP, and LAMP

Difference between XAMPP, WAMP, and LAMP

XAMPP is an open-source platform that is one of the simplest and light-weighted local servers useful to develop/test our website locally. XAMPP stands for cross-platform, Apache, MariaDB (MySQL), PHP and Perl. It can work with all major operating systems such as Windows, Mac, Linux, etc. We can perform testing and update the contents in our websites testing locally. It is open-source which can be easily downloaded and installed in our computer system.

WAMP uses the Apache webserver that is used to run a web server on windows. WAMP stands for Windows, Apache, MySQL, and PHP. It works on only the windows operating system. It uses the MySQL relational database management system and PHP object-oriented scripting language, which helps to test the web pages without publishing it on the live web server.

LAMP platform has four layers, also known as a LAMP stack. LAMP stands for Linux, Apache, Mysql, and PHP. It works on the Linux operating system. It is easy to code with PHP and a cheap and ubiquitous hosting platform. It can generate dynamic web pages that run PHP code and load data from a MySQL database.

Q17. Tell me few diffrence between GET & POST

Few difference between GET & POST is - 

GET request remains in browser history while POST Request does not remain in browser history.

GET is availbale for retrieving data while POST is available for writing/Updating data.

GET have no side effects while POST have some side effects.

 

Q18. How to connect MongoDB using PHP?

Q19. What is default session time in PHP? How to increase It?

Q20. How can you connect a web page data with mysql ?

Q21. Explian the difference between preg_Match and preg_replace?

preg_Match is the pattern, that is used for searching as a string, while preg_replace is the pattern, that contains the string which is used to search the content, which can be the array of string.

 

Q22. List the HTTP methods avalable in PHP?

Q23. What is Interface? Why we use it?

In the concept of object-oriented programming, Interfaces are used for the implementation of multiple inheritances. In simple words, it means it is a point or a place where two systems, organizations, subjects etc. meet and interact with each other. It is advantageous to increase the readability of the codes . It helps to decrease class LOC. Here, we just declare the procedure or methods and does not provide any implementation for the same. They are more flexible than Classes. They are helpful when we can’t use class inheritance. For the achievement of total abstraction, we need interfaces. Loose coupling is also achieved through it. It gives us more capability to extend and maintain our applications, utilization of abstraction and implementing good software development practices.

Q24. What is difference between PHP 4, 5 and 7?

Difference between PHP4, PHP5, and PHP7

PHP 4:

  • Here everything, including objects, is passed by value. We have to copy the code and assign a new value if we want to duplicate an object.
  • Here, the constructor is just a method with the same name as the name of the class.

PHP 5

  • Here, everything is passed by reference only.
  • It has three levels of visibility of class methods and properties namely public, protected and private.
  • It has a unified name for the constructors -"construct()" and also a "_destruct()"
  • We can also create abstract classes.
  • Limited type hinting, E_STRICT error level, etc are included for a better experience.

PHP7

  • It allows the user to declare the return type of the functions as per the expected return value.
  • Introduction of new Engine Exception Objects.
  • It offers an anonymous class to speed up the execution time.
  • It has the Group Use Declaration through which we can include classes from the same namespace.

Q25. What is difference between the include(), require(),require_once() functions in PHP?

Q26. What are design patterns in PHP? Can you list few.

Q27. What are Super Global variables in PHP?

Q28. What is Php ini?

Q29. Code to send a mail with attachment using phpmailer?

Q30. What is difference between CURL and AJAX?

Difference between CURL and AJAX

AJAX

  • It refers to the client-side utility to call PHP and extract data from it.
  • It is asynchronous and a client-side call which means until the client loads the page,it will not be executed.
  • It is used for communication from the client to the server.

CURL

  • It refers to the Client URL that helps us to connect with other URLs and apply their responses in our codes.
  • It is a package name useful in PHP in order to access data from outside webpages.
  • It is a process from server-side that is it makes requests to external websites and get a response in our background PHP script on the server.

Q31. How to set and Get a value in PHP Session.

Q32. What is the usage of link() in PHP?

PHP link() function is used to hard link for a specified target. The link function takes two arguments first is the target file and the second argument is the name of the link.

Note: The link() function does not work remotely.

Example

<?php
$target = "abc.php";
$linkname = "name of link";
link($target, $linkname);
?>

Q33. PHP resembles syntax from which programming Lanaguage?

PHP resembles its syntax from C and Perl Programming Language.

Q34. What is the default session path in PHP?

The default PHP session storage path on the server is /tmp directory.

Q35. Can we run php script from CLI? Explain how?

Yes, the PHP script can be executed from the command line. To execute it, go to the directory where your PHP script file is stored. Open the command line from that directory and run the following command.

PHP filename.php //here filename is the actual name of your PHP script. 

Q36. Explain what pear in PHP?

PEAR (PHP Extension and Application Repository) is a repository of PHP code and software components. Developed by Stig S Bakken in 1999, PEAR is mainly used to reuse existing code, improve code structure. PEAR group is the governing body of PEAR that mainly promotes a standard coding style for PHP developers using PEAR. PHP comes with a PEAR package manager which is used to download the PEAR packages as a tar file. The PEAR framework is divided into three classes which are PEAR library, PEAR core components, PECL packages. The PECL package is like a PEAR package but has the C extensions that are compiled into PHP.

Q37. Enlist some frameworks of PHP?

Some of the popular frameworks in PHP are,

  • Laravel – An open-sourced framework that is used to develop complex applications seamlessly.
  • CodeIgniter – A popular lightweight framework for developing dynamic web applications.
  • Symfony – A PHP MVC framework for developing large scale applications.
  • CakePHP – A easy to learn PHP framework for developing feature-rich websites.
  • Yii – A simple framework for developing modern PHP web applications.
  • ZEND – An object-oriented based PHP framework for developing complex, large-scale web applications.

Q38. How to define constant in PHP?

In PHP, constants are named that stores a value. The value of the constant cannot be changed at runtime and it is global by default.

To define a constant in PHP, the define method is used.

//syntax 
define(name, value, casesensitive) 

Here, is the name of the constant. Value is the constant value. Case sensitive defines whether the constant should behave as case sensitive or not. By default, it is false and not case sensitive.

<?php 
define("CONSTANT", "HELLO!"); 
echo CONSTANT; 
?> 

Q39. Enlist major datatypes supported by PHP?

PHP supports all major data types such as String, Integer, Float or Double, Boolean, Array, Object, NULL, Resource, etc.

Q40. What are magic constants in PHP?

The magic constants in PHP are a set of predefined constants that changes their feature based on where it is used. These constants start and end with a double underscore. The magic constants in PHP are,

  • __LINE__ - It represents the current line number.
  • __FILE__ – It represents the name and path of the file.
  • __DIR__ – It represents the full directory path of the file.
  • __FUNCTION__ – It is used to represent the function name.
  • __CLASS__ – It is used to represent the class name.
  • __TRAIT__ – It is used to represent the trait name.
  • __METHOD__ – It is used to represent the name of the class method.
  • __NAMESPACE__ – It represents the name of the namespace.

Q41. List types of array available in PHP?

An array is used to store more than one value to do various operations. There are three types of array present in PHP.

  • Indexed array – Here the array has sorted values with a numeric index.
//syntax to create an indexed array. 
$name = array("one", “two”, “three”, “four”, “five”); 

Here, the values in the array name can be accessed or traversed using its index value starting from 1.

  • Associative array - It is similar to an indexed array but the value is assigned in the array with a user-defined key instead of index numbers.
//example to define a associative array 
$name = array("ONE"=>"1", "TWO"=>"2", "THREE"=>"3", "FOUR"=>"4", "FIVE"=>"5"); 

Here, the values “1”, “2”, “3”, “4”, “5” are associated with user-defined keys “ONE”, “TWO”, “THREE”, …. The array values can be accessed or traversed with the key values.

  • Multidimensional array – Here every element in the array can store the array within. That is the element in the array is itself an array and sub-array within.
//example to create a multidimensional array 
$number = array( array( "one" => "1", "two" => "2", "three" => "3", ), array( “four" => "4", "five" => "5", "six" => "6", ) ); 

Here, each element is another array. The elements within the sub-array can be accessed using the index value. For eg: to access “one”, type $number[0][“one”].

Q42. What is T_PAAMAYIM_NEKUDOTAYIM in PHP?

The Paamayin nekudotayim(::) is the scope resolution operator in PHP for identifying integer by specifying the namespace. It is the Hebrew word for the double colon. The T_PAAMAYIM_NEKUDOTAYIM is the syntax error PHP throws when it expects the scope resolution operator(::)

Q43. Explain the difference between == and === operator in PHP?

= = and = = = are both the comparison operator used in PHP. = = is called the equal operator that is used to check if the values are equal in both side of the operand. = = = is called as the identical operator that is used to check values as well as the data types of the operands are equal or not.

//example for = = 
   <?php 
if("2" == 2) { 
   echo "YES"; 
} 
?> 

It prints YES as the values are equal even though the datatype is not.

//example for = = = 
if("1" == “1”) { 
   echo "YES"; 
} 

It prints YES as both the value and the datatype are equal.

Q44. Explain the difference between == and === operator in PHP?

= = and = = = are both the comparison operator used in PHP. = = is called the equal operator that is used to check if the values are equal in both side of the operand. = = = is called as the identical operator that is used to check values as well as the data types of the operands are equal or not.

//example for = = 
   <?php 
if("2" == 2) { 
   echo "YES"; 
} 
?> 

It prints YES as the values are equal even though the datatype is not.

//example for = = = 
if("1" == “1”) { 
   echo "YES"; 
} 

It prints YES as both the value and the datatype are equal.

Q45. What is purpose of @ in Php ?

@ in PHP is used to control the expression. It is the error control operator. When @ is appended before an expression, any error generated by that expression will be ignored. Using @ is not a good practice as it doesn’t eliminate error but hides it.

//example 
<?php   
$value = @$array_PHP[$key];   
?> 
//If the key doesn’t exist, the error will not be displayed as the error control operator is appended before the expression. 
 

Q46. What is difference between strstr() and stristr() ?

strstr() and stristr() are both used to find the first occurrence of the string except for one difference. That is strstr() is case sensitive and stristr() is not.

//example for strstr() 
strstr(“prograMminG”, “M”);

Here the output is Mming as the case matches with each other.

//example for stristr() 
stristr(“prograMming”, “m”);

Here the output is Mming even though the case doesn’t match as the method is case insensitive.

Q47. How to get count elements of an array in PHP?

The count() function in PHP is used to return the size of the array passed to this method.

//syntax 
count(array, mode); 

Here array is the array name to be passed. Mode specifies whether to count the values in multi-dimensional array or not. By default, the value is 0 and doesn’t count the sub array length in the multi-dimensional array. You can change it to 1 to count the values of the sub array in a multi-dimensional array.

//example  
<?php 
$array_PHP=array("one","two","three"); 
echo count($array_PHP); 
?> 

It returns the value 3.

Q48. How to register a variable in PHP session?

To register a session variable in PHP, Start your session_start() at the beginning of your script. Use the $_SESSION[‘VARIABLE_NAME’] to create and register your session variable. It is a superglobal variable that is accessible by every file in your application.

Eg: $_SESSION[‘user_name’] = “login_name”; 

Note:- You can destroy the session variables using the method session_method();

Q49. What is default time and path of PHP session?

PHP has a session time of 24 minutes which is the default. The default path where session data files are stored in the temporary folder that is, /tmp.

Q50. What is difference between require and include in PHP?

Both the require and include statements are used to include different text, markup, code files into the current PHP file. The difference between require and include method are,

Require statement produces error statement (E_COMPILE_ERROR) when the file is not found and will stop executing the script.

//require() statement example
require("path/to/filename"); //produces error if the file is not found. 

Include a statement only produces the error warning and will continue to run the script without the file.

//include() statement example
include("path/to/filename"); //produces only warning(E_WARNING) when the file is not found. 

Q51. Enlist different types of errors available in PHP?

Errors are nothing but a mistake in the script. PHP has four types of error.

Parse error – It is the error in the syntax of the code. The error arises due to human mistakes. The error is identified by the compiler and fixed by the programmer. The script works fine after it is fixed. Examples of this type are semicolon missing, unclosed quotes or braces, etc.

Example

<?php 
echo "Dog" 
?> 

Note:- In the above code, a semi-colon is missing. So, PHP produces the syntax error.

Fatal error – It occurs when we call an undefined function. PHP understands the code but is unable to execute it.

Example

<?php 
function fun1() 
{ 
echo "Function 1"; 
} 
fun2(); 
?> 

Note:- Here, we define the function 1 but call the undefined function 2. So, PHP produces the undefined function error.

Warning error – As the name implies, it is just a warning. Not an actual error. Examples are missing files, wrong number of arguments, etc.

Example

<?php 
include ("Warning.php"); 
?> 

Note:- Here, the Warning.php is not present int the directory. So, the PHP produces a warning message.

Notice error – It is the same as the warning error but the execution is not stooped here.

Example

<?php   
echo $x;  
?> 

Note:- Here the variable x is not declared or initialized. So, the PHP produces an undefined variable error.

Q52. What are namespaces in PHP?

In PHP, namespaces are used to declare the same function or classes or methods in the different namespaces without getting any error or conflict by encapsulating the code. They are just normal PHP code that is declared using the namespace keyword. It should be declared at the top of the file to use it throughout the file. The namespace provides flexibility while writing code. A namespace can have sub-namespaces within it. A namespace can be declared globally by creating the namespace without any name.

<?php   
Namespace NamspaceName {  
       function namespaceFunction()   
   {  
// Regular PHP code  
   }  
}  
?> 

Q53. How to add redirect in PHP?

Redirection in PHP is used to redirect to a different web page from another page. It can be done using the header() method.

//syntax for header function 
header( $header, $replace, $http_response_code ); 

Here, $header holds the header string. $replace is an optional parameter that indicates that the header should replace the previous header or add a similar header. $http_response_code holds the actual response code.

//example 
<?php  
header("Location: http://www.google.com");  
exit;  
?> 
 

Here, PHP redirects the page to google home page. Exit() or die() after redirection is mandatory as it exits any following code after the redirection.

Q54. What is use of GD library in PHP?

Developed by Thomas Boutell, the GD library is used in the development of web applications. An open-source library used for creating images in the format of JPEG, GIF, and PNG. It is also used to generate charts and graphics too.

Q55. What is cURL in PHP?

The cURL in PHP is a library that is used to make an HTTP request to fetch a URL. The curl_init() creates the session and returns the curl handle. After the initialization, there are many functions in curl to grab the contents of the URL and display it. Curl_exec($ch) grabs the contents of the URL and passes it into a variable to display. Curl_setopt() function is also used to grab the contents in various fashion based on the parameters passed.

//example 
<?php  
$url = "https://www.google.com";  
$curl = curl_init(); //it initializes the session 
curl_setopt($ch, CURLOPT_URL, $url); //grabs the content of the URL and passes it to the variable. 
$result = curl_exec($ch); //the grabbed content is passed to another variable for displaying the result. 
echo $result; 
?> 

Q56. What is composer?

Composer is an application manager that is used to install dependencies and libraries in PHP. Inspired by npm and bundler, the Composer is an open-source cross-platform dependency manager that was released in 2012. The important commands in the composer require to a library, install to install a library, update to update a library, and remove to remove a library from compser.json. This command line-based dependency installs the package from the packagist repository.

Q57. Explain PHP traits?

In PHP, using traits, you can reuse a method in multiple classes. Traits are just a group of methods that cannot be instantiated but is used in another class. It is like an abstract class. The trait keyword is used to declare the trait method. You can declare multiple trait methods and use them in a class too.

//syntax 
<?php 
trait traitmethodname { 
//code statement 
} 
?> 

To use a trait in a class, you need to include it with the ‘use’ keyword.

//syntax 
<? 
Class classname{ 
use traitmethodname; 
} 
?> 

Q58. What is use of PHP.ini file?

PHP ini file provides information about configurations and user controls. It is read by the system to configure what a user can and cannot do with the application whenever it is initialized. Apart from this, information related to the global variables, maximum upload size, log error display, time to execute PHP script are present in this file. This file makes it easy to change these configurations. The web server needs to be restarted whenever some changes are made in this file.

Q59. What is difference between array_merge and array_combine?

 

//example 
$array_1 = array(“city1”=>"delhi”, “city2”=>"mumbai”); 
$array_2 = array(“city1”=>"sydney”, “city4”=>"tokyo”); 
print(array_merge($array_1, $array_2)); 
The output will be Array([city1]=>sydney, [city2]=>mumbai, [city4]=>tokyo) 

Array_combine() function combines two arrays of equal length to create a new array. It uses one array for key and another for values. It returns false off you pass an array of different lengths.

//example 
$array_1 = array(“city1”=>"delhi”, “city2”=>"mumbai”); 
$array_2 = array(“city3”=>"sydney”, “city4”=>"tokyo”); 
print(array_merge($array_1, $array_2)); 
The output will be Array([city1]=>sydney, [city2]=>tokyo) 

Q60. Enlist few sensable functions of PHP?

AJAX (Asynchronous Javascript And XML) is a function call used for data retrieval. The call is asynchronous so the data sent and received from the server is independent. It reduces the unnecessary reload by the web page and thereby making it more interactive, versatile, robust and convenient.

CURL(Client URL) is used to get the content of the URL. It is a library used in PHP to get data from outside the current web page. It allows the code to connect with an external URL and get its response to use it in your application.

Q61. Please Explain Display Mode in MVC?

The Display Mode in the ASP.net is used to render the page content based on the requesting device. The requesting device can be web, mobile, tablet, iPhone, or android, the display mode will render the page content based on the size and the variety of the device.

To do this, You Need to create a display mode for each class of devices. The display mode will check the “user-agent" headers and renders the page appropriate for the devices.

The Display Mode can be Set Up when the Application Starts that is, global.asax file.

//example for the display mode setup for android and windows phone
DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("iPhone") { ContextCondition = (ctx => ctx.GetOverriddenUserAgent() .IndexOf("iPhone", StringComparison.OrdinalIgnoreCase) > 0) }); DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("Android") { ContextCondition = (ctx => ctx.GetOverriddenUserAgent() .IndexOf("Android", StringComparison.OrdinalIgnoreCase) > 0) });

About Author :

  • Author of PHP Interview Questions

    Ketan Chauhan

    Ketan is a Software developer from Bengaluru, Karnataka, India.He works on latest Javascript technologoies like Angular, Node JS, React JS. He has also good knowledge of PHP and its frameworks like CodeIgniter, CakePHP,Laravel, Zend.He is always ready for learning new technologies. He loves playing Table tennis, watching and answersing developers queries.

Leave A Comment :

Valid name is required.

Valid name is required.

Valid email id is required.