101  PHP Technical Interview questions and answers

Interview
Question & Answers
Tutorials

101 PHP Technical Interview questions and answers101  PHP Interview questions and answers  help job seekers and freshers to have basic and advance knowledge of PHP language. Experienced also can take the advantage of  PHP Interview questions and answers post.  I got the feedback from many PHP developers that they found PHP Interview questions and answers post very helpful for succeeding in freelancers.com and upwork.com exam PHP test. PHP Interview questions and answers have been designed to help you understand the basics and advance commands.

The initials php interview questions let you know basic concepts of php language which are helpful to get stronger in the php programming platform specially for beginners. The list of PHP questions answers are like a php tutorial which makes the reader strong technically in PHP language.

 

1.What is PHP?

PHP stands for Hypertext Preprocessor Preprocessor, is open supply server aspect scripting language usually used for net applications equipped with frameworks and CMS(Content Management System). PHP additionally supports OOPS ideas i.e you'll be able to produce category(classes) with functions like in C#, Java. PHP is enough pwerful to handle databases like MySQL, Oracle, Sybase, Solid, PostgreSQL, generic ODBC.

2. Define  "echo" and "Print".

  • Echo is capable of taking  more than one string for output and return 1.
  • print's capacity is to take only one argument as parameter. Echo is faster than print because it does not return any value.

3. Define  include, require and require_once.

  • include or require helps merging contents like text/code/markup from a another file referred to include or require.
  • e_compile_error is thrown if  require is not able to find refereed file causing termination of  scripts.
  • Displays a warning if include fails to find referred  file and execution of scripts continues.
  • require_once() includes the content of file just one occasion.

4. Define GET and POST methods.

    • GET method's bytes capacity is  only  1024.
    • POST method's bytes capacity is  more than 1024 bytes means can handle big volume of data.
    • POST is secure than GET method.
    • POST method is capable of handling ASCII and  binary data.
    • POST Method sends the information via HTTP headers in encoded(as configured) format.
    • GET method adds the information in URL as query string.
      More Details

5. Define in_array() function.

in_array  scans whole array to find a  particular/specific value.

6. Session and Cookies.

Session Cookies
The storage of sessions happens on the server. cookies are stored on the visitor's machine in the text file format.
Multiple variables can be stored in session Multiple variables are not allowed in cookies.
The life of session depends on activity of browser. once browser is closed session also expires. Expiry date and time can be set for cookies.
Session is used for login and logout purpose. cookies is used for user tracking.
Sessions are more secure than cookies as it is stored in serve Cookie can be turn off from browser.

7. Define explode() and implode function.

explode function  is capable of  converting a string into array with a delimiter.
implode is reverse of explode, it implodes an array to a string.

Syntax : array explode ( string $delimiter , string $string [, int $limit ] );

8. Define mysql_real_escape_string() function.

To use special characters like @, underscore(_), ampersand(&) etc as a literal  word in SQL statement mysql_real_escape_string is used.

9. Define trim() function.

The trim() function removes white spaces or other predefined characters from both sides of a string.

10.  How to redirect a page?

header("Location:HomePage.php");

11. Define variables scope in PHP.

  • Local: A variable declared within a function has a local scope  and can only be accessed within that function.
  • Global: A variable declared as global can be accessed in any part of program. To make the variable as global place the key word "global" before the variable name within a function. $GLOBALS keeps the all PHP global variables in an array form.
  • Static: Generally all variables are destroyed or deleted when then execution of function ends. So to maintain the value in some variables for further jobs declare it as static. static variables are not destroyed even after the function completes or finish its operation.   More Details

11. How to stop the execution of a php script ?

By Using exit(); function.

12. Define isset() function.

isset() function is used to check if a variable is set and is not NULL.

13. Define encryption techniques.

MD5 hash algorithm using the md5 function.

14. Define unlink and unset().

  • unset() function sets a variable to “undefined”
  • unlink() function deletes the given file from the file system.

15. Define mysql_fetch_array() and mysql_fetch_assoc().

  • mysql_fetch_assoc() function Fetch a result row as an associative array,
  • mysql_fetch_array() function fetches an associative array, a numeric array, or both.

16. How to get the IP address of the client?

$_SERVER["REMOTE_ADDR"];

