PHP Interview Questions and Answers

Questions

112

Last updated

Mar 24, 2024

PHP earlier stood for Personal Home Pages, but now it stands for Hypertext Pre-processor. PHP is a server-side scripting language that is used for building web pages and applications. We have just added more questions in our question bank for PHP interview questions. This language includes many Frameworks and CMS for creating large websites. Even a non-technical person can create web pages or apps using PHP CMS or frameworks. PHP supports various frameworks and CMS that are used to develop applications.

Before getting confused with the plethora of PHP developer interview questions, you need to ensure the basics. This question will help you to understand the core basics of PHP and make you even more confident enough to jump onto the advanced questions.

Quick Facts About PHP
What is the latest version of PHP? 8.0.3, released on 4th March 2021
Who is the developer of PHP? Rasmus Lerdorf
What language does PHP use? C language
PHP License It is a BSD-style license which does not have the "copyleft" and restrictions associated with GPL.
Key points about PHP:
  • It runs on various platforms, including Windows, Mac OS X, Linux, Unix, etc.
  • It is compatible with almost all servers, including Apache and IIS.
  • It supports many databases like MySQL, MongoDB, etc
  • It is free, easy to learn and runs on the server-side.
  • PHP can operate various file operations on the server

Note: This is a list of the most frequently asked PHP interview questions. Please have a good read and if you want to download it, it is available in a PDF format so that you can brush up your theoretical skills on this subject.

Most Frequently Asked PHP Interview Questions

Here in this article, we will be listing frequently asked PHP Interview Questions and Answers with the belief that they will be helpful for you to gain higher marks. Also, to let you know that this article has been written under the guidance of industry professionals and covered all the current competencies.

Q1. What is PHP? Why it is used?
Answer

PHP earlier stood for Personal Home Pages, but now it stands for Hypertext Pre-processor. PHP is a server-side scripting language that is used for building web pages and applications. This language includes many Frameworks and CMS for creating large websites.

Even a non-technical person can create web pages or apps using PHP CMS. PHP Supports various CMS like WordPress, Joomla, Drupal and Frameworks like Laravel, CakePHP, Symfony, etc

Q2. What are the advantages of PHP?
Answer
  • Open source
  • Robust functions
  • Centralized built-in database
  • Extensive community support
Q3. Who developed PHP?
Answer

PHP was developed by Rasmus Lerdorf in 1994.

Q4. What is the latest version of PHP and Mysql?
Answer

PHP 7.4 is the latest version of PHP and 8.0 is the newest version of Mysql.

Q5. What is the difference between the functions unlink and unset?
Answer

unlink() : It is used to delete a file.

unset() : It is used to unset a file.

unlink('headbar.php');
unset($variable);

Q6. How many types of errors in PHP?
Answer

Primarily PHP supports four types of errors, listed below:-

  • Syntax Error
  • Fatal Error
  • Warning Error
  • Notice Error

1. Syntax Error: It will occur if there is a syntax mistake in the script

2. Fatal Error: It will happen if PHP does not understand what you have written. For example, you are calling a function, but that function does not exist. Fatal errors stop the execution of the script.

3. Warning Error: It will occur in following cases to include a missing file or using the incorrect number of parameters in a function.

4. Notice Error: It will happen when we try to access the undefined variable.

Note: The page you are accessing has some of the most basic and complex PHP Interview Questions and Answers. You can download it as a PDF to read it later offline.

Q7. What is the main difference between require() and include()?
Answer
require() include()
If a required file not found, it will through a fatal error & stops the code execution If an essential file not found, It will produce a warning and execute the remaining scripts.
Q8. How to get IP Address of clients machine?
Answer

If we used $_SERVER[‘REMOTE_ADDR’] to get an IP address, but sometimes it will not return the correct value. If the client is connected with the Internet through Proxy Server then $_SERVER[‘REMOTE_ADDR’] in PHP, it returns the IP address of the proxy server not of the user’s machine.

So here is a simple function in PHP to find the real IP address of the user’s machine.

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

Q9. What is the difference between require() and require_once()?
Answer

require() and require_once() both are used for include PHP files into another PHP files. But the difference is with the help of require() we can include the same file many times in a single page, but in case of require_once() we can call the same file many times, but PHP includes that file only single time.

Note: From the vast number of php basic interview questions, answering this will help you to align yourself as an expert in the subject. This is a very tricky question that often makes developers nervous.

Q10. What is the difference between GET & POST ?
Answer

These both methods are based on the HTTP method.

GET POST
The GET method transfers data in the form of QUERY_STRING. Using GET it provides a $_GET associative array to access data The post method transfer form data by HTTP Headers. This POST method does not have any restrictions on data size to be sent. With POST method data can travel within the form of ASCII as well as binary data. Using POST, it provides a $_POST associative array to access data.
Q11. How can we make a constant in PHP?
Answer

With the help of define(), we can make constants in PHP.

define('DB_NAME', 'bestInterviewQ')

Q12. List some array functions in PHP?
Answer

