PHP Interview Questions and Answers : One of the most important things I watch out is the creativity of the person In interview.PHP Interview Questions PHP is a web language based on scripts that allow developers to dynamically create generated web pages. PHP stands for Hypertext Preprocessor. It is an open source server-side scripting language which is widely used for web development.
People who are searching or preparing for PHP jobs, have to face some common questions in the interview.
We Chose Some PHP Interview Questions and Answers For You.
PHP Interview Questions and Answers
1- Who is the father of PHP ?
Rasmus Lerdorf is known as the father of PHP.
2- What is PHP?
PHP is a server side scripting language commonly used for web applications. PHP has many frameworks and cms for creating websites.Even a non technical person can cretae sites using its CMS.PHP is an open source scripting language. Needless to say, it’s one of the most popular scripting languages in the world – you wouldn’t be reading this tutorial if that wasn’t the case.
3- What is the use of “echo” in php?
It is used to print a data in the webpage, Example: , The following code print the text in the webpage
4- PHP resembles which programming language?
The syntax of PHP resembles Perl and C.
5- How to create a mysql connection?
mysql_connect(servername,username,password);
6- What is the name of scripting engine in PHP?
ZEND Engine 2 is the name of the scripting engine that powers PHP.
7- What Is A Session?
A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests
8- What is MIME?
MIME – Multi-purpose Internet Mail Extensions.
MIME types represents a standard way of classifying file types over Internet.
Web servers and browsers have a list of MIME types, which facilitates files transfer of the same type in the same way, irrespective of operating system they are working in.
A MIME type has two parts: a type and a subtype. They are separated by a slash (/).
MIME type for Microsoft Word files is application and the subtype is msword, i.e. application/msword.
9- What is mean by LAMP?
LAMP means combination of Linux, Apache, MySQL and PHP.
10- What is the purpose of the superglobal variable called $_SERVER ?
$_SERVER is an array and it holds the information about paths, headers, and script locations.
11- How to redirect a page in php?
The following code can be used for it, header(“Location:index.php”);
12- How to include a file to a php page?
We can include a file using “include() ” or “require()” function with file path as its parameter.
13- What types of loops exist in php?
for,while,do while and foreach (NB: You should learn its usage)
14- How to select a database?
mysql_select_db($db_name);
15- What are the common uses of PHP?
Using PHP, you can restrict users to access some pages of your website and also encrypt data.
It performs system functions, i.e. from files on a system it can create, open, read, write, and close them.
You can add, delete, modify elements within your database with the help of PHP.
Access cookies variables and set cookies.
It can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user.
16- How can I execute a php script using command line?
Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, “php myScript.php”, assuming “php” is the command to invoke the CLI program.
Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.
17- What is the difference between $message and $$message?
They are both variables. But $message is a variable with a fixed name. $$message is a variable who’s name is stored in $message. For example, if $message contains “var”, $$message is the same as $var.
18- What is PEAR in PHP?
PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP Extension and Application Repository. It contains all types of PHP code snippets and libraries. It also provides a command line interface to install “packages” automatically.
19- What is the difference between $name and $$name?
$name is variable where as $$name is reference variable like $name=Bilal and $$name=Khan so $Bilal value is Khan.
20- What is meant by nl2br()?
Nl2br Inserts HTML line breaks before all newlines in a string string nl2br (string); For example: echo nl2br(“god bless you”) will output “god bless you” to your browser.
21- What is the difference between static and dynamic websites?
Static Websites
In static websites, content can’t be changed after running the script. You cannot change anything in the site as it is predefined.
Dynamic Websites
In dynamic websites, content of script can be changed at the run time. Its content is regenerated every time a user visits or reloads.
22- Is PHP a case sensitive language?
PHP is partially case sensitive. The variable names are case-sensitive but function names are not. If you define the function name in lowercase and call them in uppercase, it will still work. User-defined functions are not case sensitive but the rest of the language is case-sensitive.
23- What are the method available in form submitting?
GET and POST
24- How to execute a PHP script from the command line?
To execute a PHP script, use the PHP Command Line Interface (CLI) and specify the file name of the script in the following way:
php script.php
25- How can we get the browser properties using PHP?
<?php
echo $_SERVER[‘HTTP_USER_AGENT’].”\n\n”;
$browser=get_browser(null,true);
print_r($browser);
?>
26- What Is a Session?
A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests. Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.
27- How can we register the variables into a session?
<?php
session_register($ur_session_var);
?>
28- How many ways we can pass the variable through the navigation between the pages?
Register the variable into the session
Pass the variable as a cookie
Pass the variable as part of the URL
29- How can we know the total number of elements of Array?
sizeof($array_var)
count($array_var)
30- How can we create a database using php?
mysql_create_db();
31- What is the functionality of the function strstr and stristr?
strstr() returns part of a given string from the first occurrence of a given substring to the end of the string.
For example:strstr(“[email protected]”,”@”) will return “@example.com”.
stristr() is idential to strstr() except that it is case insensitive.
32- What are encryption functions in PHP?
CRYPT(), MD5()
33- How to store the uploaded file to the final location?
move_uploaded_file( string filename, string destination)
34- Explain mysql_error().
The mysql_error() message will tell us what was wrong with our query, similar to the message we would receive at the MySQL console.
35- What is Constructors and Destructors?
CONSTRUCTOR : PHP allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
DESTRUCTORS : PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.
36- Explain the visibility of the property or method.
The visibility of a property or method must be defined by prefixing the declaration with the keywords public, protected or private.
Class members declared public can be accessed everywhere.
Members declared protected can be accessed only within the class itself and by inherited and parent classes.
Members declared as private may only be accessed by the class that defines the member.
37- What are the differences between Get and post methods.
There are some difference between GET and POST method
GET Method have some limit like only 2Kb data able to send for request But in POST method unlimited data can we send
when we use GET method requested data show in URL but Not in POST method so POST method is good for send sensitive request
38- What are the differences between require and include?
Both include and require used to include a file but when included file not found
Include send Warning where as Require send Fatal Error
39- What is use of header() function in php ?
The header() function sends a raw HTTP header to a client.We can use herder() function for redirection of pages. It is important to notice that header() must be called before any actual output is seen.
40- List out the predefined classes in PHP?
Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter
41- What type of inheritance that PHP supports?
In PHP an extended class is always dependent on a single base class,that is, multiple inheritance is not supported. Classes are extended using the keyword ‘extends’.
42- How can we encrypt the username and password using php?
You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD(“Password”);
We can encode data using base64_encode($string) and can decode using base64_decode($string);
43- What is the difference between explode and split?
Split function splits string into array by regular expression. Explode splits a string into array by string.
For Example:explode(” and”, “Pakistan and UK and UAE”);
split(” :”, ” Pakistan : UK : UAE “);
Both of these functions will return an array that contains UK , Pakistan, and UAE.
44- How do you define a constant?
Constants in PHP are defined using define() directive, like define(“MYCONSTANT”, 100);
45- How do you pass a variable by value in PHP?
Just like in C++, put an ampersand in front of it, like $a = &$b;
46- What does a special set of tags <?= and ?> do in PHP?
The output is displayed directly to the browser.
47- How do you call a constructor for a parent class?
parent::constructor($value)
48- What’s the special meaning of __sleep and __wakeup?
__sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.
49- What is the difference between PHP and JavaScript?
java script is a client side scripting language, so JavaScript can make popups and other things happens on someone’s PC. While PHP is server side scripting language so it does every stuff with the server.
50- What is the difference between the functions unlink and unset?
unlink() deletes the given file from the file system.
unset() makes a variable undefined.
51- How many ways can we get the value of current session id?
session_id() returns the session id for the current session.
52- What are default session time and path?
default session time in PHP is 1440 seconds or 24 minutes
Default session save path id temporary folder /tmp
53- For image work which library?
we will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.
54- How can we get second of the current time using date function?
<?php
$second = date(“s”);
?>
55- What are the Formatting and Printing Strings available in PHP?
printf()- Displays a formatted string
sprintf()-Saves a formatted string in a variable
fprintf() -Prints a formatted string to a file
number_format()-Formats numbers as strings
56- How can we find the number of rows in a result set using PHP?
$result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo “$num_rows rows found”;
57- What is the meaning of ‘escaping to PHP’?
The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The mechanism for doing so is known as ‘escaping to PHP’. Escaping a string means to reduce ambiguity in quotes used in that string.
58- What are the characteristics of PHP variables?
Some of the important characteristics of PHP variables include:
Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
Variables can, but do not need, to be declared before assignment.Variables in PHP do not have intrinsic types – a variable does not know in advance whether it will be used to store a number or a string of characters.All variables in PHP are denoted with a leading dollar sign ($).The value of a variable is the value of its most recent assignment.Variables used before they are assigned have default values.
59- What are the different types of PHP variables?
There are 8 data types in PHP which are used to construct the variables:
Integers − are whole numbers, without a decimal point, like 4567.
Doubles − are floating-point numbers, like 3.14159 or 49.1.
Booleans − have only two possible values either true or false.
NULL − is a special type that only has one value: NULL.
Strings − are sequences of characters, like ‘PHP supports string operations.’
Arrays − are named and indexed collections of other values.
Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
Resources − are special variables that hold references to resources external to PHP.
60- What are the rules for naming a PHP variable?
1- Variable names must begin with a letter or underscore character.
2- A variable name can consist of numbers, letters, underscores but you cannot use characters like + , – , % , ( , ) . & , etc.
61- What’s the difference between the include()
and require()
functions?
They both include a specific file but on require the process exits with a fatal error if the file can’t be included, while include statement may still pass and jump to the next step in the execution.
62- How can we get the IP address of the client?
There are many options. $_SERVER["REMOTE_ADDR"];
is the easiest solution.
63- What’s the difference between unset()
and unlink()
unset()
sets a variable to “undefined
” while unlink()
deletes a file we pass to it from the file system.
64- How can you enable error reporting in PHP?
Check if “display_errors
” is equal “on” in the php.ini or declare “ini_set('display_errors',1)
” in your script.
Then, include “error_reporting(E_ALL)
” in your code to display all types of error messages during the script execution.
65- What are Traits?
Traits are a mechanism that allows you to create reusable code in languages like PHP where multiple inheritance is not supported. A Trait cannot be instantiated on its own.
66- Can the value of a constant change during the script’s execution?
No, the value of a constant cannot be changed once it’s declared during the PHP execution.
67- Can you extend a Final
defined class?
No, you cannot extend a Final
defined class. A Final
class or method declaration prevents child class or method overriding.
68- What are the 3 scope levels available in PHP and how would you define them?
Private – Visible only in its own class
Public – Visible to any other code accessing the class
Protected – Visible only to classes parent(s) and classes that extend the current class
69- What does MVC stand for and what does each component do?
MVC stands for Model View Controller.
The controller handles data passed to it by the view and also passes data to the view.
70- Why would you use ===
instead of ==
?
If you would want to check for a certain type, like an integer or boolean, the ===
will do that exactly like one would expect from a strongly typed language, while ==
would convert the data temporarily and try to match both operand’s types. The identity operator (===
) also performs better as a result of not having to deal with type conversion. Especially when checking variables for true/false, one should avoid using ==
as this would also take into account 0/1 or other similar representation.
71- Do you use Composer? If yes, what benefits have you found in it?
Using Composer is a tool for dependency management. The candidate can declare the libraries your product relies on and Composer will manage the installation and updating of the libraries. The benefit is a consistent way of managing the libraries depended on so less time is spent managing the libraries.
72- How can we encrypt and decrypt a data present in a mysql table using mysql?
AES_ENCRYPT () and AES_DECRYPT ()
73- What are the different types of errors in php?
E_ERROR: A fatal error that causes script termination
E_WARNING: Run-time warning that does not cause script termination
E_PARSE: Compile time parse error.
E_NOTICE: Run time notice caused due to error in code
E_CORE_ERROR: Fatal errors that occur during PHP’s initial startup (installation)
E_CORE_WARNING: Warnings that occur during PHP’s initial startup
E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
E_USER_ERROR: User-generated error message.
E_USER_WARNING: User-generated warning message.
E_USER_NOTICE: User-generated notice message.
E_STRICT: Run-time notices.
E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
E_ALL: Catches all errors and warnings
74- What is the maximum size of a file that can be uploaded using php and how can we change this?
You can change maximum size of a file set upload_max_filesize variable in php.ini file.
75- How can we increase the execution time of a php script?
Set max_execution_time variable in php.ini file to your desired time in second.
76- How many ways can we get the value of current session id?
session_id() function returns the session id for the current session.
77- What is the use of “ksort” in php?
It is used for sort an array by key in reverse order.
78- How to enable the use of ‘image’ in PHP?
To use the image function in PHP, you need to have downloaded GD library – a graphics drawing tool that lets you alter the data information of an image.
79- When do you use ‘@’?
The “@” command is used to avoid problems in your code by simply telling PHP to deal with them for you.
80- How to export PHP data into Excel?
To be able to export PHP data in an Excel sheet, you will have to change the format of the file. Probably one of the most common types of such files would be a .csv formatted file.
81- What is SQL injection ?
SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications
82- What is x+ mode in fopen() used for?
Read/Write. Creates a new file. Returns FALSE and an error if file already exists
83- How to create a mysql connection?
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
84- What is x+ mode in fopen() used for?
Read/Write. Creates a new file. Returns FALSE and an error if file already exists
85- How Do You Call A Constructor For A Parent Class?
parent::constructor($value).
86- Define the use of .htaccess and php.ini files in PHP?
- .htaccess – A special file that can be used to change or manage the behavior of a website. Directing all users to one page and redirecting the domain’s page to https or www are two of the most important uses of the file. For .htaccess to work, PHP needs to be installed as an Apache module.
- php.ini – This special file allows making changes to the default PHP settings. Either the default php.ini file can be edited or a new file can be created with relevant additions and then saved as the php.ini file. For php.ini to work, PHP needs to run as CGI.
87- Explain Path Traversal?
Path Traversal is a form of attack with an aim to read into the files of a web application. ‘../’ is known as dot-dot-sequences. It is a cross-platform symbol to go up in the directory. In order to operate the web application file, Path Traversal makes use of the dot-dot-slash sequences.
88- Name some of the popular frameworks in PHP.
- CakePHP
- CodeIgniter
- Yii 2
- Symfony
- Zend Framework
89- What is the difference between “echo” and “print” in PHP?
- Echo can output one or more string but print can only output one string and always returns 1.
- Echo is faster than print because it does not return any value.
90- What is overloading and overriding in PHP?
Overloading is defining functions that have similar signatures, yet have different parameters. Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that method.
91- How can we create a database using PHP and MySQL?
- Establish a connection to MySQL server from your PHP script.
- If the connection is successful, write a SQL query to create a database and store it in a string variable.
- Execute the query.
92- 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.
93- How can you retrieve data from the MySQL database using PHP?
mysqli_fetch_array() – It is used to fetch the records as a numeric array or an associative array.
mysqli_fetch_row() – It is used to fetch the records in a numeric array.
mysqli_fetch_assoc() – It is used to fetch the records in an associative array.
mysqli_fetch_object() – It is used to fetch the records as an object.
94- 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.
95- How to add 301 redirects in PHP?
You can add 301 redirect in PHP by adding below code snippet in your file.
header("HTTP/1.1 301 Moved Permanently"); header("Location: /option-a"); exit();
96- What is T_PAAMAYIM_NEKUDOTAYIM ?
T_PAAMAYIM_NEKUDOTAYIM is scope resolution operator used as :: (double colon) .Basically, it used to call static methods/variables of a Class.
Example usage:-
$Cache::getConfig($key);
97- What is cURL in PHP ?
cURL is a library in PHP that allows you to make HTTP requests from the server.
98- What is a composer in PHP?
It is an application-level package manager for PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.
99- How to check curl is enabled or not in PHP
use function_exists(‘curl_version’) function to check curl is enabled or not. This function returns true if curl is enabled other false
Example :
if(function_exists('curl_version') ){ echo "Curl is enabled"; }else{ echo "Curl is not enabled"; }
100- What is the difference between nowdoc and heredoc?
- 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.
101- How can i execute PHP File using Command Line?
1. Open the command prompt. Click on Start button->Command Prompt.
2. In the Command Prompt, write the full path to the PHP executable(php.exe) which is followed by the full path of a script that you want to execute. You must add space in between each component. It means to navigate the command to your script location.
then your command line will be:
C:\PHP\php.exe C:\PHP\sample-php-script.php
3. Press the enter key and your script will execute.
102- What are different types of Print Functions available in PHP?
- print() Function
- echo() Function
- printf() Function
- sprintf() Function
- Var_dump() Function
- print_r() Function
Hope These PHP Interview Questions and Answers will helpful for you and your Friend.if you want to add your Question Kindly Post you Question in Comments.Thank You.