PHP interview questions

Get Technical Answers for PHP Interview Questions by PHP Expert Developers, Advanced Technical Questions for Freshers and Experience Persons. Free Practical Tests

1. What is PHP?

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.

2. What are the different types of PHP variables?

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.

3. What are constructor and destructor in 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;

}

}

?>

4. What does PEAR stands for?

Ans: PEAR means “PHP Extension and Application Repository”. it extends PHP and provides a higher level of programming for web developers

5. What are the different types of Array in PHP?

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.

6. What is the difference between the single-quoted string and double-quoted string?

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

7. How to execute an SQL query? How to fetch its result?

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’];

8. What is the difference between “echo” and “print” in PHP?

Ans: 

Echo:

  • PHP echo displays one or more strings as output. 
  • PHP echo is not a function, it is a language construct. Hence use of parentheses is not required. But when there is a need to pass more than one parameter to echo, then the use of parentheses is required.
  • Echo is faster than print as it doesn’t return any value.

Print:

  • PHP print displays a string as output. 
  • PHP print is also a language construct but not a function. Here the use of parentheses is not required with the argument list. Unlike echo, it always returns 1.
  • The print is slow compared to the echo.

9. How can we display the output directly to the browser?

Ans: To be able to display the output directly to the browser, we have to use the special tags .

10. What is the main difference between PHP 4 and PHP 5?

Ans: PHP 5 presents many additional OOP (Object Oriented Programming) features.

11. Is multiple inheritances supported in PHP?

Ans: PHP includes only single inheritance, it means that a class can be extended from only one single class using the keyword ‘extended’.

12. What is the meaning of a final class and a final method?

Ans: ‘Final’ is introduced in PHP5. Final class means that this class cannot be extended and a final method cannot be override.

13. How comparison of objects is done in PHP5?

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 ‘===’.

14. How can PHP and HTML interact?

Ans: It is possible to generate HTML through PHP scripts, and it is possible to pass information’s from HTML to PHP.

15. What is the difference between $var and $$var?

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”.

PHP Training Certification

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

 

16. What is the use of callback in PHP?

Ans: 

  • PHP callback are the functions which are called dynamically by PHP. 
  • They are used by native functions such as array_map, usort, preg_replace_callback, etc. 
  • A callback function is a function that is created and is then passed to another function as an argument. Once it has access to the callback function, the receiving function can then call it whenever there is a need.

Example:



function thisFuncTakesACallback($callbackFunc)

{

echo "I'm going to call $callbackFunc!

";

$callbackFunc();

}

function thisFuncGetsCalled()

{

echo "I'm a callback function!

";

}

thisFuncTakesACallback( 'thisFuncGetsCalled' );

?>

17. How can we execute a PHP script using a command line?

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.

18. How to submit a form without a submit button?

Ans:

A form can be submitted without any button in the following ways.

  1. On the “OnClick” event of a label in the form, a JavaScript function can be called to submit the form.

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:

    • Submitting a form by clicking a link.
    • Submitting a form by selecting an option from the drop-down box with the invocation of an “onChange” event.
    • By using JavaScript: document.form.submit();

      4. By using the header(“location:page.php”);

19. What library is used for PDF in 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.

20. How can you encrypt a password using PHP?

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";

?>


Subscribe to our youtube channel to get new updates..!

 

21. Does PHP support variable-length argument functions?

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

22. What are the different types of errors in PHP?

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.

23. How are comments used in PHP?

Ans: There are two ways of using the comments in PHP. 

  1. Single line comments that can be used using the conventional ‘#’ sign.

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";

?>

24. Differentiate between an indexed array and an associative array.

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");

25. How can you get the IP address of a client in PHP?

Ans: It is very easy to get an IP address of a client who is connected by using the following syntax.

$_SERVER["REMOTE_ADDR"];

26. How can we increase the execution time of a PHP script?

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.

  • This time can be increased by altering “max_execution_time” in seconds. The time must be changed accordingly keeping the environment of the server. This is because altering the execution time will also affect all the sites hosted by the server.
  • The script execution time can be increased by:
    • Using the “sleep()” function in the PHP script.
    • Using the “set_time_limit()” function.

The default limit is 30 seconds. The time limit can be set to zero to impose no time limit.

27. What are the steps to create a new database using MySQL and PHP?

Ans: There are four steps in creating a new database using MySQL and PHP.

  1. A connection is established to the MySQL server using the PHP script.
  2. The connection is then validated. If the connection is successful, then you are allowed to write a sample query for verification.
  3. Queries that create the database are input and later stored into a string variable.
  4. Then, the created queries are executed one after the other.