In PHP array() are the beneficial and essential thing. It allows to access and manipulate with array elements.

List of array() functions in PHP

  • array()
  • count()
  • array_flip()
  • array_key_exists()
  • array_merge()
  • array_pop()
  • array_push()
  • array_unique()
  • implode()
  • explode()
  • in_array()
Q13. List some string function name in PHP?
Answer

PHP has lots of string function that helps in development. Here are some PHP string functions.

  • nl2br()
  • trim()
  • str_replace()
  • str_word_count()
  • strlen()
  • strpos()
  • strstr()
  • strtolower()
  • strtoupper()
Q14. How can we upload a file in PHP?
Answer

For file upload in PHP make sure that the form uses method="post" and attribute: enctype="multipart/form-data". It specifies that which content-type to use when submitting the form.

$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

Q15. What are the difference between session and cookies in PHP?
Answer

Session and Cookies both functions are used to store information. But the main difference between a session and a cookie is that in case of session data is stored on the server but cookies stored data on the browsers.

Sessions are more secure than cookies because session stored information on servers. We can also turn off Cookies from the browser.

session_start();
//session variable
$_SESSION['user'] = 'BestInterviewQuestion.com';
//destroyed the entire sessions
session_destroy();
//Destroyed the session variable "user".
unset($_SESSION['user']);

Example of Cookies

setcookie(name, value, expire, path,domain, secure, httponly);
$cookie_uame = "user";
$cookie_uvalue= "Umesh Singh";
//set cookies for 1 hour time
setcookie($cookie_uname, $cookie_uvalue, 3600, "/");
//expire cookies
setcookie($cookie_uname,"",-3600);

Q16. What are headers() in PHP?
Answer

In PHP header() is used to send a raw HTTP header. It must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP

Example :

header(string,replace,http_response_code);

1. string: It is the required parameters. It specifies the header string to send.

2. replace: It is optional. It indicates whether the header should replace previous or add a second header.

3. http_response_code : It is optional. It forces the HTTP response code to the specified value

Q17. What is the difference between file_get_contents() and file_put_contents() in PHP?
Answer

PHP has multiple functions to handle files operations like read, write, create or delete a file or file contents.

1. file_put_contents():It is used to create a new file.

Syntax :

file_put_contents(file_name, contentstring, flag)

If file_name doesn't exist, the file is created with the contentstring content. Else, the existing file is override, unless the FILE_APPEND flag is set.

2. file_get_contents(): It is used to read the contents of a text file.

file_get_contents($filename);

Q18. In PHP, how to redirect from one page to another page?
Answer

With the heal of the header(), we can redirect from one page to another in PHP.

Syntax :

header('location:index.php');
Q19. What is the meaning of "enctype= multipart/form-data" ?
Answer

HTML forms provide three methods of encoding.

  • application/x-www-form-urlencoded (the default)
  • multipart/form-data
  • text/plain

multipart/form-data

This is used to upload files to the server. It means no characters will be encoded. So It is used when a form requires binary data, like the contents of a file, to be uploaded.

Q20. What is the use of the .htaccess file in php?
Answer

The .htaccess file is a type of configuration file for use on web servers running the Apache Web Server software. It is used to alter the configuration of our Apache Server software to enable or disable additional functionality that the Apache Web Server software has to offer.

Q21. How to add comments in PHP?
Answer

In PHP comments are two types.

  1. Single line comments
  2. Multi line comments

1. Single line comments: It is used comments a single line of code. It disables a line of PHP code. You have to add // or # before the system.

2. Multi line comments: It is used to comment large blocks of code or writing multiple line comments. You have to add /* before and */ after the system.

Q22. What are the difference between array_merge() and array_combine()?
Answer

1. array_combine(): It is used to creates a new array by using the key of one array as keys and using the value of another array as values.

Example :

