PHP Interview Questions

1 Which is the latest version of PHP

The latest stable version of PHP is 7.1.0 released at December 1, 2016 .

2 Define PHP

PHP is an open source server side scripting language used to develop dynamic websites . PHP stands for Hypertext Preprocessor , also stood for Personal Home Page . Now the implementations of PHP is produced by The PHP group .It was created by Rasmus lerdorf in 1995 . It is a free software released under the PHP license .

3 Who is the father of PHP

Rasmus Lerdorf known as the father of PHP . Php was created by Rasmus Lerdorf In 1995 .

4 What is the current version of Apache

The latest stable version of Apache is 2.4.16, released on 14th july 2015.

5 What is difference between unset and unlink.

Unset is used to delete(destroy) a variable whereas unlink used to delete a file.

6 What is the difference between array_merge and array_combine

array_merge merges the elements of one or more than one array such that the value of one array appended at the end of first array. If the arrays have same strings key then the later value overrides the previous value for that key .

Array_combine creates a new array by using the key of one array as keys and using the value of other array as values.<?php
$array1 = array("course1","course2");
$array2 = array(("php","html");
$new_array = array_combine($array1, $array2);
print_r($new_array);?>OUTPUT :
array
(
[course1] => php
[course2] => html
)

7 What is the difference between session and cookies

There are some difference between session and cookies thath are as following:-

1 : Session are temporary and Cookies are parmanent.

2 : Session data is store on server while Cookies are store on user's computer.

3 :Cookies contents can be easily modify but to modify Session contents is very hard.

4 :Cookies could be save for future reference but Session couldn't when user close the browser Session data also lost.

8 How we declare cookies and how we expire it

setcookie() function is used to set cookies in php.
To declare Cookies syntax will be:- setcookie(name, value, expire, path, domain);
name : Name of the cookie
value : Value of the cookie
expire : The time for cookie to expire
path : path to save the cookie where we want to save the cookie information
domain : domain name on which we want to save the cookie

e.g :setcookie("username","harry",time()+60*60*60*24);
In the above example the cookie name is username having value harry and set for one day .
To expire cookies we have set the time of cookie in past
To expire Cookies syntax will be: setcookie(name,value,time-3600);

9 What is use of var_dump

var_dump() function is used to display structured information(type and value) about one or more variable.

11 What is the difference between include() and require()

include() function gives the warning when specified file not found but all script will be continually executed.
e.g. <?php
include("filename.php");
echo "hello";

?>output:- hello
In the above example if file not found then it gives warning and print the hello because warning does not stop script and echo will be execute.require() function gives the fatal error when specifies file is not found and stop the script. e.g. <?php

require("filename.php");
echo "hello";
?>output:- it gives fatal error and stop the script ,echo will not be executed.

12 What is final class

final class is a class that can not be inherited.Its protect the methods of class to be overriden by the child classes.e.g. final class baseclass
{
public function mymethod() {
echo "baseclass method";
}

}

class derivedclass extends baseclass
{
public function mymethod() {

echo "derivedclass method";

}

}

$c= new derivedclass();
$c->mymethod();

In the above example base class is declared as final and hence can not be inherited.
derived class tries to extends baseclass then compile error will be generated.

13 What is difference between abstract class and interface classes

Interface : An interface does not contain any code,it contain only declaration of methods,properties,events. Interfaces allow us to code which specifies which methods a class must have implement . Interfaces defines with the word interface . All methods in interfaces must be public e.g : interface myItem

{

void Id();
string description();
string Runtest(int testnumber);

}

Abstract class : Abstract classes are look like interfaces.Abstract classes may contain code although it may also have abstract method that do not have code. Abstract classes defines only signature of the method ,not implementation. The child class which inherit the abstarct class must define all the abstarct methods of its parent class .

14 What is difference between echo() and print()

echo() and print() function both are used to show the output on the visitors screen but in echo we can take one or more parameters.

print() has a return value of true or false whereas echo has a void return type.

echo() is slightly faster than print.

15 What is the difference between PHP4 and PHP5

There are some difference between PHP4 and PHP5 that are as following:-

1) In PHP5 abstract classes are used but not used in PHP4.

2) In PHP5 interfaces are used but not used in PHP4.

3) In PHP5 visibility are used but not used in PHP4.

4) In PHP5 magic methods are used but not uesd in PHP4.

5) In PHP5 typehinting are used but not used in PHP4.