28. What is the difference between “mysql_connect” and “mysql_pconnect”?

Ans:

  • The mysql_pconnect() method is used to make a persistent connection to the database which means a SQL link that doesn’t close the connection even after the execution of the script ends. 
  • The mysql_connect() method simply provides only the new database connection while using mysql_pconnect(), the method would first try to find a persistent link that’s already open with the same host, username and password. 
  • If one is found, an identifier for it will be returned instead of opening a new connection. The connection to the SQL server is not closed when the execution of the script ends rather the link will remain open for future use.

29. What is Zend Engine?

Ans: 

  • Zend Engine is internally used by PHP as a compiler and a runtime engine.
  • PHP Scripts are loaded into memory and are compiled into Zend OPCodes.
  • These OPCodes are executed and the generated HTML is sent to the client.
  • It provides memory and resource management services and other standard services for the PHP language. 
  • The performance, reliability, and extensibility of the Zend Engine have a significant role.

30. What is Type hinting in PHP?

Ans: 

  • Type hinting is used to specify the expected data type of an argument in a function declaration. 
  • When a function is called, PHP will then check whether or not the method arguments are of the specified type. If not, the run-time will raise an error and execution will be halted.

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.

31. What is htaccess? Why do we use it and where?

Ans: 

  • The “.htaccess” files are the configuration files of Apache Server that provide settings for configuration changes on a per-directory basis. 
  • A file which contains one or more configuration directives is placed into a particular document directory; the directives apply to that directory and all subdirectories thereof.
  • The “.htaccess” files are used in changing the functionality and features of the Apache web server.

For instance:

  • The “.htaccess” file is used for rewriting the URL.
  • It is used for making the site as password-protected.
  • It restricts few IP addresses such that those sites cannot be opened on these restricted IP addresses.

32. How to create a session? How to set a value in session? How to Remove data from a session?

Ans: The following are the ways of creating, setting and removing a session.

  1. Creating a session : session_start();
  2. Setting a value into session : $_SESSION[‘USER_ID’]=1;
  3. Remove the data from a session : unset($_SESSION[‘USER_ID’]);

33. What is the use of session and cookies in PHP?

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."; 

?>

34. What are some of the popular frameworks in PHP?

Ans: There are many frameworks in PHP. The most popular frameworks are.

  • CodeIgniter
  • CakePHP
  • Laravel
  • Zend
  • Phalcon
  • Yii 2

35. How does the ‘foreach’ loop work in PHP? Give an example.

Ans: 

  • The “foreach” is a looping construct statement which is used in PHP for iterating and looping through the array data type. 
  • The “foreach” statement works with every single pass of the value, elements get assigned a value and pointers are incremented. This process is repeated until the end of the array.

Syntax:

foreach(array)

{

Code inside the loop;

}

Example:



$colors = array("red", "blue", "green");

foreach ($colors as $value) {

echo "$value";

}

?>

36. What is the difference between require() and require_once() functions?

Ans: 

require():

  • This method includes a specific file and evaluates that file.
  • It is preferred for files with fewer functions.

require_once():

  • This method includes the files only if they are not included before.
  • It is preferred for files when there many functions.

37. How can you open a file in PHP?

Ans: 

  • PHP supports file operations by providing users with excessive file-related functions.
  • To open a file, the “fopen()” method is used. This function can open a file or a URL as per necessity. It takes two arguments: “$filename” and “$mode”.

Syntax:  resource fopen(string $filename,string $mode[,bool $use_include_path = false [, resource $context ]] )

38. How the result set of Mysql be handled in PHP?

Ans: The result set can be handled using mysql_fetch_array, mysql_fetch_assoc, mysql_fetch_object or mysql_fetch_row.

PHP Training Certification

Weekday / Weekend Batches

 

39. What is the function mysql_pconnect() usefull for?

Ans : mysql_pconnect() ensure a persistent connection to the database, it means that the connection do not close when the the PHP script ends.

40. What is the function file_get_contents() usefull for?

Ans: file_get_contents() lets reading a file and storing it in a string variable.

41. What should we do to be able to export data into an Excel file?

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.

42. How is it possible to set an infinite execution time for PHP script?

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.

43. What is the main difference between require () and require once()?

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())

44. How failures in execution are handled with include () and require () functions?

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.

45. How can PHP and JavaScript interact?

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.

Submit an interview question

Categories

Request for more information

John
John
Cloud Technologies & Cyber Security
John is a Post Graduate in Computer Science from Andhra University .She is currently working as an IT developer at hkr trainings.com. And he has great experience includes both IT development and operational roles. Connect with him on LinkedIn and Twitter. Thank you

WhatsApp
To Top