$array1 = array('key1', 'key2', 'key3'); $array2 = array(('umesh', 'sonu', 'deepak'); $new_array = array_combine($array1, $array2); print_r($new_array);

OUTPUT : Array([key1]  => umesh[key2]    => sonu[key2]    =>deepak)

2. array_merge(): It merges one or more than one array such that the value of one array appended at the end of the first array. If the arrays have the same strings key, then the next value overrides the previous value for that key.

Example :

$array1 = array("one" => "java","two" => "sql"); $array2 = array("one" => "php","three" => "html","four"=>"Me"); $result = array_merge($array1, $array2); print_r($result); Array ( [one] => php [two] => sql [three] => html [four] => Me )

Q23. How to get a total number of elements used in the array?
Answer

We can use the count() or size() function to get the number of elements or values in an array in PHP.

$element = array("sunday","monday","tuesday");
echo count($element );

echo sizeof($element );

Q24. What is the difference between public, protected and private?
Answer

PHP has three access modifiers such as public, private, and protected.

  • public scope of this variable or function is available from anywhere, other classes, and instances of the object.
  • private scope of this variable or function is available in its class only.
  • protected scope of this variable or function is available in all classes that extend the current class including the parent class.

Note: One of the most tricky oops interview questions in php, you need to answer this question with utmost clarity. Maybe explaining it with a short example or even a dry run would help you get that dream job.

Q25. How to use implode() and explode() in PHP?
Answer

explode() function breaks a string into an array, but the implode() function returns a series from the elements of an array.

Example :
$arr = array("1","2","3","4","5");

$str = implode("-",$arr);

OUTPUT

1-2-3-4-5

 

$array2 = "My name is umesh";

$a = explode(" ",$array2 );

print_r ($a);

OUTPUT

$a = Array ("My", "name", "is", "umesh");

 

Q26. What is the difference server side and browser side validation?
Answer

We need to add validation rules while making web forms. It is used because we need to take inputs from the user in the right way like we need the right email address in the email input field. Some time user did not enter the correct address as we aspect. That's why we need validation.

Validations can be applied on the server side or the client side.

Server Side Validation

In the Server Side Validation, the input submitted by the user is being sent to the server and validated using one of the server-side scripting languages like ASP.Net, PHP, etc.

Client Side Validation

In the Client Side Validation, we can provide a better user experience by responding quickly at the browser level.

Q27. How to create and destroy cookies in PHP?
Answer

A cookie is a small file that stores on user's browsers. It is used to store users information. We can create and retrieve cookie values in PHP.

A cookie can be created with the setcookie() function in PHP.

Create Cookie

$cookie_name = "username";

$cookie_value = "Umesh Singh";

setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

Update Cookie

$cookie_name = "username";

$cookie_value = "Alex Porter";

setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");

Delete Cookie

setcookie("username", "", time() - 3600);

Q28. What is the difference between fopen() and fclose()?
Answer

 

These both are PHP inbuilt function which is used to open & close a file which is pointed file pointer.

S.no fopen() fclose()
1. This method is used to open a file in PHP. This method is used to close a file in PHP. It returns true or false on success or failure.
2. $myfile = fopen("index.php", "r") or die("Unable to open file!"); $myfile = fopen("index.php", "r");
Q29. What is the difference between php 5 and php 7?
Answer

There are differences between php5 and php7.

  • PHP 5 is released 28 August 2014 but PHP 7 released on 3 December 2015
  • It is one of the advantages of the new PHP 7 is the compelling improvement of performance.
  • Improved Error Handling
  • Supports 64-bit windows systems
  • Anonymous Class
  • New Operators

On our website you will find industry's best PHP interview questions for freshers.

Q30. How to get last inserted id after insert data from a table in mysql?
Answer

mysql_insert_id() is used to get last insert id. It is used after insert data query. It will work when id is enabled as AUTO INCREMENT

Q31. How to remove HTML tags from data in PHP?
Answer

With the help of strip_tags(), we can remove HTML tags from data in PHP.

The strip_tags() function strips a string from HTML, XML, and PHP tags.

strip_tags(string,allow)

The first parameter is required. It specifies the string to check.

The second parameter is optional. It specifies allowable tags. Mention tags will not be removed

Q32. What is str_replace()?
Answer

It is used to replaces some characters with some other characters in a string.

Suppose, we want to Replace the characters "Umesh" in the string "Umesh Singh" with "Sonu"

echo str_replace("Umesh","Sonu","Umesh Singh");

Q33. What is substr() in PHP? and how it is used?
Answer

It is used to extract a part of the string. It allows three parameters or arguments out of which two are mandatory, and one is optional

echo substr("Hello world",6);

It will return first six characters from a given string.

Q34. What the use of var_dump()?
Answer

It is used to dump information about one or more variables. It displays structured data such as the type and value of the given variable.

Example:

$var_name1=12; int(12);

Q35. What is the use of nl2br() in PHP?
Answer

It is used to inserts HTML line breaks ( <br /> or <br /> ) in front of each newline (\n) in a string.

Q36. Please explain the difference between $var and $$var?
Answer

$$var is known as reference variable where $var is a normal variable.

Q37. Please explain the difference between isset() and empty()?
Answer

1. isset(): It returns TRUE if the variable exists and has a value other than NULL. It means variables assigned a "", 0, "0", or FALSE are set.

2. empty(): It checks to see if a variable is empty. It interpreted as: "" (an empty string).

isset($var) && !empty($var)

will be equals to !empty($var)

Q38. Explain the difference between mysql_fetch_array(), mysql_fetch_object()?
Answer

1. mysql_fetch_object: It returns the result from the database as objects. In this field can be accessed as $result->name

2. mysql_fetch_array: It returns result as an array. In this field can be accessed as $result->[name]

Q39. What are the __construct() and __destruct() methods in a PHP class?
Answer

Constructor and a Destructor both are special functions which are automatically called when an object is created and destroyed.

class Animal
{
    public $name = "Hello";    
    public function __construct($name)
    {
        echo "Live HERE";
        $this->name = $name;
    }    
    public function __destruct()
    {
        echo "Destroy here";
    }
}
$animal = new Animal("Bob");
echo "My Name is : " . $animal->name;

Q40. How to get complete current page URL in PHP?
Answer

$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Q41. How to include a file code in different files in PHP?
Answer

For including a file into another PHP file we can use various function like include(), include_once(), require(), require_once().

<?php require('footer.php') ?>

Q42. What are the different functions in sorting an array?
Answer

 

The items of an array can be sorted by various methods.

  • sort() - it sort arrays in ascending order
  • rsort() - it sort arrays in descending order
  • asort() - it sorts associative arrays in ascending order, according to the value
  • ksort() - it sort associative arrays in ascending order, according to the key
  • arsort() - it sorts associative arrays in descending order, according to the value
  • krsort() - it sorts associative arrays in descending order, according to the key
Q43. How can we enable error reporting in PHP?
Answer

The error_reporting() function defines which errors are reported.We can modify these errors in php.ini. You can use these given function directly in php file.

error_reporting(E_ALL);
ini_set('display_errors', '1');

Q44. What are magic methods?
Answer

Magic methods are unique names, starts with two underscores, which denote means which will be triggered in response to particular PHP events.

The magic methods available in PHP are given below:-
  • __construct()
  • __destruct()
  • __call()
  • __get()
  • __unset()
  • __autoload()
  • __set()
  • __isset()

Note: One of the most tricky oops interview questions in php, you need to answer this question with utmost clarity. Maybe explaining it with a short example or even a dry run would help you get that dream job.

Q45. What are traits? How is it used in PHP?
Answer

A trait is a group of various methods that reuse in single inheritance. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of processes. We can combine traits and classes to reduce complexity, avoid problems typically associated with Mixins and multiple inheritances.

Related Article: How to Use Traits in PHP

trait HelloWorld
{
     use Hello, World;
}
class MyWorld
{
     use HelloWorld;
}
$world = new MyWorld();
echo $world->sayHello() . " " . $world->sayWorld(); //Hello World

Q46. What is inheritance in PHP? How many types of inheritance supports PHP?
Answer

Inheritance has three types, are given below.

  • Single inheritance
  • Multiple inheritance
  • Multilevel inheritance

But PHP supports only single inheritance, where only one class can be derived from a single parent class. We can do the same thing as multiple inheritances by using interfaces.

Note: Before getting confused with the plethora of PHP interview questions for experienced, you need to ensure the basics. This question will help you to understand the core basics of php and make you even more confident enough to jump onto the advanced questions.

Q47. How to download files from an external server with code in PHP?
Answer

We can do it by various methods, If you have allow_url_fopen set to true:

  • We can download images or files from an external server  with cURL() But in this case, curl has been enabled on both servers
  • We can also do it by file_put_contents()

$ch = curl_init();
$source = "http://abc.com/logo.jpg";
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$destination = "/images/newlogo.jpg";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);