17. Define  main error types.

  • E_Notices – Occurs during the script execution.
  • E_Warnings – Scripts continue the execution but shows warning.
  • Fatal – A fatal error that terminates script execution.

18. Placing the _ symbol before a function tells PHP to suppress any errors generated by that function.

  • #
  • $
  • !
  • @

19.  What is the difference between == and === operator ?

  • == equal operator's capacity is to evaluate  values of two operands for equality/unequality and return true or false.
  • === Identical operator does the same thing but also checks data type for comparison.

20. Giving the following array:

$array=array(0 => ‘blue’, 1 => ‘red’, 2 => ‘green’, 3 => ‘red’);

Which one of the following will print 2?

  • echo array_key_exists(2, $array);
  • echo array_search(‘red’, $array);
  • echo array_search(‘green’, $array);
  • echo in_array(‘green’, $array);

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

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

23.  How to Destroy variable or object?

By Using unset() function.

24. Which MIME type need to be used to send attachment in mail?

By Using  multipart/mixed

25. What is the use of the function 'imagetypes()'?

imagetypes() gives the image format and types supported by the current version of GD-PHP.

26. What is the function file_get_contents() useful for?

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

27. How to create a database with PHP in MySQL Server?

mysql_create_db(‘database’);

28. Which of the following is true about the singleton design pattern?

  • A singleton pattern means that a class will only have a single method.
  • A singleton pattern means that a class can have only one instance object.
  • A singleton pattern means that a class has only a single member variable.
  • Singletons cannot be implemented in PHP.

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

30. Which function gives us the number of affected entries by a query?

mysqli_affected_rows() return the number of entries affected by an SQL query.

31. What is mode to write into a file at the end of the existing content, and create the file if the file does not exist?

a  - Append Mode

32. Define 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.

33. Which is wrong with the following code?

