Signup/Sign In
PUBLISHED ON: MARCH 6, 2023

Top PHP Interview Questions and Answers for Intermediate Level

Php Interview Questions and Answers

PHP is a popular server-side scripting language used for web development. It's widely used in creating dynamic websites and web applications. If you're an intermediate PHP developer preparing for a job interview, it's essential to have a good grasp of the language and its core concepts.

To help you prepare for your upcoming interview, we've compiled a list of the top PHP interview questions and answers for intermediate level developers. These questions cover a range of topics, including PHP basics, object-oriented programming, database connectivity, and more.

By reviewing these questions and answers, you can gain a deeper understanding of the language and be better equipped to tackle common interview questions. You'll also be able to identify any gaps in your knowledge and focus on areas where you need more practice.

So whether you're a seasoned PHP developer or just starting out, read on to discover the top PHP interview questions and answers for intermediate level developers.

PHP Interview Questions and Answers for Intermediate Level

1. How to get IP Address of clients machine?

If we used $_SERVER['REMOTE ADDR'] to get an IP address, the number returned is not always accurate. If the client is connected to the Internet via a proxy server, $_SERVER['REMOTE ADDR'] in PHP returns the proxy server's IP address rather than the user's IP address.

Example:

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

2. What is the use of the .htaccess file in php?

The .htaccess file is a configuration file used on Apache Web Server-powered web servers. It is used to modify the configuration of our Apache Server software in order to activate or disable extra capabilities offered by the Apache Web Server programme.

3. List some array functions in PHP?

array() is a useful and fundamental function in PHP. It permits access to and manipulation of array items.

PHP array() functions listing

  • array()
  • count()
  • array_flip()
  • array_key_exists()
  • array_merge()
  • array_pop()
  • array_push()
  • array_unique()
  • implode()
  • explode()
  • in_array()

4. How to make database connection in PHP?

Example:

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

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

both require() and require_once() are used to incorporate PHP files into other PHP scripts. With need(), it is possible to include the same file several times on a single page. With require_once(), it is possible to call the same file multiple times, but PHP only includes it once.
With need(), it is possible to include the same file several times on a single page. With require once(), it is possible to call the same file multiple times, but PHP only includes it once.


6. List some string function name in PHP?

There are several string functions in PHP that facilitate programming. The following are PHP string functions.

  • nl2br()
  • trim()
  • str_replace()
  • str_word_count()
  • strlen()
  • strpos()
  • strstr()
  • strtolower()
  • strtoupper()

7. How can we upload a file in PHP?

Ensure that the form uses method="post" and enctype="multipart/form-data" for file uploads in PHP. It determines the content-type to utilise during form submission.

$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;
    }
}

8. How many types of errors in PHP?

PHP primarily supports the following four error types:

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

1. Syntax Error: It will occur if the script has a syntax error.

2. Fatal Error: This will occur if PHP can not comprehend your code. For instance, you may be invoking a function that does not exist. Fatal errors halt the script's execution.

3. Warning Error: Inclusion of a missing file or improper number of arguments in a function will result in the following error messages:

4. Notice Error: Occurs while attempting to access an undefined variable.

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

Cookies and Session are both used to store information. The primary distinction between a session and a cookie is that session data is saved on the server, but cookie data is stored on the browsers.

Sessions are more secure than cookies since information is kept on server-side sessions. Additionally, we may disable Cookies in the browser.

Example:

session_start();
//session variable
$_SESSION['user'] = 'StudyTonight.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);

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

PHP offers several methods for managing file operations such as reading, writing, creating, and deleting a file or its contents.

1.file put contents(): This function is used to create a new file.

Syntax:

file_put_contents(file_name, contentstring, flag)

2. file get contents(): This function is used to read the contents of a text file.

file_get_contents($filename);

11. What is the difference between PHP version 5 and PHP version 7?

  • The programming languages php5 and php7 vary.
  • PHP 5 is published on August 28, 2014, PHP 7 on December 3, 2015
  • One of the benefits of the new PHP 7 is the significant performance enhancement.
  • Improved Error Handling
  • Compatible with 64-bit Windows systems
  • Anonymous Group
  • New Operators

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

PHP's count() and size() functions may be used to determine the number of items or values in an array.

Example:

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

echo sizeof($element );

13. How to remove HTML tags from data in PHP?

PHP's strip_tags() function allows us to remove HTML tags from data.

The strip_tags() method removes HTML, XML, and PHP tags from a string.

strip_tags(string,allow)

The first argument must be present. It identifies the string to be validated.

