1. What is PHP ?
PHP: Hypertext Preprocessor is open source server-side scripting language that is widely used for creation of dynamic web applications.It was developed by Rasmus Lerdorf also know as Father of PHP in 1994.

PHP is a loosely typed language , we didn’t have to tell PHP which kind of Datatype a Variable is. PHP automatically converts the variable to the correct datatype , depending on its value.

T_PAAMAYIM_NEKUDOTAYIM is scope resolution operator used as :: (double colon) .Basically, it used to call static methods/variables of a Class.

3. What is session in PHP. How to remove data from a session?
As HTTP is a stateless protocol. To maintain states on the server and share data across multiple pages PHP session are used. PHP sessions are the simple way to store data for individual users/client against a unique session ID. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data, if session id is not present on server PHP creates a new session, and generate a new session ID.

4. What is the difference between == and === operator in PHP ?
In PHP == is equal operator and returns TRUE if $a is equal to $b after type juggling and === is Identical operator and return TRUE if $a is equal to $b, and they are of the same data type.

5. How to register a variable in PHP session ?
In PHP 5.3 or below we can register a variable session_register() function.It is deprecated now and we can set directly a value in $_SESSION Global.

6. Where sessions stored in PHP ?
PHP sessions are stored on server generally in text files in a temp directory of server.
That file is not accessible from outside word. When we create a session PHP create a unique session id that is shared by client by creating cookie on clients browser.That session id is sent by client browser to server each time when a request is made and session is identified.
The default session name is “PHPSESSID”.

7. What is default session time and path in PHP. How to change it ?
Default session time in PHP is 1440 seconds (24 minutes) and Default session storage path is temporary folder/tmp on server.

You can change default session time by using below code

// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);

// each client should remember their session id for EXACTLY 1 hour

8. What are constructor and destructor in PHP ?
PHP constructor and a destructor are special type functions which are automatically called when a PHP class object is created and destroyed.

Generally Constructor are used to intializes the private variables for class and Destructors to free the resources created /used by class .

9. How to increase the execution time of a PHP script ?
The default max execution time for PHP scripts is set to 30 seconds. If a php script runs longer than 30 seconds then PHP stops the script and reports an error.
You can increase the execution time by changing max_execution_time directive in your php.ini file or calling ini_set(‘max_execution_time’, 300); //300 seconds = 5 minutes function at the top of your php script.

10. What is purpose of @ in Php ?
In PHP @ is used to suppress error messages.When we add @ before any statement in php then if any runtime error will occur on that line, then the error handled by PHP

11. What is difference between strstr() and stristr() ?
In PHP both functions are used to find the first occurrence of substring in a string except
stristr() is case-insensitive and strstr is case-sensitive,if no match is found then FALSE will be returned.

12. Is multiple inheritance supported in PHP ?
NO, multiple inheritance is not supported by PHP

Also Read:- Top 10 PHP Interview Questions and Answers

13. What is the difference between unset and unlink ?
Unlink: Is used to remove a file from server.
usage:unlink(‘path to file’);

Unset: Is used unset a variable.
usage: unset($var);

14. How to get number of days between two given dates using PHP ?
$tomorrow = mktime(0, 0, 0, date(“m”) , date(“d”)+1, date(“Y”));
$lastmonth = mktime(0, 0, 0, date(“m”)-1, date(“d”), date(“Y”));
echo ($tomorrow-$lastmonth)/86400;

15. What is Cross-site scripting?
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side script into web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same-origin policy.

16. What are the difference between echo and print?
Difference between echo and print in PHP

echo in PHP
echo is language constructs that display strings.
echo has a void return type.
echo can take multiple parameters separated by comma.
echo is slightly faster than print.
Print in PHP
print is language constructs that display strings.
print has a return value of 1 so it can be used in expressions.
print cannot take multiple parameters.
print is slower than echo.

17. What are different types of Print Functions available in PHP?
PHP is a server side scripting language for creating dynamic web pages. There are so many functions available for displaying output in PHP. Here, I will explain some basic functions for displaying output in PHP. The basic functions for displaying output in PHP are as follows:

print() Function
echo() Function
printf() Function
sprintf() Function
Var_dump() Function
print_r() Function

18. Why should I store logs in a database rather than a file?
A database provides more flexibility and reliability than does logging to a file. It is easy to run queries on databases and generate statistics than it is for flat files. Writing to a file has more overhead and will cause your code to block or fail in the event that a file is unavailable. Inconsistencies caused by slow replication in AFS may also pose a problem to errors logged to files. If you have access to MySQL, use a database for logs, and when the database is unreachable, have your script automatically send an e-mail to the site administrator.

