PHP is an acronym for PHP Hypertext Preprocessor. It is a widely implemented open-source programming language which is used in creating dynamic websites and mobile API’s.
In this article, you can go through the set of PHP interview questions most frequently asked in the interview panel. This will help you crack the interview as the topmost industry experts curate these at HKR trainings.
Let us have a quick review of the PHP interview questions.
Ans: PHP is a server-side scripting language generally used for web applications. PHP has many frameworks and cms for creating websites. Even a non-technical person is able to create the sites using its CMS.WordPress, osCommerce which are the famous CMS of PHP. It is also an object-oriented programming language like java, C-sharp etc. It is very easy for learning.
Ans: There are eight different data types of PHP used to construct the variables.
Integers: These are the whole numbers, without a decimal point, like 4195.
Doubles: These are the floating-point numbers, like 3.14159 or 49.1.
Booleans: This type will have only two possible values either true or false.
NULL: It is a special type that only has one value: NULL.
Strings: These are sequences of characters, like ‘PHP supports string operations.’
Arrays: These are named and indexed collections of other values.
Objects: These are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
Resources: These are special variables that hold references to resources external to PHP.
Ans: The constructor and destructor are special type functions in PHP which are automatically called when a PHP class object is created and destroyed. The constructor is the most useful among these two because it allows you to send parameters along while creating a new object, which can then be used to initialize variables on the object. The below example of constructor and destructor in PHP.
Example:
}
public function setLink(Foo $link){
$this->;link = $link;
}
public function __destruct() {
echo 'Destroying: ', $this->name, PHP_EOL;
}
}
?>
Ans: PEAR means “PHP Extension and Application Repository”. it extends PHP and provides a higher level of programming for web developers
Ans: There are three different types of Arrays in PHP.
Indexed Array: An array with a numeric index is known as the indexed array. Here the values are stored and accessed in a linear fashion.
Associative Array: An array with strings as the index is known as the associative array. This stores element values in association with key values rather than in strict linear index order.
Multidimensional Array: An array which contains one or more arrays is known as a multidimensional array. The values are accessed using multiple indices.
Ans: Singly quoted strings are literally treated, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.
Example:
$variable = "name";
$statement = 'This $variable will not print!n';
print($statement);
print "
;"
$statement = "This $variable will print!n"
print($statement);
?>
Output:
My $variable will not print!
My name will print
Ans:
The below statement is used for executing an SQL query.
$my_qry = mysql_query(“SELECT * FROM `users` WHERE `u_id`=’1′; “);
The below statement is used for fetching the result of SQL query.
$result = mysql_fetch_array($my_qry);
The below statement is used for printing the result of the SQL query.
echo $result[‘First_name’];
Ans:
Echo:
Print:
Ans: To be able to display the output directly to the browser, we have to use the special tags .
Ans: PHP 5 presents many additional OOP (Object Oriented Programming) features.
Ans: PHP includes only single inheritance, it means that a class can be extended from only one single class using the keyword ‘extended’.
Ans: ‘Final’ is introduced in PHP5. Final class means that this class cannot be extended and a final method cannot be override.
Ans: We use the operator ‘==’ to test is two object are instanced from the same class and have same attributes and equal values. We can test if two object are refering to the same instance of the same class by the use of the identity operator ‘===’.
Ans: It is possible to generate HTML through PHP scripts, and it is possible to pass information’s from HTML to PHP.
Ans: Both “$var” and “$$var” are variables. The “$var” is a variable with a fixed name while ”$$var” is a variable whose name is stored in “$var”.
Example: If “$var” contains “message” then “$$var” is the same as “$message”.
Explore HP Sample Resumes Download & Edit, Get Noticed by Top Employers !
Ans:
Example:
function thisFuncTakesACallback($callbackFunc)
{
echo "I'm going to call $callbackFunc!
";
$callbackFunc();
}
function thisFuncGetsCalled()
{
echo "I'm a callback function!
";
}
thisFuncTakesACallback( 'thisFuncGetsCalled' );
?>
Ans: Run the PHP CLI (Command-line Interface) program and provide the PHP script file name as the command-line argument.
Example:
php myScript.php
Assuming php as the command to invoke the CLI program.
Keep in mind that if the PHP script is written for the Web CGI interface, it may not execute properly in the command-line environment.
Ans:
A form can be submitted without any button in the following ways.
Example: document.form_name.submit()
2. Submitting using a Hyperlink. On clicking the link, a JavaScript function can be called.
Example:
3. A form can be also be submitted in the following ways without using any submit button:
4. By using the header(“location:page.php”);
Ans: The PDF files are created with PDF functions by using PDFlib version 6. PDFlib offers an object-oriented API for PHP5 in addition to the function-oriented API for PHP4.
There is also the » Panda module.
FPDF is a PHP class, which allows generating PDF files with pure PHP, without using PDFlib. F from FPDF stands for Free, it can be used for any requirement and modify them to suit the needs. FPDF doesn’t require any extension except zlib to activate compression and GD for GIF support and it works with PHP4 and PHP5.
Ans: The “crypt()” function is used to create one-way encryption. It takes one input string and one optional parameter. The function is defined as
crypt(input_string, salt)
where “input_string” consists of the string that has to be encrypted and “salt” is an optional parameter.
The PHP uses DES for encryption. The format is as follows:
$password=crypt('hkrtrainings');
print $password."is the encrypted version of hkrtrainings";
?>
Ans: Yes, PHP supports the use of variable length argument functions. You are able to pass any number of arguments to a function. The syntax includes using three dots before the argument name as shown in the below example:
function add(...$num) {
$sum = 0;
foreach ($num as $n) {
$sum += $n;
}
return $sum;
}
echo add(5, 6, 7, 8);
?>
Output: 26
Ans: There are three different types of runtime errors in PHP.
1. Notices: These errors are trivial and non-critical that PHP encounters while executing a script.
Example: Accessing a variable which is not yet defined.
By default, such errors are not displayed to the user at all, although you can change this default behaviour.
2. Warnings: These errors are more serious.
Example: Attempting to include() a file which does not exist.
By default, these errors are displayed to the user, but they do not result in script termination.
3. Fatal errors: These errors are very critical.
Example: Instantiating an object of a non-existent class, or calling a non-existent function.
These errors cause the immediate termination of the script, and PHP’s default behaviour is to display them to the user when they take place.
Ans: There are two ways of using the comments in PHP.
Example:
# This is a comment
echo "Single-line comment";
?>
2. Multi-line comments that can be denoted using ‘/* */’ in PHP.
Example:
/*
This is
a
Multi-line
Comment
In PHP;
*/
echo "Multi-line comment";
?>
Ans:
Indexed Arrays:
These arrays will have elements that contain a numerical index value.
Example: $color=array("red","green","blue");
Here, red is at index 0, green at index 1, and blue at index 2.
Associative Arrays:
These arrays hold the elements with string indices as shown below:
Example: $salary=array("Jacob"=>"20000","John"=>"44000","Josh"=>"60000");
Ans: It is very easy to get an IP address of a client who is connected by using the following syntax.
$_SERVER["REMOTE_ADDR"];
Ans: The default time allowed for a PHP script for execution is 30 seconds mentioned in the “php.ini” file. The function that will be used is
“set_time_limit(int sec)”.
If the value passed is ‘0’, then it takes unlimited time. Note that if the default timer is set to 30 seconds and 20 seconds is specified in “set_time_limit()”, then the script will run for 45 seconds.
The default limit is 30 seconds. The time limit can be set to zero to impose no time limit.
Ans: There are four steps in creating a new database using MySQL and PHP.
Ans:
Ans:
Ans:
Example:
function sendEmail (Email $email)
{
$email->send();
}
?>
The above example describes how to send the Email function argument “$email” Type hinted of an “Email” Class. It means to call this function you must have to pass an email object otherwise an error is generated.
Ans:
For instance:
Ans: The following are the ways of creating, setting and removing a session.
Ans: A session is a global variable stored on the server. a unique id is assigned for each session which is used to retrieve stored values. Sessions can store large data as compared to cookies which have high storage capabilities. The session values will be deleted automatically when the browser is closed.
Creating a cookie in PHP:
Example:
$cookie_value = "hkrtrainings";
setcookie("hkrtrainings",$cookie_value,time()+3600,"/your_usename/","hkrtrainings.com", 1, 1);
if (isset($_COOKIE['cookie']))
echo $_COOKIE["hkrtrainings"];
?>
Creating a session in PHP:
Example:
session_start();
if( isset( $_SESSION['counter'] ) )
{
$_SESSION['counter'] += 1;
}
else
{
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page". $_SESSION['counter'];
$msg .= "in this session.";
?>
Ans: There are many frameworks in PHP. The most popular frameworks are.
Ans:
Syntax:
foreach(array)
{
Code inside the loop;
}
Example:
$colors = array("red", "blue", "green");
foreach ($colors as $value) {
echo "$value";
}
?>
Ans:
require():
require_once():
Ans:
Syntax: resource fopen(string $filename,string $mode[,bool $use_include_path = false [, resource $context ]] )
Ans: The result set can be handled using mysql_fetch_array, mysql_fetch_assoc, mysql_fetch_object or mysql_fetch_row.
If you have any doubts on PHP, then get them clarified from PHP Industry experts on our PHP Community!
Ans : mysql_pconnect() ensure a persistent connection to the database, it means that the connection do not close when the the PHP script ends.
Ans: file_get_contents() lets reading a file and storing it in a string variable.
Explore PHP Sample Resumes Download & Edit, Get Noticed by Top Employers!
Ans: The most common and used way is to get data into a format supported by Excel. For example, it is possible to write a .csv file, to choose for example comma as separator between fields and then to open the file with Excel.
Ans: 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.
Ans: Require () and require once () perform the same task except that the second function checks if the PHP script is already included or not before executing it.
(same for include once() and include())
Ans: If the function require () cannot access to the file then it ends with a fatal error. However, the include () function gives a warning and the PHP script continues to execute.
Ans: PHP and JavaScript cannot directly interact since PHP is a server side language and JavaScript is a client side language. However we can exchange variables since PHP is able to generate JavaScript code to be executed by the browser and it is possible to pass specific variables back to PHP via the URL.
Batch starts on 7th Jun 2023, Weekday batch
Batch starts on 11th Jun 2023, Weekend batch
Batch starts on 15th Jun 2023, Weekday batch