6) In PHP5 cloning are used but not used in PHP4.

7) In PHP5 construtor are written as __construct keyword but in PHP4 are written as class name.

16 How many types of errors in PHP

There are mainly three types of error in php. These are -

(1) Notice error

(2) Warning error

(3) Fatal error

Notice error happened when a variable not decleared but it is used.

Warning error occurred when a package not defined and some functionality has been used in the program.These are not serious errors, they continue the execution of script.

And Fatal error are those errors when an object call a class and the class not present there.These errors are serious error which can stop the execution of script

17 Why do we use ob_start()

Ob_start used to active the output buffering .When output buffering is on all output of the page sent at one time to the browser ,otherwise sometimes we face headers already sent type errors.

18 What is a .htacces file

.htaccess is a configuration file running on Apache server.These .htaccess file used to change the functionality and features of apache web server .

e.g .htaccess file used for url rewrite .

.htaccess file used to make the site password protected.

.htaccess file can restrict some ip addresses ,so that on restricted ip adresses site will not open.

19 Is PHP an interpreted language or compiler language

PHP is an interpreted language.

20 What is the difference between compiler language and interpreted language

Interpreted language executes line by line , if there is some error on a line it stops the execution of script.
Compiler language can execute the whole script at a time and gives all the errors at a time. It does not stops the execution of script ,if there is some error on some line.

21 What are web services in PHP

Web services converts our applicaton into a web-application ,which can publish its functions and messages to the internet users.The main web services platform is XML and HTTP.Web services can be published ,found and used through web.

22 What is static methods and properties in PHP

A static method is accessible without needing instantiation of a class. It means there is no need to make an object to call the static methods .Static methods and properties can be directly call from its class name with (::) a scope resolution operator. They cannot be call from the object of its class. We need static methods to overcome long overhead of instantiation of classes .e.g
<?php

23 What is static methods and properties in PHP

A static method is accessible without needing instantiation of a class. It means there is no need to make an object to call the static methods .Static methods and properties can be directly call from its class name with (::) a scope resolution operator. They cannot be call from the object of its class. We need static methods to overcome long overhead of instantiation of classes . e.g <?php

24 What is type hinting in PHP

Type hinting means the function specifies what type of parameters must be and if it is not of the correct type an error will occur.PHP 5 introduces type hinting and the functions are able to force the parameters to be objects, interfaces ,array .

25 Is multiple inheritance supported in PHP

No, multiple inheritance is not supported by PHP

26 How can we define constants in PHP

In PHP we can define constants with the keyword define .

e.g :<?PHPdefine(‘SiteName’,’Letsknowit.com’);

echo ‘You are visiting’ .Sitename;?>

OUTPUT : You are visiting Letsknowit.com

27 How can we change the time zones using PHP

We can change the time zones by using date_default_timezone_set() function.e.g :

<?php

date_default_timezone_set('America/Los_Angeles');

?>

28 How to read the contents of a file in PHP

<?php

$fileName = 'instructions.txt';

$file = fopen(“instructions.txt”,”r”) or exit(“Unable to open the file!”) ;
While( ! feof($file) ) // feof()checks the end of file in php
{echo fgets($file); // fgets() read a fileline by line in php

}
fclose($file); // fclose() used to close a file in php?>

29 How to read a file character by character

<?phpfgetc() function is used to read a file character by character.e.g.
While(!feof($file)) // feof()checks the end of file in php
{
echo fgetc($file); // fgetc() read a file character by character in PHP
}?>

30 Define PHP filter

PHP filter is used to validate the data coming from different sources like the user’s input.
It is important part of a web application to test, validate the data coming from insecure sources.
We have different functions to validate the data:

filter_var();filter_var_array(); filter input();filter_input_array();

31 Which function is used to remove HTML tags from data

Strip_tags() function is used to remove html tags. e.g :<?php

$data = '<p>Web Development</p>' ;

echo $profession = strip_tags($data); // It will remove the <p> tag from output.?>

33 Why we use nl2br()

nl2br inserts HTML line breaks(<br/>) before all new lines in a string .e.g :<?php
echo nl2br(“Thanks for visiting letsknowit.com /n see you soon .”);?> OUTPUT : Thanks for visiting letsknowit.com <br/>
See you soon .

34 What is ajax and how it is useful to us