19. What is PECL?
PECL is an online directory or repository for all known PHP extensions. It also provides hosting facilities for downloading and development of PHP extensions.

20. What is Pear in PHP?
PEAR stand for Php Extension and Application Repository.PEAR provides:

A structured library of code
maintain a system for distributing code and for managing code packages
promote a standard coding style
provide reusable components.

21. What is the difference between runtime exception and compile time exception?
An exception that occurs at compile time is called a checked exception. This exception cannot be ignored and must be handled carefully. For example, in Java if you use FileReader class to read data from the file and the file specified in class constructor does not exist, then a FileNotFoundException occurs and you will have to manage that exception. For the purpose, you will have to write the code in a try-catch block and handle the exception. On the other hand, an exception that occurs at runtime is called unchecked-exception Note: Checked exception is not handled so it becomes an unchecked exception. This exception occurs at the time of execution.

22. Which Scripting Engine PHP uses?
Zend Engine is used by PHP. The current stable version of Zend Engine is 3.0. It is developed by Andi Gutmans and Zeev Suraski at Technion – Israel Institute of Technology.

23. What is difference between session and cookie in PHP ?
Session and cookie both are used to store values or data.
cookie stores data in your browser and a session is stored on the server.
Session destroys that when browser close and cookie delete when set time expires.

24. Explain preg_Match and preg_replace?
These are the commonly used regular expressions in PHP. These are an inbuilt function that is used to work with other regular functions.

preg-Match: This is the function used to match a pattern in a defined string. If the patterns match with string, it returns true otherwise it returns false.

Preg_replace: This function is used to perform a replace operation. In this, it first matches the pattern in the string and if pattern matched, ten replace that match with the specified pattern.

25. What is php.ini & .htacess file?
Both are used to make the changes to your PHP setting. These are explained below:

php.ini: It is a special file in PHP where you make changes to your PHP settings. It works when you run PHP as CGI. It depends on you whether you want to use the default settings or changes the setting by editing a php.ini file or, making a new text file and save it as php.ini.

.htaccess: It is a special file that you can use to manage/change the behavior of your site. It works when PHP is installed as an Apache module. These changes include such as redirecting your domain’s page to https or www, directing all users to one page, etc.

26. What is list in PHP?
List is similar to an array but it is not a function, instead it is a language construct. This is used for assignment of a list of variables in one operation. If you are using PHP 5 version, then the list values start from a rightmost parameter, and if you are using PHP 7 version, then your list starts with a left-most parameter.

Also Read:- Top 20 PHP Interview Questions and Answers

27. What is MIME?
MIME stands for Multipurpose Internet Mail Extensions is an extension of the email protocol. It supports exchanging of various data files such as audio, video, application programs, and many others on the internet. It can also handle ASCII texts and Simple Mail Transport Protocol on the internet.

28. What is a path Traversal ?
Path Traversal also is known as Directory Traversal is referring to an attack which is attacked by an attacker to read into the files of the web application. Also, he/she can reveal the content of the file outside the root directory of a web server or any application. Path traversal operates the web application file with the use of dot-dot-slash (../) sequences, as ../ is a cross-platform symbol to go up in the directory.

Path traversal basically implements by an attacker when he/she wants to gain secret passwords, access token or other information stored in the files. Path traversal attack allows the attacker to exploit vulnerabilities present in web file.

29. What is the difference between nowdoc and heredoc?
Heredoc and nowdoc are the methods to define the string in PHP in different ways.

Heredoc process the $variable and special character while nowdoc doesn't do the same.
Heredoc string uses double quotes "" while nowdoc string uses single quote ''
Parsing is done in heredoc but not in nowdoc.

30. What should be the length of variable for SHA256?
It is clear from the name SHA256 that the length is of 256 bits long. If you are using hexadecimal representation, then you require 64 digits to replace 256 bits, as one digit represents four bits. Or if you are using a binary representation which means one byte equals to eight bits, then you need 32 digits.

31. Why do we use PHP?
There are several benefits of using PHP. First of all, it is totally free to use. So anyone can use PHP without any cost and host the site at a minimal cost.
It supports multiple databases. The most commonly used database is MySQL which is also free to use. Many PHP frameworks are used now for web development, such as CodeIgniter, CakePHP, Laravel etc.
These frameworks make the web development task much easier than before.

32. Is PHP a strongly typed language?
No. PHP is a weakly typed or loosely typed language.

