Hello dear friends today you learn Most Important 100+ PHP Interview Question and Answer, learn complete.
What is PHP?
PHP is a web language based on scripts that allow developers to dynamically create generated web pages..
PHP has many frameworks and cms for creating websites
What do the initials of PHP stand for?
PHP means PHP: Hypertext Preprocessor.
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
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.
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.
How do you execute a PHP script from the command line?
Just use the PHP command line interface (CLI) and specify the file name of the script to be executed as follows:
php script.php
How to run the interactive PHP shell from the command line interface?
Just use the PHP CLI program with the option -a as follows:
php -a
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.
What is the correct and the most two common way to start and finish a PHP block of code?
The two most common ways to start and finish a PHP script are: and
What is the main difference between PHP 4 and PHP 5?
PHP 5 presents many additional OOP (Object Oriented Programming) features.
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
Example
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.
Example
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.
Example
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
Example
What are PHP Magic Methods/Functions. List them.
In PHP all functions starting with __ names are magical functions/methods. Magical methods always lives in a PHP class.The definition of magical function are defined by programmer itself.
Here are list of magic functions available in PHP
__construct()
__destruct()
__call()
__callStatic()
__get()
__set()
__isset()
__unset()
__sleep()
__wakeup()
__toString()
__invoke()
__set_state()
__clone()
__debugInfo()
What is difference between include and include_once?
Include
Include – Include is used to include files more than once in single PHP script.You can include a file as many times you want.
Syntax: – include(“file_name.php”);
Include Once
Include Once – Include once include a file only one time in php script.Second attempt to include is ignored.
Syntax: – include_once(“file_name.php”);
What is difference between require and require_once()?
Require
Require – Require is also used to include files more than once in single PHP script.Require generates a Fatal error and halts the script execution,if file is not found on specified location or path.You can require a file as many time you want in a single script.
Syntax: – require(“file_name.php”);
Require Once
Require Once – Require once include a file only one time in php script.Second attempt to include is ignored. Require Once also generates a Fatal error and halts the script execution ,if file is not found on specified location or path.
Syntax: – require_once(“file_name.php”);
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 .
Example
List data types in PHP ?
- integer
- boolean
- float
- string
- array
- object
- callable
- resource
- NULL
Explain Type hinting in PHP ?
In PHP Type hinting is used to specify the excepted data type of functions argument.
Example
What are different types of errors available in Php ?
There are 13 types of errors in PHP, We have listed all below
- 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 initial startup.
- E_CORE_WARNING: – Warnings that occur during PHP 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.
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.
Example
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’.
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.
How to get length of an array in PHP ?
PHP count function is used to get the length or numbers of elements in an array
Example
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.
Example
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.
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.
How can I display text with a PHP script?
Two methods are possible:
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().
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.
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.
What is the function file_get_contents() useful for?
file_get_contents() lets reading a file and storing it in a string variable.
How can we connect to a MySQL database from a PHP script?
To be able to connect to a MySQL database, we must use mysqli_connect() function as follows:
What is the function mysql_pconnect() useful for?
mysql_pconnect() ensure a persistent connection to the database, it means that the connection does not close when the PHP script ends.
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.
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.
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.
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:
www.url.com?var=value
$variable = $_GET[“var”]; this will now contain ‘value’
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.
How is a constant defined in a PHP script?
The define() directive lets us defining a constant as follows:
define (“ACONSTANT”, 123);
How is it possible to cast types in PHP?
The name of the output type has to be specified in parentheses before the variable which is to be cast as follows:
- (int), (integer) – cast to integer
- (bool), (boolean) – cast to boolean
- (float), (double), (real) – cast to float
- (string) – cast to string
- (array) – cast to array
- (object) – cast to object
When is a conditional statement ended with endif?
When the original if was followed by: and then the code block without braces.
How is the ternary conditional operator used in PHP?
It is composed of three expressions: a condition, and two operands describing what instruction should be performed when the specified condition is true or false as follows:
Expression_1?Expression_2 : Expression_3;
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.
How to get no of arguments passed to a PHP Function?
func_get_args() function is used to get number of arguments passed in a PHP function.
Example
What is the difference between unset and unlink ?
unset
- Unset: – Is used unset a variable.
- usage: – unset($var);
unlink
- Unlink: – Is used to remove a file from server.
- usage: – unlink(‘path to file’);
What are the difference between echo and print?
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.
What is namespaces in PHP?
PHP Namespaces provide a way of grouping related classes, interfaces, functions and constants.
Example
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
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.
What is Gd PHP?
GD is an open source library for creating dynamic images.
PHP uses GD library to create PNG, JPEG and GIF images.
It is also used for creating charts and graphics on the fly
GD library requires an ANSI C compiler to run
Example
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.
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.
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:
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:
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.
What is difference between ksort() and usort() functions.
ksort() function is used to sort an array according to its key values whereas asort() function is used to sort an array according to its values.
They both used to sort an associative array in PHP.
Example
How we can retrieve the data in the result set of MySQL using PHP?
- mysql_fetch_row
- mysql_fetch_array
- mysql_fetch_object
- mysql_fetch_assoc
What’s the difference between __sleep and __wakeup?
- __sleep returns the array of all the variables that need to be saved
- while __wakeup retrieves them.
What does $GLOBALS mean?
$GLOBALS is associative array including references to all variables which are currently defined in the global scope of the script.
What does $_SERVER mean?
$_SERVER is an array including information created by the web server such as paths, headers, and script locations.
What does $_FILES means?
$_FILES is an associative array composed of items sent to the current script via the HTTP POST method.
How can we change the maximum size of the files to be uploaded?
We can change the maximum size of files to be uploaded by changing upload_max_filesize in php.ini.
What does $_ENV mean?
$_ENV is an associative array of variables sent to the current PHP script via the environment method.
What does $_COOKIE mean?
$_COOKIE is an associative array of variables sent to the current PHP script using the HTTP Cookies.
What does the scope of variables mean?
The scope of a variable is the context within which it is defined. For the most part, all PHP variables only have a single scope.
This single scope spans included and required files as well.
what the difference between the ‘BITWISE AND’ operator and the ‘LOGICAL AND’ operator?
‘BITWISE AND’ operator
$a and $b: – TRUE if both $a and $b are TRUE.
‘LOGICAL AND’ operator
$a & $b: – Bits that are set in both $a and $b are set.
What are the two main string operators?
The first is the concatenation operator (‘.’), which returns the concatenation of its right and left arguments.
The second is (‘.=’), which appends the argument on the right to the argument on the left.
What does the array operator ‘===’ means?
$a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
What is the differences between $a != $b and $a !== $b?
!= means inequality (TRUE if $a is not equal to $b) and !== means non-identity (TRUE if $a is not identical to $b).
What is the goto statement useful for?
The goto statement can be placed to enable jumping inside the PHP program.
The target is pointed by a label followed by a colon, and the instruction is specified as a goto statement followed by the desired target label.
What is the difference between $var and $$var?
They are both variables.
- But $var is a variable with a fixed name
- $$var is a variable who’s name is stored in $var
- For example:
- if $var contains “message”
- $$var is the same as $message
Explain type casting and type juggling.
Type casting
The way by which PHP can assign a particular data type for any variable is called typecasting.
The required type of variable is mentioned in the parenthesis before the variable.
Type juggling
PHP does not support data type for variable declaration.
The type of the variable is changed automatically based on the assigned value and it is called type juggling.
Example 1
Example 2
What are the differences between mysqli_connect and mysqli_pconnect?
mysqli_connect and mysqli_pconnect
mysqli_connect() – function searches any existing persistence connection first and if no persistence connection exists, then it will create a new database connection and terminate the connection at the end of the script.mysqli_pconnect() – function is used for making a persistence connection with the database that does not terminate when the script ends.
Example
What is the use of imagetypes() method?
image types() – function returns the list of supported images of the installed PHP version. You can use this function to check if a particular image extension is supported by PHP or not.
Example
What is the use of strip_tags() method?
strip_tags() – function is used to retrieve the string from a text by omitting HTML, XML and PHP tags. This function has one mandatory parameter and one optional parameter. The optional parameter is used to accept particular tags.
Example
What is the difference between substr() and strstr()?
substr() and strstr()
substr() – function returns a part of the string based on the starting point and length. Length parameter is optional for this function and if it is omitted then the remaining part of the string from the starting point will be returned.strstr() – function searches the first occurrence of a string inside another string. The third parameter of this function is optional and it is used to retrieve the part of the string that appears before the first occurrence of the searching string.
How can you declare a constant variable in PHP?
define() – function is used to declare a constant variable in PHP. Constant variable declares without the $ symbol.
Example
hat is the difference between for and foreach loop in PHP?
for loop and foreach loop
for loop – is mainly used for iterating a pre-defined number of timesforeach loop – is used for reading array elements or MySQL result set where the number of iteration can be unknown.
Example 1
Example 2
How we can retrieve the data in the result set of MySQL using PHP?
mysql_fetch_rowmysql_fetch_arraymysql_fetch_objectmysql_fetch_assoc
What is Zend Engine?
Zend Engine is used internally by PHP as a compiler and runtime engine. PHP Scripts are loaded into memory and compiled into Zend opcodes.
These opcodes are executed and the HTML generated is sent to the client.
The Zend Engine provides memory and resource management, and other standard services for the PHP language. Its performance, reliability and extensibility played a significant role in PHP’s increasing popularity.
– ghhfhg
What are some new features introduced in PHP7?
Zend Engine 3 performance improvements and 64-bit integer support on Windows
uniform variable syntax AST-based compilation process
added Closure::call()
bitwise shift consistency across platforms
(null coalesce) operator
Unicode codepoint escape syntax
return type declarations
scalar type (integer, float, string and boolean) declarations.
Explain soundex() and metaphone().
soundex() and metaphone()
- soundex() – The soundex() function calculates the soundex key of a string. A soundex key is a four character long alphanumeric strings that represents English pronunciation of a word. The soundex() function can be used for spelling applications.
- metaphone() – The metaphone() function calculates the metaphone key of a string. A metaphone key represents how a string sounds if pronounced by an English person. This function can also be used for spelling applications.
Example 1
Example 2
How can we 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.
Remember that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.
What is smarty?
Smarty is a template engine written in PHP. Typically, these templates will include variables —like {$variable} — and a range of logical and loop operators to allow adaptability within of the template.
What is Memcache?
Memcache is a technology that caches objects in memory such that your web application can get to them really fast. It is used by sites such as Digg.com, Facebook.com and NowPublic.com and is widely recognized as an essential ingredient in scaling any LAMP.
Explain the difference between $message and $$message?
$message and $$message
$message – is used to store variable data. $$message can be used to store variable of a variable. Data stored in $message is fixed while data stored in $$message can be changed dynamically.$$message – $message is a variable and $$message is a variable of another variable. $$message allows the developer to change the name of the variable dynamically.
Example 1
Example 2
Explain how to get DNS servers of a domain name.
Include Net/DNS.php file in the beginning of the script
Create an object for DNS resolver by using $ndr = Net_DNS_Resolver()
Query the ip address using $ndr->search(“somesite.com”,”A”) and assign to a relevant variable. Ex: $result
Now, display the value of $result
What is the importance of “method” attribute in a html form?
“method” attribute determines how to send the form-data into the server.
There are two methods, get and post.
The default method is get.This sends the form information by appending it on the URL.
Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
What is the importance of “action” attribute in a html form?
The action attribute determines where to send the form-data in the form submission.
What is the use of “enctype” attribute in a html form?
The enctype attribute determines how the form-data should be encoded when submitting it to the server.
We need to set enctype as “multipart/form-data”when we are using a form for uploading files.
Is it possible to use COM component in PHP?
Yes, it’s possible to integrate (Distributed) Component Object Model components ((D)COM) in PHP scripts which is provided as a framework.
Explain how you can update Memcached when you make changes to PHP?
When PHP changes you can update Memcached by
Clearing the Cache proactively: – Clearing the cache when an insert or update is madeResetting the Cache: – It is similar to the first method but rather than just deleting the keys and waiting for the next request for the data to refresh the cache, reset the values after the insert or update.
Is it possible to extend the execution time of a PHP script?
The use of the set_time_limit(int seconds) enables us to extend the execution time of a PHP script. The default limit is 30 seconds.
How can we pass the variable through the navigation between the pages?
It is possible to pass the variables between the PHP pages using sessions, cookies or hidden form fields.
Is it possible to submit a form with a dedicated button?
It is possible to use the document.form.submit() function to submit the form.
For example: <input type=button value=”SUBMIT” onClick=”document.form.submit()”>
How to get no of arguments passed to a PHP Function?
func_get_args() – function is used to get number of arguments passed in a PHP function.
Example
How to access standard error stream in PHP?
You can access standard error stream in PHP by using following code snippet:
$stderr = fwrite(“php://stderr”);
$stderr = fopen(“php://stderr”, “w”);
$stderr = STDERR;
How to get the IP address of the client/user in PHP?
You can use $_SERVER[‘REMOTE_ADDR’] to get IP address of user/client in PHP, But sometime it may not return the true IP address of the client at all time.
Example
What is difference Between PHP 5 and 7?
There are many differences between PHP 5 and 7. Some of the main points are:
- Performance: – it is obvious that later versions are always better than the previous versions if they are stable. So, if you execute code in both versions, you will find the performance of PHP 7 is better than PHP5. This is because PHP 5 use Zend II and PHP & uses the latest model PHP-NG or Next Generation.
- Return Type: – In PHP 5, the programmer is not allowed to define the type of return value of a function which is the major drawback. But in PHP 7, this limitation is overcome and a programmer is allowed to define the return type of any function.
- Error handling: – In PHP 5, there is high difficulty to manage fatal errors but in PHP 7, some major errors are replaced by exceptions which can be managed effortlessly. In PHP 7, the new engine Exception Objects has been introduced.
- 64-bit support: – PHP 5 doesn’t support 64-bit integer while PHP 7 supports native 64-bit integers as well as large files.
- Anonymous Class: – Anonymous class is not present n PHP 5 but present in PHP 7. It is basically used when you need to execute the class only once to increase the execution time.
- New Operators: – Some new operators have added in PHP 7 such as <=> which is called a three-way comparison operator. Another operator has added is a null coalescing operator which symbol as?? and use to find whether something exists or not.
- Group Use declaration: – PHP 7 includes this feature whereas PHP 5 doesn’t have this feature.
What are access specifiers?
An access specifier is a code element that is used to determine which part of the program is allowed to access a particular variable or other information. Different programming languages have different syntax to declare access specifiers. There are three types of access specifiers in PHP which are:
- Private: – Members of a class are declared as private and they can be accessed only from that class.
- Protected: – The class members declared as protected can be accessed from that class or from the inherited class.
- Public: – The class members declared as public can be accessed from everywhere.
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.
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.
Explain mail function in PHP with syntax?
The mail function is used in PHP to send emails directly from script or website. It takes five parameters as an argument.
Syntax of mail (): mail (to, subject, message, headers, parameters);
to – refers to the receiver of the emailSubject – refers to the subject of an emailthe message – defines the content to be sent where each line separated with /n and also one line can’t exceed 70 characters.Headers – refer to additional information like from, Cc, Bcc. These are optional.Parameters – refer to an additional parameter to the send mail program. It is also optional
What is difference between md5 and SHA256?
Both MD5 and SHA256 are used as hashing algorithms. They take an input file and generate an output which can be of 256/128-bit size. This output represents a checksum or hash value. As, collisions are very rare between hash values, so no encryption takes place.
The difference between MD5 and SHA256 is that the former takes less time to calculate than later one.SHA256 is difficult to handle than MD5 because of its size.SHA256 is less secure than MD5MD5 result in an output of 128 bits whereas SHA256 result output of 256 bits.
What is the goto statement useful for?
The goto statement can be placed to enable jumping inside the PHP program. The target is pointed by a label followed by a colon, and the instruction is specified as a goto statement followed by the desired target label.
What is the goto statement useful for?
The goto statement can be placed to enable jumping inside the PHP program. The target is pointed by a label followed by a colon, and the instruction is specified as a goto statement followed by the desired target label.
What does the scope of variables mean?
The scope of a variable is the context within which it is defined. For the most part, all PHP variables only have a single scope. This single scope spans included and required files as well.
What does $_COOKIE mean?
$_COOKIE is an associative array of variables sent to the current PHP script using the HTTP Cookies.
What does $_ENV mean?
$_ENV is an associative array of variables sent to the current PHP script via the environment method.
What does $_FILES means?
$_FILES is an associative array composed of items sent to the current script via the HTTP POST method.