/*-------This is another way to do it-------*/

$url = 'http://abc.com/logo.jpg';
$img = '/images/flower.jpg';
file_put_contents($img, file_get_contents($url));

Q48. What are the different MySQL database engines?
Answer
  • InnoDB
  • CSV
  • MEMORY
  • ARCHIVE
  • MyISAM

With PHP 5.6+ "InnoDB" is treated by default database storage engine. Before that MyISAM defaulted storage engine.

Q49. What is the difference between = , == and ===?
Answer

These all are PHP Operators.

  • = is used to assign value in variables. It is also called assignments operators.
  • == is used to check if the benefits of the two operands are equal or not.
  • === is used checks the values as well as its data type.
Q50. How to make a class in PHP?
Answer

We can define a class with keyword "class" followed by the name of the class.

 

Example :

class phpClass {
    public function test() {
       echo 'Test';
    }
}

Q51. What are the final class and final method?
Answer

Its properties cannot be declared final, only classes and methods may be declared as final. If the class or method defined as final, then it cannot be extended.

class childClassname extends parentClassname {
    protected $numPages;

    public function __construct($author, $pages) {
       $this->_author = $author;
       $this->numPages = $pages;
    }

    final public function PageCount() {
       return $this->numPages;
    }
}

Q52. Write a query to find the 2nd highest salary of an employee from the employee table?
Answer

You can use this SELECT MAX(salary) FROM employee WHERE Salary NOT IN ( SELECT Max(Salary) FROM employee); Query to find the 2nd highest salary of the employee.

Q53. What is the role of a limit in a MySQL query?
Answer

It is used with the SELECT statement to restrict the number of rows in the result set. Limit accepts one or two arguments which are offset and count.

The syntax of limit is a

SELECT name, salary FROM employee LIMIT 1, 2

Q54. How to get a total number of rows available in the table?
Answer

COUNT(*) is used to count the number of rows in the table.

SELECT COUNT(*) FROM BestPageTable;

Q55. What is MVC?
Answer

MVC is an application in PHP which separates the application data and model from the view.

The full form of MVC is Model, View & Controller. The controller is used to interacting between the models and views.