The second argument may be omitted. It defines permitted tags. Not all mention tags will be deleted.

14. How to get complete current page URL in PHP?

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

15. How can we enable error reporting in PHP?


The error_reporting() method specifies which problems are reported. These errors may be modified in the php.ini file. These functions may be used directly in PHP files.

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

16. What is the use of @ in Php?

It suppresses error messages. It's not a good practise to utilise @ since it may result in significant debugging difficulties and even include important mistakes.

17. What is the use of cURL()?

It is a PHP library and command line utility that allows us to transmit and receive files through HTTP and FTP. It also enables proxy servers and SSL connections for data transmission.

Example:

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

18. How to use Exception handling?

PHP 5 added exception handling as a new method for executing code and determining what exceptions to make in the event of a given problem.

There are several exception handling keywords in PHP, including:

  • Try: This try block contains code that might possibly generate an exception. This try block executes all of its function unless and until an exception is raised.
  • Throw: This throw keyword is utilised to notify the user of a PHP exception. The runtime will then use the catch clause to address the error.
  • Catch: This keyword is only invoked if an exception occurs inside the try block. The code of catch must ensure that the thrown exception is effectively handled.
  • Finally: This keyword is used in PHP versions 5.5 and higher, where code is only executed after the try and catch blocks have been executed. In instances when a database must be closed regardless of the incidence of an exception or whether it was handled, the final keyword is beneficial.

19. What are aggregate functions in MySQL?

The aggregate function calculates a collection of values and delivers a single result. It disregards NULL values while doing calculations, with the exception of the COUNT function.

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

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

Example:

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

21. What is the difference between Apache and Tomcat?

Both are used to deploy Java Servlet and JSP applications. The Apache HTTP Server serves HTTP. Tomcat is a Servlet and JSP Server that provides support for Java technologies.

22. What is the difference between REST and Soap?

  • SOAP is an acronym for Simple Object Access Protocol, while REST is an acronym for Representation State Transfer.
  • SOAP is a protocol, while Rest is a type of architecture.
  • SOAP only supports XML data format, but REST supports several data formats like plain text, HTML, XML, JSON, etc.
  • SOAP demands more bandwidth and resources than REST; thus, when bandwidth is limited, SOAP should be avoided.

23. What is the use of friend function?

A friend function in PHP is a non-member function that has access to private and protected class members. The greatest use case for a friend function is when it is shared across many classes and may be specified either as member functions inside a class or as a global function.

24. How to remove blank spaces from the string?

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

25. What are the different functions in sorting an array?

There are many ways to sort an array's elements.

  • sort() - It sorts arrays in ascending order.
  • rsort() - It sorts array elements in descending order.
  • asort() - It sorts associative arrays according to their value in ascending order.
  • ksort() - It sorts associative arrays according to the key in ascending order.
  • arsort() - It sorts associative arrays according to their value in decreasing order.
  • krsort() - It sorts associative arrays according to the key in descending order.

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

Below are the three forms of inheritance.

  • Single inheritance
  • Multiple inheritance
  • Multilevel inheritance

However, PHP only allows single inheritance, meaning that only one class may derive from a single parent class. Interfaces may do the same function as many inheritances.

27. What are the final class and final method?

Only classes and methods may be declared final; properties cannot be. If a class or function is declared final, it cannot be expanded.

Example:

class childClassname extends parentClassname {
    protected $numPages;

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

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

28. What is MVC?

MVC is a PHP programme that isolates the model and application data from the view.

MVC stands for Model, View, and Controller. The controller facilitates communication between models and views.

Example: Laravel, YII, etc

29. What is a composer?

It is a PHP application package manager that offers a common framework for handling PHP software dependencies. Nils Adermann and Jordi Boggiano continue to oversee the project and are developing the composer. The composer is simple to use, and command line installation is possible.

It is available for direct download at https://getcomposer.org/download.

Using the composer may provide solutions to the following issues:

  • Resolution of PHP package dependencies
  • To keep all packages current
  • The solution is PHP package autoloading

30. How to write a program to make chess?

Example:

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

Conclusion

In conclusion, preparing for PHP interviews at the intermediate level requires a deep understanding of the language and its common applications. The questions listed in this article are a great starting point to help you evaluate your knowledge and identify areas where you may need further improvement. Remember, practice makes perfect, so keep working on your skills and confidence, and you'll be well on your way to landing your next PHP development role.



About the author:
Adarsh Kumar Singh is a technology writer with a passion for coding and programming. With years of experience in the technical field, he has established a reputation as a knowledgeable and insightful writer on a range of technical topics.