The demand for PHP jobs
is increasing day by day. People who are searching or preparing for PHP jobs,
have to face some common questions in the interview. So, if you are a fresher
and want to make your career as PHP developer then you must read this article
to increase your chance to get PHP job easily and fast. Most common PHP
interview questions are discussed in this article with answers.
Q#01. What is PHP?
PHP is one of the
popular server-side scripting languages for developing the web application. The
full form of PHP is Hypertext Preprocessor. It is used by embedding HTML to
create dynamic content, communicate with a database server, handling session
etc.
Q#02.
Why do we use PHP?
There are many 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 with minimal cost. It supports multiple
databases. 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 easier than before.
Q#03. Is PHP a strongly typed language?
No. PHP is a weakly
typed or loosely typed language. That means PHP does not require to declare
data types of the variable when you declare any variable like 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 the numeric value in that
same variable then data type is Integer.
Sample
code:
$var =
"Hello"; //String
$var =
10; //Integer
Q#04. What is mean by variable variables in PHP?
When the value of a
variable is used as the name of other variables then it is called variable
variables. $$ is used to declare variable variables in PHP.
Sample
code:
$str =
"PHP";
$$str =
" Programming"; //declaring variable variables
echo
"$str ${$str}<br/>"; //It will print "PHP programming"
echo
"$PHP"; //It will print "Programming"
Q#05. What are the differences between echo and
print?
Both echo and print method prints the output in the browser but there is a
difference between these two methods. echo
does not return any value after printing the output and it works faster than
print method. print method is slower
than echo because it returns boolean value after printing the output.
Sample
code:
echo
"PHP Developer<br/>";
$n =
print "Java Developer<br/>";
Q#06. How can you execute PHP script from command
line?
You have to use php command in command line to execute
PHP script. If the PHP file name is test.php
then the following command is used to run the script from command line.
phptest.php
Q#07. How can you declare the array in PHP?
You can declare three
types of arrays in PHP. These are numeric,
associative and multidimensional
arrays.
Sample
code:
//Numeric
Array
$computer
= array("Dell", "Lenavo", "HP");
//Associative Array
$color = array("Sithi"=>"Red",
"Amit"=>"Blue",
"Mahek"=>"Green");
//Multidimensional Array
$courses
= array ( array("PHP",50), array("JQuery",15),
array("AngularJS",20) );
Q#08.
What are the uses of explode() and implode() functions?
explode()
function
is used to split a string into an array and implode() function is used to make string by combining array
elements.
Sample
code:
$text =
"I like programming";
print_r
(explode(" ",$text));
$strarr =
array('Pen','Pencil','Eraser');
echo
implode(" ",$strarr);
Q#09.
Which function can be used to exit from the script after displaying the error
message?
You can use exit() or die() function to exit from the current script after displaying the
error message.
Sample
code:
if(!fopen('t.txt','r'))
exit("<br/>Unable to open the file");
Sample code:
if(!mysqli_connect('localhost','user','password'))
die("<br/>Unable to connect with the
database");
Q#10.
Which function is used in PHP to check the data type of any variable?
gettype() function is
used to check the data type of any variable.
Sample
code:
echogettype(true).'<br>';
//boolean
echogettype(10).'<br>';
//integer
echogettype('Web
Programming').'<br>'; //string
echogettype(null).'<br>';
//NULL
Q#11.
How can you increase the maximum execution time of script in PHP?
You will require to
change the value of the
max_execution_timedirective in php.ini file for increasing maximum
execution time. For example, if you want to set the max execution time for 120
seconds then set the value as follows,
max_execution_time
= 120
Q#12.
What are mean by passing the variable by value and reference in PHP?
When the variable is
passed as value then it is called pass variable by value. Here, the main
variable remains unchanged when the passed variable changes.
Sample
code:
functiontest($n)
{
$n=$n+10;
}
$m=5;
test($m);
echo $m;
When the variable is
passed as the reference then it is called pass variable by reference. Here,
both the main variable and passed variable share the same memory location and &is used for reference. So, if one
variable changes then other will change.
Sample
code:
function
test(&$n) {
$n=$n+10;
}
$m=5;
test($m);
echo $m;
Q#13.
What are type casting and type juggling?
The way by which PHP
can assign a particular data type for any variable is called type casting. The
required type of variable is mentioned in the parenthesis before the variable.
Sample
code:
$str =
"10"; // $str is now string
$bool =
(boolean) $str; // $bool is now boolean
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.
Sample
code:
$val = 5;
// $val is now number
$val =
"500" //$val is now string
Q#14. How can you make connection with MySQL server
using PHP?
You have to provide MySQL
hostname, username and password to make the connection with MySQL server in mysqli_connect() method or declaring
database object of mysqli class.
Sample
code:
$mysqli =
mysqli_connect("localhost","username","password");
$mysqli =
new mysqli("localhost","username","password");
Q#15.
How can you retrieve data from MySQL database using PHP?
Many functions are
available in PHP to retrieve data from MySQL database. These are mentioned
below.
mysqli_fetch_array() – It is used to fetch records as a numeric array
or an associative array.
Sample
code:
// Associative or Numeric array
$result=mysqli_query($DBconnection,$query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
echo "Name is $row[0] <br/>";
echo "Email is $row['email'] <br/>";
mysqli_fetch_row() – It is used to fetch records as a numeric array.
Sample
code:
//Numeric array
$result=mysqli_query($DBconnection,$query);
$row=mysqli_fetch_array($result);
printf ("%s %s\n",$row[0],$row[1]);
mysqli_fetch_assoc() – It is used to fetch records as an associative
array.
Sample
code:
// Associative array
$result=mysqli_query($DBconnection,$query);
$row=mysqli_fetch_array($result);
printf ("%s
%s\n",$row["name"],$row["email"]);
mysqli_fetch_object() – It is used to fetch records as an object.
Sample
code:
// Object
$result=mysqli_query($DBconnection,$query);
$row=mysqli_fetch_array($result);
printf ("%s %s\n",$row->name,$row->email);
Q#16.
What are the differences between mysqli_connect and mysqli_pconnect?
mysqli_pconnect()
function
is used for making persistence connection with the database that does not
terminate when the script ends. mysqli_connect()
function searches any existing persistence connection first if no persistence
connection exists then it will create a new database connection and terminate
the connection at the end of the script.
Sample
code:
$DBconnection =
mysqli_connect("localhost","username","password","dbname");
// Check for valid connection
if (mysqli_connect_errno())
{
echo "Unable to connect with MySQL: " . mysqli_connect_error();
}
// Check for valid connection
if (mysqli_connect_errno())
{
echo "Unable to connect with MySQL: " . mysqli_connect_error();
}
mysqli_pconnect() function is deprecated in the new version of
PHP, but you can create persistence connection using mysqli_connect with the
prefix p.
Q#17.
Which function is used in PHP to count the total number of rows returned by any
query?
mysqli_num_rows()
function is used to count the total number of rows returned by the query.
Sample
code:
$mysqli =
mysqli_connect("hostname","username","password","DBname");
$result=mysqli_query($mysqli,"select
* from employees");
$count=mysqli_num_rows($result);
Q#18.
How can you create session in PHP?
session_start()
function is used in PHP to create session.
Sample
code:
session_start();
//Start session
$_SESSION['USERNAME']='Fahmida';
//Set a session value
unset($_SESSION['USERNAME'];
//delete session value
Q#19.
What is the use of imagetypes() method?
imagetypes()
function returns the list of supported images of the installed PHP version. You
can use this function to check particular image extension is supported by PHP
or not.
Sample
code:
//Check
BMP extension is supported by PHP or not
if (imagetypes() & IMG_BMP) {
echo "BMP extension Support is enabled";
}
echo "BMP extension Support is enabled";
}
Q#20.
Which function you can use in PHP to open a file for reading or writing or for
both?
You can use fopen() function to read or write or
both in PHP.
Sample
code:
$file1 =
fopen("myfile1.txt","r"); //Open for reading
$file2 =
fopen("myfile2.txt","w"); //Open for writing
$file3 =
fopen("myfile3.txt","r+"); //Open for reading and writing
Q#21.
What is the difference between include() and require()?
Both include() and require() function are used for including PHP script from a file to
another file. But there is a difference between these functions. If any error
occurs at the time of including a file using include() function then it continues the execution of the script
after showing the error message. require()
function stops the execution of the script by displaying the error message if
an error occurs.
Sample
code:
if
(!include(‘test.php’)) echo “Error in file inclusion”;
if
(!require(‘test.php’)) echo “Error in file inclusion”;
Q#22.
Which function is used in PHP to delete a file?
unlink()
function is used in PHP to delete any file.
Sample
code:
unlink('filename');
Q#23.
What is the use of strip_tags() method?
strip_tags()
function is used to retrieve 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.
Sample
code:
//Remove
all tags from the text
echo
strip_tags("<b>PHP</b> is a popular
<em>scripting</em> language");
//Remove
all tags excluding <b> tag
echo
strip_tags("<b>PHP</b> is a popular
<em>scripting</em> language","<b>");
Q#24.
How can you send HTTP header to the client in PHP?
header()
function is used to send raw HTTP header to a client before any output is sent.
Sample
code:
header('Location:
http://www.your_domain/');
Q#25.
Which functions are used to count the total number of array elements in PHP?
count()
and sizeof() functions can be used
to count the total number of array elements in PHP.
Sample
code:
$names=array(“Asa”,”Prinka”,”Abhijeet”);
echo count($names);
echo count($names);
$marks=array(95,70,87);
echo sizeof($marks);
echo sizeof($marks);
Q#26.
What is the difference between 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 is string inside another string. The third
parameter of this function is optional and used to retrieve the part of the
string that appears before the first occurrence of the searching string.
Sample
code:
echosubstr("Computer
Programming",9,7); //Returns “Program”
echo
substr("Computer Programming",9); //Returns “Programming”
Sample
code:
echo
strstr("Learning Laravel 5!","Laravel"); //Returns Laravel
5!
echo
strstr("Learning Laravel 5!","Laravel",true); //Returns
Learning
Q#27.
How can you upload a file using PHP?
To upload a file by
using PHP, you have to do the following tasks.
1. Enable
file_uploads directive
Open
php.ini file and find out file_uploads directive and make it on.
file_uploads = On
2. Create
an HTML form using enctype attribute and file element for uploading the file.
<form
action="upload.php" method="post"
enctype="multipart/form-data">
<input
type="file" name="upd" id="upd">
<input
type="submit" value="Upload" name="upload">
</form>
3. Write
PHP script to upload the file
if
(move_uploaded_file($_FILES["upd"]["tmp_name"],
"Uploads/")) {
echo "The file
". basename( $_FILES["upd"]["name"]). " is
uploaded.";
} else {
echo "There is an
error in uploading.";
}
Q#28.
How can you declare the constant variable in PHP?
define()
function is used to declare constant variable in PHP. Constant variable
declares without $ symbol.
Sample
code:
define("PI",3.14);
Q#29.
Which function is used in PHP to search a particular value in an array?
in_array()
function is used to search a particular value in an array.
Sample
code:
$languages
= array("C#", "Java", "PHP", "VB.Net");
if
(in_array("PHP", $languages))
{
echo "PHP is in the list";
}
else {
echo "php is not in the list";
}
Q#30.
What is the use of $_REQUEST variable?
$_REQUEST
variable is used to read data from the submitted HTML form.
Sample
code:
Here, $_REQUEST variable is used to read the
submitted form field with the name ‘username’.
If the form will submit without any value then it will print “Name is empty”, otherwise it will print
the submitted value.
<?php
if
(isset($_POST['submit'])) {
// collect value of input field
$name = $_REQUEST['username'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
else
{
?>
<form
method="post" action="#">
Name: <input type="text"
name="username">
<input
type="submit" name="submit">
</form>
<?php
} ?>
Q#31.
What is the difference between for and foreach loop in PHP?
for
loop is mainly used for iterating pre-defined number of times and foreach loop is used for reading array
elements or mysql resultset where the number of iteration can be unknown.
Sample
code:
//Loop will iterate
for 5 times
for ($n
= 0; $n <= 5; $n++) {
echo "The number is: $n <br>";
}
echo "The number is: $n <br>";
}
Sample
code:
//Loop
will iterate based on array elements
$parts
= array("HDD", "Monitor", "Mouse", "Keyboard");
foreach ($parts as $value) {
echo "$value <br>";
}
foreach ($parts as $value) {
echo "$value <br>";
}
Q#32. How long does a PHP session last for?
By
default, session data last for 24 minutes or 1440 seconds in PHP. But if you
want you can change the duration by modifying the value of gc_maxlifetime directive in php.ini
file. To set the session time for 30 minutes, open php.ini file and set the
value of gc_maxlifetime directive as
follows,
gc_maxlifetime =
1800
Q#33. What is the difference between “= =” and “= = =”
operators.
“= =” is called equivalent operator
that is used to check only the equivalency of two values butnot the data types.
Sample
code:
10 and “10” are
equivalent by values. So the if condition will be true and print “n is equal to 10”.
$n = 10;
if ($n ==
"10")
echo "n is equal to 10";
//This will print
else
echo "n is not equal to
10";
“= = =” is called strictly
equivalent operator that is used to check the equivalency of two values by
comparing both data types and values.
Sample
code:
10 and “10” are equal
by values but not equal by data type. One is string and one is number. So, if condition will be false and print “n is not equal to 10”.
$n = 10;
if ($n ===
"10")
echo "n is equal to 10";
else
echo "n is not equal to
10"; //This will print
Q#34. Whichoperator is used to combine string values in PHP?
Two or more string values can be
combined by using ‘.’ operator.
Sample
code:
$val1 =
"Software ";
$val2 =
"Testing";
echo $val1.$val2; //
The output is “Software Testing”
Q#35. What is PEAR?
The
full form of PEAR “PHP Extension and
Application Repository”. Anyone can download reusable PHP components by
using this framework freely. It contains different types of packages from
different developers.
The
URL address of PEAR is,
Q#36. What type of errors can be occurred in PHP?
Different types of errors can occur
in PHP. Some major error types are mentioned here.
Fatal Errors– The
execution of the script stops when this error occurs.
Sample
code:
In the following
script, f1() function is declared
but f2() function is called which is
not declared. The execution of the
script will stop when f2() function
will call. So, “Testing Fatal Error”
will not be printed.
function f1(){
echo "function 1";
}
f2();
echo “Testing Fatal
Error”;
Parse Errors- This
type of error occurs when the coder uses wrong syntax in the script.
Sample code:
Here, semicolon(;) is missing at
the end of the first echo statement.
echo "This is a
testing script<br/>"
echo
"error";
Warning Errors- This
type of error does not stop the execution of the script. It continues the
script after displaying the error.
Sample code:
In the
following script, if test.txt file
does not exist in the current location then a warning message will display to
show the error and print “Opening File”
text by continuing the execution.
$handler =
fopen("test.txt","r");
echo "Opening
File";
Notice Errors- This
type of error shows the minor error of the script and continues the execution
after displaying the error.
Here, the variable, $a is defined
but $b is not defined. So, a notice of undefined variable will display for “echo $b” statement and print “Checking notice error” by continuing
the script.
Sample code:
$a = 100;
echo $b;
echo "Checking
notice error";
Q#37. Does PHP support multiple inheritances?
PHP does not support multiple
inheritances. To implement the features of multiple inheritances, the interface
is used in PHP.
Sample code:
Here,
two interfaces, Isbn and Type are declared and implemented in a
class, book Details to add the
feature of multiple inheritances in PHP.
interface Isbn {
public function setISBN($isbn);
}
interface Type{
public function setType($type);
}
class bookDetails
implements Isbn, Type {
private $isbn;
private $type;
public function setISBN($isbn)
{
$this -> isbn = $isbn;
}
public function setType($type)
{
$this -> type = $type;
}
}
Q#38. 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 in the visitor's computer.
Session variable can store more data than cookie variable. Session data are
stored in $_SESSION array and Cookie data are stored in $_COOKIE array. Session
values are removed automatically when the visitor closes the browser and cookie
values are not removed automatically.
Q#39. 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 SQL
statement.
Sample code:
$DBconnection=mysqli_connect("localhost","username","password","dbname");
$productName =
mysqli_real_escape_string($con, $_POST['proname']);
$ProductType =
mysqli_real_escape_string($con, $_POST['protype']);
Q#40. Which functions are used to remove whitespaces from the
string?
There are three functions in PHP to
remove whitespaces from the string.
trim() – it removes whitespaces
from the left and right side of the string.
ltrim() – it removes whitespaces
from the from the left side of the string.
rtrim() – it removes whitespaces
from the from the right side of the string.
Sample code:
$str = " Tutorials for your help ";
$val1 = trim($str);
$val2 = ltrim($str);
$val3 = rtrim($str);
41. What is
persistence cookie?
The cookie file that is stored permanently in the browser is
called persistence cookie. It is not secure and used for tracking visitor for
long times. This type of cookie can be declared as follows,
setccookie ("cookie_name", "cookie_value", strtotime("+2 years");
42. How does the
cross-site scripting attack can be prevented by PHP?
Htmlentities() function of PHP can be used for preventing
cross-site scripting attack.
43. Which PHP global
variable is used for uploading a file?
$_FILE[] array contains all information of the uploaded
file. The use of various indexes of this array is mentioned below.
$_FILES[$fieldName]['name']
– Keeps the original file name.
$_FILES[$fieldName]['type'] – Keeps the file type of the uploaded file.
$_FILES[$fieldName]['size'] – Stores the file size in bytes.
$_FILES[$fieldName]['tmp_name'] – Keeps the temporary file name which is used to store the file in the server.
$_FILES[$fieldName]['error'] – Contains error code related to the error thatappears during the upload.
$_FILES[$fieldName]['type'] – Keeps the file type of the uploaded file.
$_FILES[$fieldName]['size'] – Stores the file size in bytes.
$_FILES[$fieldName]['tmp_name'] – Keeps the temporary file name which is used to store the file in the server.
$_FILES[$fieldName]['error'] – Contains error code related to the error thatappears during the upload.
44. What are mean 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 access by
the parent class only.
Ø
Protected- variables, classes, and methods which
are declared protected can be access 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 child class to
declare the same item again.
45.How image properties can 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.
46.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.
47. What
is garbage collection?
It is an automated feature of PHP. When it runs, it removes all sessions
data which are not accessed for long times. It runs on /tmp directory which is the default session directory. PHP
directives which are used for garbage collection are,
Ø session.gc_maxlifetime (default value, 1440)
Ø session.gc_probability (default value, 1)
Ø session.gc_divisor (default value, 100)
48. 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, such as
rotating image, cropping an image, creating image thumbnail etc.
49. What is URL rewriting?
Appending the session ID in every local URL of the requested page for
keeping 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.
50. 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, the developer can easily switch from one database server to other. But it
does not support all advanced features of the new MySQL server.
Hope, this article will increase your
confidence level to face PHP interview. Thank you.
PHP is used to create dynamic websites with the help of web-based language scripts. If you are also looking to set your career path in the field of PHP development, then you must see our list of PHP Interview Questions which includes all the questions often asked in the PHP interview.
ReplyDeleteAll in all, if someone is going to work as a programmer, these questions can be useful. I think that one of the tasks can also be application transformation into some other form. Finally, such a person must have a very good understanding of the IT industry, because in that case he will create all kinds of software.
ReplyDelete