Ajax is termed as Asynchronus javascript and XML .It is used for creating fast and dynamic web pages.With ajax it is possible to be update part of web page asynchronously (in the background) without refreshing the whole page.It is used on client side to create asynchronus web appliation

35 What is differnce between HTML and XHTML

2 :HTML permit the omission of certain tags and use attribute minimization whereas XHTML does not permit the omission of any tag .A XML document must be well formed ,means there must be an end tag for every start tag.

36 What is the reason behind selecting LAMP for web development

The main reason behind selecting LAMP is :
All are open sources and free to use.
The security of LINUX is much more than windows operating system.
The Apache server have better security and functionality compared to Apache .
MySql is a world wide open source database and enrich in functionality and security .
PHP is an open source and free to use.It is faster than any other scripting languages

37 How to execute PHP through command line Interface

In CLI we have to provide the script file name started with PHP tag as a command line argument and it runs after press enter .e.g :

php index.php

38 What are magic methods in PHP.

Magic methods are very easy to identify, that every magical method name is started with double underscore( __)sign. We can not declare any user-defined functions with __ sign.

44 How to get the names of all included and required files for a particular page in PHP

The function get_included_files () function is used to get the names of all required and included files in a page . It returns an array with the names of included and required files in a page

45 What is end function in PHP

End function can set the pointer of an array to the last element of array.e.g : <?php
$arr = array('name'=>'angel' ,'city'=>'delhi' ,'profession'=>'web developer');
$lastValue = end($arr);?>OUTPUT : web developer

46 How to get the number of elements in an array

We have two functions to get the number of elements in an array ie count() and sizeof().Synatx : count ($array_name) and sizeof($array_name)

47 Why we use strpos in PHP

Strpos used to find the first occurrence of a string in another string.It return the position of the substring in a string . If the searched string will not exists in the searching string it return false.Synatx : strpos(‘stringtosearchin’ ,’stringtosearch’);
e.g :<?php

53 What is difference between single quotes and double quotes in php

When string is in single quotes php will not evaluate it . If there is a string with single quotes and if we place a variable in that it would not substitute its value in string, whereas double quotes support variable expansion. If we place variable in double quotes it would substitute its value in string.

<?php

$str = 1;echo '$str is a value'; // OUTPUT : $str is a valueecho "$str is a value"; //OUTPUT : 1 is a value

?>

54 How can we resolve maximum allocation time exceeds error

We can resolve these errors through php.ini file or through .htaccess file.

1. From php.ini file increase the max_execution_time =360 (or more according to need)

and change memory_limit =128M (or more according to need)

2. From php file we can increase time by writing ini_set(‘max_execution_time’,360 ) at top of php page to increase the execution time.

57 What is output of this code:

when the string is evaluated in numeric context it works like: if a string does not contain any of the character 'e', 'E,' and valid numeric value(int type), it will be evaluated as a integer otherwise will be a float.

the value taken by the initial string portion. if it has valid numeric then that value will be taken otherwise value will be 0. This is the case here happening.

58 What will be the output of following.

59 How to find first array elements which are missing in second array.

<?php

$array1 = array("a" => "green", "red", "blue", "red");

$array2 = array("b" => "green", "yellow", "red");

$result = array_diff($array1, $array2);

print_r($result);

?>

60 what is headers already sent error , why we encounter this and how it can be resolved?

A web page is composed of two parts, the header and the body. An error is seen like something:

Warning: Cannot modify header information – headers already sent by (output started at /home/usr1/public_html/sent.php:42) in /home/usr1/public_html/includes/theme-header.php on line 12

Header is generated automatically containing information related to server, cookies. Sometimes programmers want to change some of the header values. For example, if the PHP if generating XML output, the Content-Type should be changed to reflect this. Another common example is in redirecting the user’s browser to a different web page using the Location header element.

The header must come first in the response from a web server and is separated from the body by one blank line. The reason this error occurs is that some part of the body of the web page has been sent to the user already when a request is made to set a header value. Because PHP simplifies many things for you, the problem may be hiding in plain site. Here are some guidelines for finding the problem:

1) Find the header () statement that is causing the problem. The error must be at or before this line.

2) Look for any statements that could send output to the user before this header statement. If you find one or more, change your code to move the header statement before them. Complex conditional statements may complicate the issue, but they may also help solve the problem. Consider a conditional expression at the top of the PHP script that determines the header value as early as possible and sets it there.