Example: Laravel, YII, etc

Q56. What is a composer?
Answer

It is an application package manager for the PHP programming language that provides a standard format for managing dependencies of PHP software. The composer is developed by Nils Adermann and Jordi Boggiano, who continue to lead the project. The composer is easy to use, and installation can be done through the command line.

It can be directly downloaded from https://getcomposer.org/download

Using the composer can solve the following problems:
  • Resolution of dependency for PHP packages
  • To keep all packages updated
  • The solution is autoloading for PHP packages.
Q57. What is the use of $_SERVER["PHP_SELF"] variable?
Answer

It is used to get the name and path of current page/file.

Q58. What is the use of @ in Php?
Answer

It suppresses error messages. It’s not a good habit to use @ because it can cause massive debugging headaches because it will even contain critical errors

Q59. What is namespace in PHP?
Answer

Namespace allows us to use the same function or class name in different parts of the same program without causing a name collision.

Namespace MyAPP;
   function output() {
   echo 'IOS!';
}

namespace MyNeWAPP;
   function output(){
   echo 'RSS!';
}

Q60. How can we get the browser properties using PHP?
Answer

With the help of $_SERVER['HTTP_USER_AGENT']

Q61. What is the use of cURL()?
Answer

It is a PHP library and a command line tool that helps us to send files and also download data over HTTP and FTP. It also supports proxies, and you can transfer data over SSL connections.

Using cURL function module to fetch the abc.in homepage