<?php
curl_setopt($ch, CURLOPT_url, “http://www.example.com”);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exc($ch);
curl_close($ch);
?>

  • There is nothing wrong with the code
  • The CURL resources $ch has not been created using the curl_init() method.
  • The $ch variable needs to be initialized as $ch=null;
  • The code cause will cause a parse error

34. How to check the value of a given variable is a number?

is_numeric() to check whether it is a number or not.

35. What is the result of a fatal error PHP program?

The PHP program will stop executing at the point where the error occurred.

36. How to detect which request type was used (GET, POST, PUT OR DELETE)?

$method = $_SERVER[‘REQUEST_METHOD’];

37. Which statement is not correct?

$x = null;

  • empty($x) return TRUE
  • is_null($x) return FALSE
  • isset($x) return FALSE
  • None of the above

38.  How to remove escape characters from a string?

stripslashes function.

39. What is the method to send an SMTP (Simple Mail Transfer Protocol) email using PHP?

mail($EmailAddress, “Subject”, $MessageBody);.

40. Which of the following are valid MySQLi Configuration options? (Choose all that apply)

  • mysqli.allow_persistent
  • mysqli.rollback_on_cached_size
  • mysqli.default_port
  • mysqli.default_socket

41. How to automatically escape incoming data?

Enabling the magic quotes entry in the configuration file of PHP.

42. Where can protected property or method be accessed?

  • It can only be accessed within the class itself
  • It can be accessed outside of the class
  • It can only be accessed within the class itself or in descendant classes.
  • It can no be accessed anywhere

43. How to rename a file in PHP?

rename(oldname, newname)

44. Which method is used to tweak an Oject’s cloning behavior?

__clone()

45. You can extend the exception class, however you can not override any of the preceding ways they're declared as:

  • protected
  • final
  • static
  • private

46. The ___ statement takes all the text/code/markup/that exists in the specified file and copies it into the file that uses the statement.

  • require
  • include
  • get
  • add

47. Which in-built function will add a value to end of an array?

  • array_unshift()
  • into_array()
  • inend_array()
  • array_push()

48. What is the correct syntax of mail() function in PHP?

mail($to,$subject,$message,$headers)

49. The PDO_MYSQL Data Source Name(DSN) is composed of the following elements?

  • unix_socket
  • charset
  • user_pass
  • db_table
  • dbname

50. What will be the output of executing the following code?

class Person{
proctected $name;
public function __construct($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
}
$person = new Person(“Foo”);
echo $person -> getName();

  • Nothing will be printed on-screen
  • Foo
  • Syntax error on line $this->name=$name
  • Fatal error on line $this->name=$name

51. What is the most convenient hashing method to be used to hash passwords?

crypt() is advisable supporting several hashing algorithms or the function hash().

52. Which technology extension offer generation and verification of digital signatures?

The PHP-OpenSSL extension provides several cryptographic operations including generation and verification of digital signatures.

53. Define constant in PHP?

PHP Constant is like a variable once declared and assigned can not be changed or modified  throughout the whole program. Constant name must start with a letter or underscore unlike the variable $ sign is not required as prefix and by default all constants are global.  More Details

Using the define() function you can declare the PHP constant.

Syntax:  define(name, value)

<?php

define("MyCostantVariable", "Welcome to PHP Tutorial");
echo MyCostantVariable;

?>

54. Which function can be used to determine if a file exists?

  • is_readable()
  • file_exists()
  • feof()
  • is_file_exists()

55. Which of these is not a valid SimpleXML Parser method?

  • simplexml_import_dom()
  • simplexml_import_sax()
  • simplexml_load_file()
  • simplexml_load_string()

56. What's the difference between __sleep and __wakeup?

  • __sleep returns the array of all the variables that need to be saved.
  • __wakeup retrieves them.

57. Define  session_unregister() and session_unset()?

  • session_unregister() function unregister a global variable from the current session.
  • session_unset() function frees all session variables.

58. Define $GLOBALS variable.

$GLOBALS is associative array including references to all variables which are currently defined in the global scope of the script.

59. Defaine $_SERVER variable?

$_SERVER is an array including information created by the web server such as paths, headers, and script locations.

60. How to change the maximum size of the files to be uploaded?

By changing upload_max_filesize in php.ini.

61. What does $_ENV mean?

$_ENV is an associative array of variables sent to the current PHP script via the environment method.

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

63. Exception::getMessage and Exception:: getLine.

  • Exception::getMessage lets us getting the Exception message.
  • Exception::getLine lets us getting the line in which the exception occurred.

64. Define the functions strstr() and stristr().

  • The string function strstr(string allString, string lotus) returns part of allString from the first occurrence of lotus to the end of allString. This function is case-sensitive.
  • stristr() is identical to strstr() except that it is case insensitive.

65. What will be the output of above code?

<?php $arr = array(‘Hello’, ‘World!’, ‘Beautiful’, ‘Day!’) echo implode(” “, $arr); ?>

  • HelloWorld!BeautifulDay!
  • ‘Hello’, ‘World!’, ‘Beautiful’, ‘Day!’
  • Hello World! Beautiful Day!
  • No Output

66. Which of the following will produce a value of “83” as its output?

  • echo intval(“0123”, 8);
  • echo (int) 083
  • echo (int) 123
  • echo intval(“0123”);

67. How to remove white-space from the beginning and end of $string variable?

  • cut($string);
  • removeSpace($string);
  • shorten($string);
  • trim($string);

68. How to destroy a cookie?

By setting the cookie with a past expiration time.

69. What is the default session time in PHP?

Until the closing of the browser.

70. Which of the following is used to send mail in PHP?

  • send_mail(to, subject, headers, parameters);
  • mail(to, subject, headers, parameters);
  • mail::(to, subject, headers, parameters);
  • mail_to(to, subject, headers, parameters);

71. What is the best practice for running MySQL queries in PHP? Consider the risk of SQL injection.

  • Use mysql_query() and variables: for example: $input = $_POST[‘user_input’]; mysql_query(«INSERT INTO table (column) VALUES (‘» . $input . «‘)»);
  • Use PDO prepared statements and parameterized queries: for example: $input= $_POST[«user-input»] $stmt = $pdo->prepare(‘INSERT INTO table (column) VALUES («:input»); $stmt->execute(array(‘:input’ => $input));
  • Use mysql_query() and string escaped variables: for example: $input= $_POST[«user-input»] $input_safe = mysql_real_escape_string($input); mysql_query(«INSERT INTO table (column) VALUES (‘» . $input. «‘)»);
  • Use mysql_query() and variables with a blacklisting check: for example: $blacklist = array(«DROP»,»INSERT»,»DELETE»); $input= $_POST[«user-input»] if (!$array_search($blacklist))) mysql_query(«INSERT INTO table (column) VALUES (‘» . $input. «‘)»);

72. What are methods in PHP?

  • Individual action that an object will be to perform are defined within the class as methods?
  • An individual instance of the data structure defined by a class
  • These are the function defined inside a class and are used to access object data
  • There are the function in which the objects of the class are saved

73. PHP ___ are used to validate and sanitize external input?

  • Cookies
  • Filters
  • Exceptions
  • Files

74. Which of the following is not a valid cURL parameter in PHP?

  • CURLOPT_RETURNTRANSFER
  • CURLOPT_GET
  • CURLOPT_POST
  • CURLOPT_POSTFIELDS

75. List functions for searching strings using POSIX-style regular expression?

  • sql_regcase()
  • eragi_replace()
  • ereg_replace()
  • spliti()
  • erag()

77. What is the output of the following code?

<?php function abc(){
return_FUNCTION_;
}
function xyz() {
return abc();
}
echo xyz();
?>

  • abc
  • __FUNCTION__
  • xyz
  • <empty.output>

79.  What will be output of the following code?

<?php
$x = 1;
while ($x <=3)){
echo “$x, “;
$x++
}
?>

  • 1
  • 1, 2, 3,
  • 1, 2, 3
  • No Output

80. what is sql injection ?

SQL injection is a code injection technique, used to attack data-driven applications, in which nefarious SQL statements are inserted into an entry field for execution.

81. How can you connect with a MySQL Server in PHP?

  • database_connect(server, username, password)
  • mysql_connect(host, username, password)
  • mysql(server, username, password)
  • connect(server, username, password)

 82. What does PEAR stand for?

PEAR means "PHP Extension and Application Repository". The goal  PEAR is to provide: A structured library of open-source code for PHP users.

85. Which of these is not a valid PHP XML DOM method?

  • geElementByName()
  • removeChild()
  • geElementById()
  • appendChild()

87. Which function is used to read a file removing the HTML and PHP tags in it?

  • fgetss()
  • fgets()
  • fopen()
  • file_strip_tags()

88. How to enable error reporting in PHP?

Set  “display_errors” is equal “on” in the php.ini.
Declare “ini_set('display_errors', 1)” in your script.
Include “error_reporting(E_ALL)” in your code to display all types .

89. What is the meaning of the system message, Allowed memory size of bytes exhausted?

  • The avaliable RAM memory is exhausted
  • The avaliable disk memory is exhausted
  • The avaliable readomly memory is exhausted
  • The maximum memory allocated in php.ini is exhausted.

90. Define __construct() and __destruct() methods in a PHP class?

PHP have Constructor and Destructor methods built-in for all types of objects. Whenever a new instance of class  is created then constructor method is called immediately  and it’s used to initialize class properties. The destructor method takes no parameters.

91. Define scope levels in PHP?

Private – accessible only in its own class
Public – accessible to any other code accessing the class
Protected – accessible only to classes parent(s) and classes that extend the current class.

92. How to change default execution time of a PHP script?

Using set_time_limit(int seconds) . The default limit is 30 seconds.

93. How to pass the variable through the navigation between the pages?

Using sessions, cookies or hidden form fields.

94. How to find current session id?

session_id().

95. Define function htmlentities.

htmlentities is used to convert all applicable characters to HTML entities.

96. Define $var and $$var.

Both are variables. $$var uses the value of the variable whose name is the value of $var. It means $$var is known as reference variable where as $var is normal variable.

97. Defaine "action" attribute in a html form?

The action attribute determines where to send the form-data in the form submission.

98.  How to to protect special characters in a query string?

Use urlencode() function.

99. How to sort an array in reverse order?

Using "ksort".

100. Define associative array.

In associative arrays  string keys is called associative arrays.

101. With regards to the “static” keyword in PHP, which of the following statement is false?

  • The $this can be used inside any static method.
  • Static properties may only be intialized using literal or a constant
  • A property declared as static can not be accessed with an instantiated class object
  • A static variable or method can be accessed without requiring instantiation of class

Conclusion

In PHP Interview questions and answers I have tried to cover almost all topics of PHP language. However in interview question on PHP interview questions could be could be random but my experience says generally interviewer starts from basic questions and moves on advance questions. I hope this php questions answers have cleared all concepts of PHP. Your suggestion regarding php tutorials are welcome.

 

See Also: C# Interview Questions And Answers