Which means PHP does not require to declare data types of the variable when you declare any variable like the other standard programming languages C# or Java. When you store any string value in a variable then the data type is the string and if you store a numeric value in that same variable then the data type is an Integer.

33. How can you execute PHP script from the command line?
You have to use PHP command in the command line to execute a PHP script. If the PHP file name is test.php then the following command is used to run the script from the command line.

php test.php

34. What is PEAR?
The full form of PEAR is “PHP Extension and Application Repository”.
Anyone can download reusable PHP components by using this framework at a free of cost. It contains different types of packages from different developers.

35. What are the differences between session and cookie?
The session is a global variable which is used in the server to store the session data. When a new session creates the cookie with the session id is stored on the visitor’s computer. The session variable can store more data than the cookie variable.

Session data are stored in a $_SESSION array and Cookie data are stored in a $_COOKIE array. Session values are removed automatically when the visitor closes the browser and cookie values are not removed automatically.

36. What is the use of mysqli_real_escape_string() function?
mysqli_real_escape_string() function is used to escape special characters from the string for using a SQL statement
$productName = mysqli_real_escape_string($con, $_POST['proname']);
$ProductType = mysqli_real_escape_string($con, $_POST['protype']);

37. What is a persistence cookie?
A cookie file that is stored permanently in the browser is called a persistence cookie. It is not secure and is mainly used for tracking a visitor for long times.
This type of cookie can be declared as follows,
setccookie ("cookie_name", "cookie_value", strtotime("+2 years");

38. How can a cross-site scripting attack be prevented by PHP?
Htmlentities() function of PHP can be used for preventing cross-site scripting attack.

39. What is meant by public, private, protected, static and final scopes?
Public– Variables, classes, and methods which are declared public can be accessed from anywhere.
Private– Variables, classes and methods which are declared private can be accessed by the parent class only.
Protected– Variables, classes, and methods which are declared protected can be accessed by the parent and child classes only.
Static– The variable which is declared static can keep the value after losing the scope.
Final– This scope prevents the child class to declare the same item again.

40. How can image properties be retrieved in PHP?
getimagesize() – It is used to get the image size.
exif_imagetype() – It is used to get the image type.
imagesx() – It is used to get the image width.
imagesy() – It is used to get the image height.

Top 30 PHP Interview Questions and Answers

41. What is the difference between abstract class and interface?
Abstract classes are used for closely related objects and interfaces are used for unrelated objects.
PHP class can implement multiple interfaces but can’t inherit multiple abstract classes.
Common behavior can be implemented in the abstract class but not an interface.

42. Which library is used in PHP to do various types of Image work?
Using GD library, various types of image work can be done in PHP. Image work includes rotating image, cropping an image, creating image thumbnail etc.

43. What is URL rewriting?
Appending the session ID in every local URL of the requested page for keeping the session information is called URL rewriting.

The disadvantages of this methods are, it doesn’t allow persistence between the sessions and, the user can easily copy and paste the URL and send to another user.

44. What is PDO?
The full form of PDO is PHP Data Objects.

It is a lightweight PHP extension that uses consistence interface for accessing the database. Using PDO, a developer can easily switch from one database server to the other. But it does not support all the advanced features of the new MySQL server.

45. What Are PHP Traits?
This is the common PHP Interview Questions asked in an interview. It is a mechanism that enables us to try and do code reusability in single inheritance language, such as PHP. Its structure is sort of same as that of PHP code, simply that it’s a bunch of reusable functions. Despite having the same name they all having a separate declaration resulting in code duplicity. We will make PHP Traits by clustering these functions. The class will use this attribute to incorporate the functions outlined in it.

46. Why we tend to Use Extract() In PHP?
The extract() perform imports variables into the local symbol table from an array. It uses variable names as array keys and variable values as array values. for every component of an array, it creates a variable within the same symbol table. Following is the syntax.

47. What are the most common errors in PHP?
The most common types of runtime errors in PHP are as follows:
Notices: By default, these errors don’t seem to be flaunted to the user the least bit – though you’ll be able to modify this default behavior.
These include non-critical trivial errors.
For example, accessing a variable that has not yet been outlined
Warnings: By default, these errors are visible to the user, however, they are doing not lead to script termination.
These include a lot of serious errors.
For example, making an attempt to include () a file that does not exist
Fatal Errors: These errors cause the termination of the script immediately, and PHP’s default behavior is to show them to the user. These include critical errors
For example, instantiating an object of a non-existent class.

48. What Is PDO in PHP?
PDO stands for <PHP Data Object>.
It is a group of PHP extensions that give a core PDO class and database, specific drivers.
It provides a vendor-neutral, lightweight, data-access abstraction layer. Thus, in spite of what database we tend to use, the function to issue queries and fetch data will be the same.
It focuses on data access abstraction rather than database abstraction.
PDO needs familiarised options within the core of PHP 5. Therefore, it’ll not run with earlier versions of PHP.
PDO divides into two components.
•The core that provides the interface.
•Drivers to access explicit driver.

49. Define PEAR in PHP?
PEAR stands for “PHP Extension and Application Repository”. PEAR is that the next revolution in PHP. PEAR is used to automatically install “packages” and PEAR could be a framework and distribution system for reusable PHP components.
The purpose of PEAR is to provide:
For PHP users it is a structured library of open-sourced code
It is a system for code distribution and package maintenance
PHP Foundation categories (PFC).
PHP Extension Community Library (PECL).

50. What library is used for PDF in PHP?
This is the most popular PHP Interview Questions asked in an interview. The PDF functions in PHP will produce PDF files exploitation the PDFlib library Version 6. PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4.
There is also the » Panda module. FPDF is a PHP class that permits generating PDF files with pure PHP (without using the PDFlib library.)
F from FPDF stands for Free: you’ll use it for any quite usage and modify it to fit your desires. FPDF needs no extension to works with PHP4 and PHP5.

51. What is the way to avoid email sent through PHP getting into the spam folder?
There’s no special methodology of keeping your emails from being known as spam. But we will contemplate some points that cause this downside.
Let me explain a few common reasons.
1. Sending mail using the `mail` function with minimum parameters
we tend to should use all potential mail headers like `MIME-version`, `Content-type`, `reply address`, `from address` etc. so as to avoid this case
2. Not employing a correct SMTP mail script like PHPmailer or SwiftMailer with Associate in Nursing actual e-mail credentials as well as the username, watchword etc.
If we tend to send e-mail from an actual e-mail account using an SMTP mailer script with username and password, then we will avoid
If you’re on a shared web server, consider buying a unique IP address for yourself, as a result, others using your IP may have gotten your IP blacklisted for spam. Do not send more than 250 emails to every supplier per hour.
Give your users unsubscribe link and if they can’t see the e-mail properly they’ll mark you as spam.

52. What do the initials of PHP stand for?
PHP means PHP: Hypertext Preprocessor.

53. Which programming language does PHP resemble?
PHP syntax resembles Perl and C

54. What does PEAR stand for?
PEAR means "PHP Extension and Application Repository". It extends PHP and provides a higher level of programming for web developers.

Top 40 PHP Interview Questions and Answers

55. What is the actually used PHP version?
Version 7.1 or 7.2 is the recommended version of PHP.

56. How can we display the output directly to the browser?
To be able to display the output directly to the browser, we have to use the special tags <?= and ?>.

57. What is the main difference between PHP 4 and PHP 5?
PHP 5 presents many additional OOP (Object Oriented Programming) features.

58. Is multiple inheritance supported in PHP?
PHP supports only single inheritance; it means that a class can be extended from only one single class using the keyword 'extended'.

59. What is the meaning of a final class and a final method?
'final' is introduced in PHP5. Final class means that this class cannot be extended and a final method cannot be overridden.

60. How is the comparison of objects done in PHP?
We use the operator '==' to test is two objects are instanced from the same class and have same attributes and equal values. We can test if two objects are referring to the same instance of the same class by the use of the identity operator '==='.

61. How can PHP and HTML interact?
It is possible to generate HTML through PHP scripts, and it is possible to pass pieces of information from HTML to PHP.

62. What type of operation is needed when passing values through a form or an URL?
If we would like to pass values through a form or an URL, then we need to encode and to decode them using htmlspecialchars() and urlencode().

63. How can PHP and Javascript interact?
PHP and Javascript cannot directly interact since PHP is a server side language and Javascript is a client-side language. However, we can exchange variables since PHP can generate Javascript code to be executed by the browser and it is possible to pass specific variables back to PHP via the URL.

64. What is needed to be able to use image function?
GD library is needed to execute image functions.

65. What is the use of the function 'imagetypes()'?
imagetypes() gives the image format and types supported by the current version of GD-PHP.

66. What are the functions to be used to get the image's properties (size, width, and height)?
The functions are getimagesize() for size, imagesx() for width and imagesy() for height.

Top 50 PHP Interview Questions and Answers

67. How can we display information of a variable and readable by a human with PHP?
To be able to display a human-readable result we use print_r().

68. How is it possible to set an infinite execution time for PHP script?
The set_time_limit(0) added at the beginning of a script sets to infinite the time of execution to not have the PHP error 'maximum execution time exceeded.' It is also possible to specify this in the php.ini file.

69. What does the PHP error 'Parse error in PHP - unexpected T_variable at line x' means?
This is a PHP syntax error expressing that a mistake at the line x stops parsing and executing the program.

70. What should we do to be able to export data into an Excel file?
The most common and used way is to get data into a format supported by Excel. For example, it is possible to write a .csv file, to choose for example comma as a separator between fields and then to open the file with Excel.

71. What is the function file_get_contents() useful for?
file_get_contents() lets reading a file and storing it in a string variable.

72. How be the result set of Mysql handled in PHP?
The result set can be handled using mysqli_fetch_array, mysqli_fetch_assoc, mysqli_fetch_object or mysqli_fetch_row.

73. How is it possible to know the number of rows returned in the result set?
The function mysqli_num_rows() returns the number of rows in a result set.

74. Which function gives us the number of affected entries by a query?
mysqli_affected_rows() return the number of entries affected by an SQL query.

75. What is the difference between mysqli_fetch_object() and mysqli_fetch_array()?
The mysqli_fetch_object() function collects the first single matching record where mysqli_fetch_array() collects all matching records from the table in an array.

76. How can we access the data sent through the URL with the GET method?
To access the data sent via the GET method, we use $_GET array like this:
$variable = $_GET["var"]; this will now contain 'value'

77. How can we check the value of a given variable is a number?
It is possible to use the dedicated function, is_numeric() to check whether it is a number or not.

78. How can we check the value of a given variable is alphanumeric?
It is possible to use the dedicated function, ctype_alnum to check whether it is an alphanumeric value or not.

79. How do I check if a given variable is empty?
If we want to check whether a variable has a value or not, it is possible to use the empty() function.

80. What does the unlink() function mean?
The unlink() function is dedicated for file system handling. It simply deletes the file given as entry.

81. What does the unset() function mean?
The unset() function is dedicated for variable management. It will make a variable undefined.

82. How do I escape data before storing it in the database?
The addslashes function enables us to escape data before storage into the database.

83. How is it possible to remove escape characters from a string?
The stripslashes function enables us to remove the escape characters before apostrophes in a string.

84. How can we automatically escape incoming data?
We have to enable the Magic quotes entry in the configuration file of PHP.

Top 60 PHP Interview Questions and Answers

85. What does the function get_magic_quotes_gpc() means?
The function get_magic_quotes_gpc() tells us whether the magic quotes is switched on or no.

86. Is it possible to remove the HTML tags from data?
The strip_tags() function enables us to clean a string from the HTML tags.

87. How can we define a variable accessible in functions of a PHP script?
This feature is possible using the global keyword.

88. How is it possible to return a value from a function?
A function returns a value using the instruction 'return $value;'.

89. What is the most convenient hashing method to be used to hash passwords?
It is preferable to use crypt() which natively supports several hashing algorithms or the function hash() which supports more variants than crypt() rather than using the common hashing algorithms such as md5, sha1 or sha256 because they are conceived to be fast. Hence, hashing passwords with these algorithms can create vulnerability.

90. Which cryptographic extension provide generation and verification of digital signatures?
The PHP-OpenSSL extension provides several cryptographic operations including generation and verification of digital signatures.

91. How can you pass a variable by reference?
To be able to pass a variable by reference, we use an ampersand in front of it, as follows $var1 = &$var2

92. Will a comparison of an integer 12 and a string "13" work in PHP?
"13" and 12 can be compared in PHP since it casts everything to the integer type.

93. When is a conditional statement ended with endif?
When the original if was followed by: and then the code block without braces.

94. What is the function func_num_args() used for?
The function func_num_args() is used to give the number of parameters passed into a function.

95. If the variable $var1 is set to 10 and the $var2 is set to the character var1, what's the value of $$var2?
$$var2 contains the value 10.

96. What does accessing a class via :: means?
:: is used to access static methods that do not require object initialization.

97. In PHP, objects are they passed by value or by reference?
In PHP, objects passed by value.

98. what is the definition of a session?
A session is a logical object enabling us to preserve temporary data across multiple PHP pages.

99. How to initiate a session in PHP?
The use of the function session_start() lets us activating a session.

100. How can you propagate a session id?
You can propagate a session id via cookies or URL parameters.

Also Read:- Top 20 PHP Interview Questions and Answers

Also Read:- Top 10 PHP Interview Questions and Answers