$ch = curl_init("https://www.bestinterviewquestion.com/");
$fp = fopen("index.php", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

Q62. Write a program to display Reverse of any number?
Answer

$num = 12345;
$revnum = 0;
while ($num > 1)
{
$rem = $num % 10;
$revnum = ($revnum * 10) + $rem;
$num = ($num / 10);
}

echo "Reverse number of 12345 is: $revnum";

Q63. How to check whether a number is Prime or not?
Answer

function IsPrime($n) {

for($x=2; $x<$n; $x++)

{

if($n %$x ==0) {

return 0;

}

}

return 1;

}

$a = IsPrime(3);

if ($a==0)

    echo 'Its not Prime Number.....'."\n";

else

    echo 'It is Prime Number..'."\n";

Q64. Write a program to display a table of any given number?
Answer

function getTableOfGivenNumber($number) {

   for($i=1 ; $i<=10 ; $i++) {

       echo $i*$number;

   }

}

getTableOfGivenNumber(5);

Q65. How to write a program to make chess?
Answer

<table width="100%" cellspacing="0px" cellpadding="0px" border="XXX2px">
<?php  
for($row=1;$row<=8;$row++)  
{  
    echo "<tr>";  
    for($column=1;$column<=8;$column++)  
    {
        $total=$row+$column;
        if($total%2==0)
        {  
            echo "<td height='72px' width='72px' bgcolor=#FFFFFF></td>";  
        }  
        else  
        {  
            echo "<td height='72px' width='72px' bgcolor=#000000></td>";  
        }  
    }  
    echo "</tr>";  
}  
?>  
</table>

Q66. What is the difference between abstract class and interface in php?
Answer

Many differences occur between the interface and abstract class in php.

  • Abstract methods can declare with protected, public, private. But in case of Interface methods stated with the public.
  • Abstract classes can have method stubs, constants, members, and defined processes, but interfaces can only have constants and methods stubs.
  • Abstract classes do not support multiple inheritance but interface support this.
  • Abstract classes can contain constructors, but the interface does not support constructors.

Note: Our PHP logical questions has been created by seasoned PHP experts. It shall help you to answer some of the most frequently asked questions during a job interview.

Q67. What are aggregate functions in MySQL?
Answer

The aggregate function performs a calculation on a set of values and returns a single value. It ignores NULL values when it performs calculation except for the COUNT function.

MySQL provides various aggregate functions that include AVG(), COUNT(), SUM(), MIN(), MAX().

Q68. What is the difference between MyISAM and InnoDB?
Answer

There are lots of differences between storage engines. Some are given below:-

  • MyISAM supports Table-level Locking, but InnoDB supports Row-level Locking
  • MyISAM designed for the need of speed but InnoDB designed for maximum performance when processing a high volume of data
  • MyISAM does not support foreign keys, but InnoDB supports foreign keys
  • MyISAM supports full-text search, but InnoDB does not support this
  • MyISAM does not support the transaction, but InnoDB supports transaction
  • You cannot commit and rollback with MyISAM, but You can determine and rollback with InnoDB
  • MyISAM stores its data, tables, and indexes in disk space using separate three different files, but InnoDB stores its indexes and tables in a tablespace

Note This is a good question concerning PHP interview questions for experienced.

Q69. What is SQL injection?
Answer

An SQL injection is a code injection malpractice or technique used to inject and execute malicious SQL statements to attack data-driven applications. It exploits the security vulnerability present in an application's software.

SELECT * FROM Users WHERE id = 10 OR 1=1;

Q70. How to redirect https to HTTP URL through .htaccess?
Answer

Place this code in your htaccess file.

RewriteEngine On

RewriteCond %{HTTPS} on

RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Q71. What is the Apache?
Answer

Apache HTTP server is the most popular open source web server. Apache has been in use since the year 1995. It powers more websites than any other product.

Q72. What is the difference between Apache and Tomcat?
Answer

Both used to deploy your Java Servlets and JSPs. Apache is an HTTP Server, serving HTTP. Tomcat is a Servlet and JSP Server serving Java technologies.

Q73. What is the best way to avoid email sent through PHP getting into the spam folder?
Answer
  • Sending mail using the PHP mail function with minimum parameters we tend to should use headers like MIME-version, Content-type, reply address, from address, etc. to avoid this case
  • Did not use correct SMTP mail script like PHPmailer.
  • Should not use website link in mail content.
Q74. What is PEAR in PHP?
Answer

It stands for PHP Extension and Application Repository. It is that the next revolution in PHP. It is used to install packages automatically.

Q75. What is the difference between REST and Soap?
Answer
  • SOAP represent for Simple Object Access Protocol, and REST stands for Representation State Transfer.
  • SOAP is a protocol and Rest is an architectural style.
  • SOAP permits XML data format only but REST permits different data format such as Plain text, HTML, XML, JSON, etc
  • SOAP requires more bandwidth and resource than REST so avoid to use SOAP where bandwidth is minimal.
Q76. How to make database connection in PHP?
Answer

$servername = "your hostname";
$username = "your database username";
$password = "your database password";

// Create connection

$conn = new mysqli($servername, $username, $password);

// Check connection

if ($conn->connect_error) {
die("Not Connected: " . $conn->connect_error);
}
echo "Connected";

Q77. How to remove blank spaces from the string?
Answer

preg_replace('/\s/', '', 'Best Interview Question');

Q78. What is the difference between mysql and mysqli?
Answer
MySQL MySQLi
This extension was added in version 2.0 of PHP and deprecated with PHP 5.5.0. Added in PHP 5.5 and is capable to work on MYSQL 4.1.3 or above.
No support for prepared statements. Supports prepared statements.
Offers procedural interface. Offers procedural interface as well as object-oriented interface.
No support for the stored procedure. Supports store procedure.
Lags with security and other special features. Users will receive here better security and advanced debugging.
Only SQL queries handled transactions. It supports API transaction.

Note: PHP’s easy to learn algorithm combined with its data semantics makes it a very high-functioning language. Our list of PHP interview questions will help you in understanding the core elements of PHP while giving you clarity on the subject.

Q79. How to find the index of an element in an array PHP?
Answer
Q80. How to check a variable is an array or not in PHP?
Answer

PHP developers use the is_array() function to determine whether a variable is an array or not. It is available for only PHP 4 and above versions.

is_array (var_name)
$var = ['Best', 'Interview', 'Questions'];
if(is_array ($var)) {
     // True
}

Q81. How to check an element is exists in array or not in PHP?
Answer

With the help of in_array() function we can check any element is exists in array or not. It's return type is true when element is exists and false when an element is not exists in array.

Syntax

in_array(search,array,type)

$array = array("Best", "Interview", "Questions");
if (in_array("Interview", $array))
{
echo "Element exists in array";
}
else
{
echo "Element not exists in array";
}

Q82. What is the IonCube PHP loader?
Answer

The ionCube Loader is an advanced component used by developers on the server to run encoded files. It protects the source code. When our PHP code gets pre-compiled and encrypted and requires a separate PHP module to load it, ionCube PHP loader will be required at that scenario.

Q83. What are getters and setters and why are they important?
Answer

In PHP, both setters and getters are methods used by developers to obtain or declare variables, especially the private ones.

Why are they important?

They are crucial because these methods allow for a certain location which will be able to handle before declaring it or while reverting it back to the developers.

Q84. How to increase the maximum execution time of a script in PHP?
Answer

There are two ways to increase the maximum execution time of a script in PHP available as following.

Method 1: Update php.ini file

To complete this process, we have to open the php.ini file and rearrange the max_execution_time (in seconds) as per our desired time.

Syntax

max_execution_time = 180 //180 seconds = 3 minutes

Method 2: Update .htaccess file

php_value max_execution_time 300

Method 3: Update your .php file

Here, we have to place the below-mentioned syntax on top of the PHP script.

ini_set('max_execution_time', 300);
ini_set('max_execution_time', 0);

Q85. What are the differences between PHP constants and variables?
Answer
Constant Variables
In PHP, the constant is an identifier or a name for a simple value. The constant value can't be changed during script execution. In PHP, the variable is a name or symbol which stands for value and used to store values such as characters, numeric, character string and memory addresses.
No dollar sign ($) is required before using a constant. Variables require a dollar sign ($) to be executed.
It can't be defined by simple assignment. Only define() function can define it. It is possible to define a variable by simple assignment.
It can be redefined or undefined after it gets set. We can redefine or undefine after it gets set.
define('TITLE', 'Best Interview Question') $title = 'Best Interview Question'
Q86. What is the purpose of break and continue statement?
Answer

In PHP, developers use the break statement to terminate a block and gain control out of the loop or switch, whereas the continue statement will not terminate the loop but promotes the loop to go to the next iteration. The break statement can be implemented in both loop (for, while do) and switch statement, but the continue statement can be only implemented in the loop (for, while do) statements.

Q87. What is the difference between overloading and overriding in PHP?
Answer
function overloading function overriding
The OOPs feature function overloading consists same function name and the function performs various tasks according to the number of arguments. In OOPs feature function overriding, both child and parent classes will have the same function name and a different number of arguments.
Q88. How to remove duplicate values from array using PHP?
Answer
To remove duplicate values from an array using PHP, we have to use the PHP array_unique() function. It removes duplicate values or elements from the array. If our array contains string keys, then this function will keep the first encountered key for every value and will ignore all other subsequent keys.

$var = array("a"=>"best","b"=>"interview","c"=>"question","d"=>"interview");

print_r(array_unique($var));

OUTPUT

Array ( [a] => best [b] => interview [c] => question)

Q89. What is the role of php.ini file?
Answer

The php.ini file is a default configuration file present in applications that require PHP. Developers use it to control different variables such as file timeouts, resource limits and upload sizes.

Q90. List the different types of Print functions available in PHP?
Answer

Here are the different types of print functions available in PHP for developers use:

  • Print() Function
  • Printf() Function
  • Echo() Function
  • Sprintf() Function
  • Print_r() Function
  • Var_dump() Function
Q91. How to send email using php script?
Answer

First, create a sendEmail.php file in web document root and we have to use the below-mentioned script in it to send email using a PHP script. Change the $to_email with a recipient email address, $body and $subject as you require, and $from_email with a sender email address here.

$to_email = "[email protected]";
$subject = "Simple Email Test via PHP";
$body = "Hi,nn This is test email send by PHP Script";
$headers = "From: [email protected]";
if ( mail($to_email, $subject, $body, $headers)) {
     echo("Email successfully sent to $to_email...");
} else {
     echo("Email sending failed...");
}

Q92. Write a program to swap two numbers using PHP.
Answer

We have to use the bellow mentioned syntax to swap two number using PHP, with or without using the third variable.

Without using third variable

<?php echo "Before Swapping:";
$a = 1;
$b = 2;
echo "a = $a<br>";
echo "b = $b<br>";

echo "After swapping:<br>";

$a = $a + $b;
$b = $a - $b;
$a = $a - $b;
echo "a = $a<br>";
echo "b = $b";
?>

With using third variable

<?php echo "Before Swapping:<br>";
$a = 1;
$b = 2;
echo "a = $a<br>";
echo "b = $b<br>";

echo "After swapping:<br>";
$temp = $a;
$a = $b;
$b = $temp;

echo "a = $a<br>";
echo "b = $b<br>";
?>

Q93. Write a program to display table of a number using PHP?
Answer
Q94. Write a program to get LCM of two numbers using PHP?
Answer

Here is the program we can use to get LCM of two number using PHP.

// PHP program to find LCM of two numbers

// Recursive function to
// return gcd of a and b
function gcd( $a, $b)
{
      if ($a == 0)
      return $b;
      return gcd($b % $a, $a);
}

// Function to return LCM
// of two numbers
function lcm( $a, $b)
{
      return ($a * $b) / gcd($a, $b);
}

// Driver Code
$a = 15;
$b = 20;
echo "LCM of ",$a, " and " ,$b, " is ", lcm($a, $b);

Q95. Write a program to get second highest number in an array using PHP?
Answer

function displaySecondHighest($arr, $arr_size)
{      
    if ($arr_size < 2)
    {
        echo(" Invalid Input ");
        return;
    }  
    $first = $second = PHP_INT_MIN;
    for ($i = 0; $i < $arr_size ; $i++)
    {
        if ($arr[$i] > $first)
        {
            $second = $first;
            $first = $arr[$i];
        } else if ($arr[$i] > $second &&
            $arr[$i] != $first)
            $second = $arr[$i];
        }
    if ($second == PHP_INT_MIN)
        echo("There is no second largest element\n");
    else
        echo("The second largest element is " . $second . "\n");
}
 
// Here is your Array
$arr = array(12, 35, 1, 10, 34, 1);
$n = sizeof($arr);
displaySecondHighest($arr, $n);
 
Output:

34

Q96. What is Web Workers in HTML5?
Answer
Q97. What is the use of ctype_upper() in PHP?
Answer
The ctype_upper() function in PHP used to check every and each and every personality of a given string is in uppercase or not. If the string in the top case then it returns TRUE otherwise returns False.
Q98. What are the difference between self and $this in PHP?
Answer
self $this
The “self” command can be used as a static function. The $this command cannot be used as a static function.
Self:: is used to access class variables and other methods The $this-> is used to access class variables and methods within.
It does not need an instantiated object. It does need an instantiated object.
Q99. How can we submit a form without a submit button?
Answer

We can use document.formname.submit()

Q100. What is the use of friend function?
Answer

In PHP, a friend function is one non-member function having access to private and protected members within a class. A friend function has the best use case when being shared among multiple classes, which can be declared either as member functions within a class or even a global function.

Q101. What is meant by urlencode and urldocode?
Answer

In PHP, the urlencode() function is one that can be conveniently used to encode any string before actually using it as part of the URL in a query. This function is a very efficient way to pass variables onto the next page. Whereas, the urldecode() function is used to decode the above-encoded string into a readable format.

Q102. What is the difference between Primary Key and Unique key?
Answer
Primary Key Unique Key
It is used to serve as a unique identifier for each row within a table. Used to determine rows that are unique and not a primary key in a table.
It cannot accept NULL values. Unique Key can accept NULL values.
There is the only scope for one primary key in any table. Multiple Unique Keys can be defined within a table.
The primary key creates a clustered index. Unique Key creates a non-clustered index.

Note: Our PHP interview questions for freshers have been selected from a plethora of queries to help you gain valuable insights and boost your career as a PHP Developer.

Q103. What is garbage collection in PHP?
Answer
Garbage collection in PHP refers to allocating and deallocating of space due to repeated use of a program. Many times, unnecessary space is consumed when a resource is orphaned after being used. The garbage collector in PHP ensures that these kinds of unwanted space consumption are minimized.
Q104. What is the difference between GROUP BY and ORDER BY?
Answer
GROUP BY ORDER BY
Used for aggregating data in a database. Used for sorting data in a database.
Used to change the form and composition of Data Used to change the display mode of data.
Attributes within GROUP BY are similar Attributes within ORDER BY are not similar.
Its function is to calculate aggregates. Its function is to sort and arrange in columns.
Q105. What are default session time and path?
Answer

The default session time in PHP is 1440 seconds or 24 minutes. The default session path is a temporary folder/tmp.

Q106. What is design pattern?
Answer

In PHP, Design patterns are technically a description of communication between objects and classes which are customized in order to solve a common obstacle related to designs in a particular context. Basically, they provide a common reusable solution to everyday programming problems. Design patterns or templates help in speeding up the process of web development and can be used multiple times in different scenarios as required.

Q107. What is cross site scripting in PHP?
Answer

Cross-Site Scripting (XSS) is one of the most common and dangerous security vulnerabilities existing within web applications. It is a means to gain unauthorized access by attacking PHP scripts present in your web app.

Q108. What is abstract method and abstract class?
Answer

In PHP, an abstract class is one in which there is at least one abstract method. An abstract method is one that is declared as a method but not implemented in the code as the same.

abstract class ParentClass {
  abstract public function someMethod1();
  abstract public function someMethod2($name, $color);
  abstract public function someMethod3() : string;
}

Q109. What is 'This' key word?
Answer

In PHP, the “This” keyword is a reference to a PHP object which has been created by the interpreter for the user containing an array of variables. If “this” keyword is called inside a normal method within a normal class, it returns the object to the appropriate method.

Q110. How to use Exception handling?
Answer

Exception handling was introduced in PHP 5 as a new way for the execution of code and what exceptions to make in code in case of a specific error.

There are various keywords of exception handling in PHP like:

Try: This try block consists of the code which could potentially throw an exception. All the code in this try block is executed unless and until an exception is thrown.

Throw: This throw keyword is used to alert the user of a PHP exception occurrence. The runtime will then use the catch statement to handle the exception.

Catch: This keyword is called only when there is an exception in the try block. The code of catch must be such that the exception thrown is handled efficiently.

Finally: This keyword is used in PHP versions 5.5 and above where the code runs only after the try and catch blocks have been executed. The final keyword is useful for situations where a database needs to be closed regardless of the occurrence of an exception and whether it was handled or not.

Note: From the vast number of PHP interview questions, answering this will help you to align yourself as an expert in the subject. This is a very tricky question that often makes developers nervous.

Q111. What is difference between drop table and truncate table?
Answer
Truncate Table Drop-Table
It is a DDL Command This command is used to remove a table from the database.
It is executed using a table lock and the whole table is locked while removing all the records. Using this, all the rows, indexes and other privileges shall also be removed.
The WHERE clause cannot be used with TRUNCATE. By using this command, no DML triggers shall be fired.
It removes all rows within a table. Once started, this operation cannot be rolled back again.
Minimum logging required in the transaction log. Hence, it is more efficient. It is also a DDL command.
This command is used to remove all the data by re-allocating the data pages to store only table data and only using it for recording page deallocations. Removes multiple table data definitions within a database.
Q112. What is difference between __sleep and __wakeup()?
Answer
_sleep() _wakeup()
It is used to return the array of all the variables which need to be saved. It is used to retrieve all the arrays returned by the _sleep() command.
It is executed before the serialize() command. Is executed before the unserialize() command.