3) Make sure there is no white space outside of the PHP start and end tags. While a blank line before the <?php start tag may look innocent, when processed by PHP, it will turn into an echo statement printing out a blank line.

61 Why we use extract() in PHP ?

The extract() function imports variables into the local symbol table from an array.

extract function uses array keys as variable names and array values as variable values. For each element of array it will create a variable in the current symbol table.

62 What will be the output ?

$num =10;

function multiply(){ $num =$num *10; } multiply(); echo $num;

63 Why we use list() function in PHP ?

List() function is used to assign values to a list of variable in one operation and list only works on numerical arrays.

<?php

$varArray = array("PHP","MYsql","Jquery");

list($a, $b, $c) = $varArray;

echo "I have knowledge of $a,$b and $c.";

?>

OUTPUT : I have knowledge of PHP,MYsql and Jquery.

64 What is use of $this in PHP Classes

$this is called pseudo variable and this is availabel when a method is called from within an Object context.

$this is refrence to the calling object of the current class. When we need to call a method of a class

within the same class instead of creating object of that class we can use $this to call the method of the existing class.

<?php

Class A

{

public function getName()

{

$name = '';

return $name;

}

public function getUserDetails()

{

$this->getName();// to call the other method of the class we can use this operator.

}

}

$obj = new A();

echo $obj->getUserDetails();

?>

65 What is PHP sessions default timeout.

The default session timeout is 24 minutes (1440 seconds),

however we can change this value by setting session.gc_maxlifetime() in php ini file.

66 What is autoloading classes in PHP

With autoloaders PHP is given a last chance to load the class or interface before it fails with an error. spl_autoload_register() function registers any number of autoloaders , enabling for classes and interfaces to be automatically loaded if they are not defined

e.g :

<?php

spl_autoload_register(function ($classname) {

include $classname . '.php';

});

$object = new Class1();

$object2 = new Class2();

?>

In the above example we do not need to include class1.php and class2.php . spl_autoload_register() function will automatically load class1.php and class2.php .

67 How to refresh a page using HTML

To refresh the page using HTML we can use META to refresh the page or to redirect to other page after certain period of time.

To refresh the page we can use

<head>

<meta http-equiv="refresh" content="15">

</head>

Then the page will refresh after every 15 seconds.

To redirect to other url we can use below code.

<head>

<meta http-equiv="refresh" content="15" URL="target.html">

</head>

From the above code the page will refresh after 15 seconds, and new URL will be target.html

68 How would you find the number of repeated characters in a given string "abcabcxyz"

Here we are giving the search string in a variable and in substr() function we will provide the length of the string we are searching for. we can search for a single character also and editing the length to one in substr() function.

<?php

$text="abcabcxyz";

$search_char="abc";

$count="0";

for($x="0"; $x< strlen($text); $x++)

{

if(substr($text,$x,3)==$search_char)

{

$count=$count+1;

}

}

echo "count of string is". $count;

?>

69 How would you separate numbers and character from a given string "68vfdksh90930hkjnvkj93890" .

Here we are using preg_replace() function .

<?php

$string = "68vfdksh90930hkjnvkj93890";

$numbers = preg_replace('/[^0-9]/', '', $string);

$chars = preg_replace(/[^a-zA-Z]/', '', $string);

echo 'Numbers are :'. $numbers;

echo '<br/>';

echo 'Charcaters are:'.$chars;

?>

70 How to get the extesnion of a file in PHP

We can get a file extension in following ways.

1. $filename = $_FILES['image']['name'];

$ext = pathinfo($filename, PATHINFO_EXTENSION);

2. $filename = $_FILES['image']['name'];

$array = explode('.', $filename);

$ext = end($array);

71 What is difference between var_dump and print_r

var_dump function displays structured information about variables including its type,size and value

78 What is the output?

79 what will be output of following?$a=024;echo $a/4;

PHP will consider 024 as octal number which is equivalent to decimal 20

80 Define WSDL,SOAP and REST.

A WSDL is an XML document that describes a web service.

It actually stands for Web Services Description Language.WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract and so on

SOAP is an XML-based protocol that lets you exchange info over a particular protocol (can be HTTP or SMTP, for example) between applications. It stands for Simple Object Access Protocol and uses XML for its messaging format to relay the information.

REST is an architectural style of networked systems and stands for Representational State Transfer.

It's not a standard itself, but does use standards such as HTTP, URL, XML, etc