Best 50 php Interview question for Php developer in 2020

Best 50 php Interview question for Php developer in 2020
Best 50 php Interview question for Php developer in 2020

This Post provides you with a compilation of the top PHP interview questions you might face during your job interview in 2020.  This post will help you  to understand basic to advance PHP.

Best 50 php Interview question for Php developer in 2020

Contents hide
1 Best 50 php Interview question for Php developer in 2020

What is PHP?

PHP stands for Hypertext Preprocessor. It is an open source server-side scripting language which is widely used for web development,  that allow developers to dynamically create generated web pages. It supports many databases like MySQL, Oracle, Sybase, Solid, PostgreSQL, generic ODBC etc.

 Which programming language does PHP resemble?

PHP syntax resembles Perl and C

 What is PEAR in PHP?

PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP Extension and Application Repository. It contains all types of PHP code snippets and libraries. It also provides a command line interface to install “packages” automatically. It extends PHP and provides a higher level of programming for web developers.

What is the difference between static and dynamic websites?

Static Websites Dynamic Websites
Static website is the basic type of website that is easy to create. You don’t need the knowledge of web programming and database design to create a static website. Its web pages are coded in HTML.

The codes are fixed for each page so the information contained in the page does not change and it looks like a printed page

It uses the HTML code for developing a website.

Dynamic website is a collection of dynamic web pages whose content changes dynamically. It accesses content from a database or Content Management System (CMS). Therefore, when you alter or update the content of the database, the content of the website is also altered or updated.

Dynamic website uses client-side scripting or server-side scripting, or both to generate dynamic content.

It uses the server side languages such as PHP,SERVLET, JSP, and ASP.NET etc. for developing a website.

Is PHP a case sensitive language?

PHP is partially case sensitive. The variable names are case-sensitive but function names are not. If you define the function name in lowercase and call them in uppercase, it will still work. User-defined functions are not case sensitive but the rest of the language is case-sensitive

e.g. If we define a variable $book= “php”; then we must need to use $name. $NAME will not work

If we define function do_work() {} then calling DO_WORK() will also work.

How is the comparison of objects done in PHP?

We use the operator ‘==’ to test is two objects are instanced from the same class and have same attributes and equal values. We can test if two objects are referring to the same instance of the same class by the use of the identity operator ‘===’.

  • Comparision operator (==)
  • Identity operator (===)
COMPARISON OPERATORS
Comparing Objects == ===
Reference Yes Yes
Instance with matching properties Yes No
Instance with different properties No No

How can PHP and HTML interact?

It is possible to generate HTML through PHP scripts, and it is possible to pass pieces of information from HTML to PHP.

PHP is a server-side programming language and is used in back-end Web Development usually with MySQL. While HTML is a mark-up language and is used in front-end Web Development that is responsible to the web-page’s layout together with CSS and Javascript.

PHP in HTML

<html>

<head></head>
<body class=”page_bg”>
Hello, today is <?php echo date(‘Y-m-d’); ?>.
</body>

</html>

HTML in PHP

<?php
$Fname = $_POST[“Fname”];
$Lname = $_POST[“Lname”];
?>
<html>
<head>
<title>Personal INFO</title>
</head>
<body>
<form method=”post” action=”<?php echo $PHP_SELF;?>”>
First Name:<input type=”text” size=”12″ maxlength=”12″ name=”Fname”><br />
Last Name:<input type=”text” size=”12″ maxlength=”36″ name=”Lname”><br /></form>
<?
echo “Hello, “.$Fname.” “.$Lname.”.<br />”;
?>

 How can PHP and Javascript interact?

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 can generate Javascript code to be executed by the browser and it is possible to pass specific variables back to PHP via the URL.

<script type='text/javascript'>
var myVar = <?php echo $myVar; ?>;
</script>

What is needed to be able to use image function?


GD library is needed to execute image functions.

What is the use of the function ‘imagetypes()’?
imagetypes() gives the image format and types supported by the current version of GD-PHP.

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

  • PHP echo output one or more string. It is a language construct not a function. So use of parentheses is not required. But if you want to pass more than one parameter to echo, use of parentheses is required. Whereas, PHP print output a string. It is a language construct not a function. So use of parentheses is not required with the argument list. Unlike echo, it always returns 1.
  • Echo can output one or more string but print can only output one string and always returns 1.
  • Echo is faster than print because it does not return any value.

What is the purpose of break and continue statement?

Break – It terminates the for loop or switch statement and transfers execution to the statement immediately following the for loop or switch.

Continue – It causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

What is overloading and overriding in PHP?

Overloading is defining functions that have similar signatures, yet have different parameters. Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that method. In PHP, you can only overload methods using the magic method __call.

What is the difference between $message and $$message in PHP?

They are both variables. But $message is a variable with a fixed name. $$message is a variable whose name is stored in $message. For example, if $message contains “var”, $$message is the same as $var.

What is the main difference between require() and require_once()?

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

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

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.

What is Namespace?

Namespaces are a way of encapsulating items. In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating reusable code elements such as classes or functions:

  1.    Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  2.    Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.

PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants.

In simple terms, think of a namespace as a person’s surname. If there are two people named “James” you can use their surnames to tell them apart.

namespace MyProject;

function output() {
# Output HTML page
echo 'HTML!';
}
namespace RSSLibrary;
function output(){
#  Output RSS feed echo 'RSS!';
}

Later when we want to use the different functions, we’d use:

\MyProject\output();
\RSSLibrary\output();

Or we can declare that we’re in one of the namespaces and then we can just call that namespace’s output():

namespace MyProject;

output(); # Output HTML page
\RSSLibrary\output();

How can we create a database using PHP and MySQL?

The basic steps to create MySQL database using PHP are:

  • Establish a connection to MySQL server from your PHP script.
  • If the connection is successful, write a SQL query to create a database and store it in a string variable.
  • Execute the query.

What is GET and POST method in PHP?

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. For example –

https://www.technolila.com/index.htm?name1=value1&name2=value2

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.

What is the difference between GET and POST method?

GET POST
  • The GET method is restricted to send upto 1024 characters only.
  • The POST method does not have any restriction on data size to be sent.
  • GET can’t be used to send binary data, like images or word documents, to the server.
  • The POST method can be used to send ASCII as well as binary data.
  • The data sent by GET method can be accessed using QUERY_STRING environment variable.
  • The data sent by POST method goes through HTTP header so security depends on HTTP protocol.
  • The PHP provides $_GET associative array to access all the sent information using GET method.
  • GET requests can be cached
  • GET requests remain in the browser history
  • GET requests can be bookmarked
  • GET requests should never be used when dealing with sensitive data
  • GET requests have length restrictions
  • GET requests are only used to request data (not modify)
  • The PHP provides $_POST associative array to access all the sent information using POST method.
  • POST requests are never cached
  • POST requests do not remain in the browser history
  • POST requests cannot be bookmarked
  • POST requests have no restrictions on data length

What is the use of callback in PHP?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
PHP callback are functions that may be called dynamically by PHP. They are used by native functions such as array_map, usort, preg_replace_callback, etc..
eg.

function greeting($name) {
  echo $name;
}

function processUserInput($callback) {
  $name = 'technolila';
  $callback($name);
}

processUserInput('greeting');

output: technolila

What are PHP Magic Methods/Functions?

PHP functions that start with a double underscore – a “__” – are called magic functions (and/or methods) in PHP. They are functions that are always defined inside classes, and are not stand-alone (outside of classes) functions

PHP provides a number of ‘magic‘ methods that allow you to do some pretty neat tricks in object oriented programming.

Here are list of Magic Functions available in PHP

__destruct() __sleep()
__construct() __wakeup()
__call() __toString()
__get() __invoke()
__set() __set_state()
__isset() __clone()
__unset() __debugInfo()

What is NULL?

NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like this −
$my_var = NULL;

What is the purpose of constant() function?

As indicated by the name, this function will return the value of the constant. This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It is stored in a variable or returned by a function.

Note:By default, a constant is case-sensitive. By convention, constant identifiers are always uppercase. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren’t actually constants).

<?php
define("TECH", 350);
echo TECH;

?>

How will you get information sent via get method in PHP?

The PHP provides $_POST associative array to access all the sent information using POST method.

What is the purpse $_REQUEST variable?

PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting an HTML form.The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods

26.What is the difference between include() Function and require() Function?

  • require will produce fatal error ( E_COMPILE _ERROR ) and stop the script.
  • include will produce only warning ( E_WARNING ) and script will continue.

 What are some common error types in PHP?

PHP supports three types of errors, they are:

Notices – Errors that are non-critical in nature. These occur during the script execution. Accessing an undefined variable is an instance of a Notice.
Warnings – Errors that have a higher priority than Notices. Like with Notices, the execution of a script containing Warnings remains uninterrupted. Example of a Notice is including a file that doesn’t exist.
Fatal Error – A termination in the script execution results as soon as such an error is encountered. Accessing a property of a non-existing object yields a Fatal Error.

What are the various ways of handling the result set of Mysql in PHP?

There are 4 ways of handling the result set of Mysql in PHP

  • mysqli_fetch_array
  • mysqli_fetch_assoc
  • mysqli_fetch_object
  • mysqli_fetch_row

Explain the differences between the echo and print statements in PHP?

There are two statements for getting output in PHP – echo, and print. Following are the distinctions between the two:

  • Although used rarely, echo has the ability to take multiple parameters. The print statement, on the contrary, can accept only a single argument
  • Echo has no return value whereas, print has a return value of 1. Hence, the latter is the go-to option for using in expressions
  • Generally, the echo statement is preferred over the print statement as it is slightly faster

Explain the difference between mysqli_connect() and mysqli_pconnect() functions?

Answer: Both mysqli_connect() and mysqli_pconnect() are functions used in PHP for connecting to a MySQL database. mysqli_pconnect ensures that a persistent connection is established with the database. It means that the connection doesn’t close at the end of a PHP script.

Explain $_SESSION in PHP?

The $_SESSION[] is called an associative array in PHP. It is used for storing session variables that can be accessed during the entire lifetime of a session.

What are major differences between for and foreach loop in PHP?

Following are the notable differences between for and foreach loop:

  • The foreach loop is typically used for dynamic array
  • The for loop has a counter and hence requires extra memory. The foreach loop has no counter and hence there is no requirement for additional memory
  • You need to determine the number of times the loop is to be executed when using the for loop. However, you need not to do so while using the foreach loop

>

Variable/s Numerical and associative arrays
At the end of the given condition At the end of the array count
Single Two
for(expr1; expr2; expr3)
{//If expr2 is true, do this}
foreach ($array as $value)
{//Do Something}
//Another form, for key & values
foreach ($array as $key => $value)
{//Do Something}

 

Example for For loop
<?php
for ($i = 1 ; $i <= 20 ; ++$i)
echo "$i minutes has " . $i * 60 . " seconds"."<br>";
?>
Example of Foreach loop
<?php
$arr=array('Ox','Goat','Elephant','Horse');
foreach($arr as $name)
{
echo $name.'<br/>';
}
?>

What is use of the header() function in PHP?

  • header() is used to redirect from one page to another: header(“Location: index.php”);
  • header() is used to send an HTTP status code: header(“HTTP/1.0 this Not Found”);
  • header() is used to send a raw HTTP header: header(‘Content-Type: application/json’);

How can you tell if a number is even or odd without using any condition or loop?

 

$arr=array("0"=>"Even","1"=>"Odd");

$check=19;

echo "Your number is: ".$arr[$check%2];

What is the difference between a session and cookies?

1. Session can store any type of data because the value is of data type of “object”
2. These are stored at server side.
3. Sessions are secured because it is stored in binary format/encrypted form and gets decrypted at server.
4. Session is independent for every client i.e. individual for every client.
5. There is no limitation on the size or number of sessions to be used in an application.
6. We cannot disable the sessions. Sessions can be used without cookies also.
7. The disadvantage of session is that it is a burden or an overhead on server.
8. Sessions are called as Non-Persistent cookies because its life time can be set manually
1. Cookies can store only “string” datatype.
2. They are stored at client side.
3. Cookie is non-secure since stored in text-format at client side.
4. Cookies may or may not be individual for every client.
5. Size of cookie is limited to 40 and number of cookies to be used is restricted to 20.
6. Cookies can be disabled.
7. Since the value is in string format there is no security.
8.We have persistent and non-persistent cookies.

Will it be possible to extend the execution time of a PHP script? How?

Yeah, it is possible to extend the execution time of a PHP script. We have the set_time_limit(int seconds) function for that. You need to specify the duration, in seconds, for which you wish to extend the execution time of a PHP script. The default time is 30 seconds.

What will be the values of $a and $b after the code below is executed? Explain your answer.

 

$a = '1';
$b = &$a;
$b = "2$b";

Both $a and $b will be equal to the string “21” after the above code is executed.

Subsequently execute the statement $b = “2$b”, $b is set equal to the string “2” followed by the then-current value of $b (which is the same as $a) which is 1, so this results in $b being set equal to the string “21”

How can we get the IP address of the client?

There are many options. $_SERVER["REMOTE_ADDR"]; is the easiest solution. You can write few line code also for this.

What’s the difference between unlink() and unset()

UNLINK() FUNCTION UNSET() FUNCTION
It is used to delete a file within a directory completely on successful execution. It is used to make a specific file empty by removing its content.
There are two parameter filename and the other one is context. There is only one parameter variable.
Return True on success and false on failure. This function does not return any value.
This is a function for file system handling. This is a function for variable management.

How can you enable error reporting in PHP?

error_reporting — Sets which PHP errors are reported

 

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

This is the most common way to write it, but a syntax error gives blank output, so use the console to check for syntax errors. The best way to debug PHP code is to use the console; run the following:

What are Traits?

In 5.4 PHP version trait is introduced to PHP object-oriented programming. A trait is like class however it is only for grouping methods in a fine-grained and reliable way. It isn’t permitted to instantiate a trait on its own. Traits are introduced to PHP 5.4 to overcome the problems of single inheritance. As we know in single inheritance class can only inherit from one other single class

 

<?php
   trait Reader{
      public function add($var1,$var2){
         return $var1+$var2;
      }
   }
   trait writer {
      public function multiplication($var1,$var2){
         return $var1*$var2;
      }
   }
   class File {
      use Reader;
      use writer;
      public function calculate($var1,$var2){
         echo "Ressult of addition:".$this->add($var1,$var2) ."\n";
         echo "Ressult of multiplication:".$this->multiplication($var1,$var2);
      }
   }
   $o = new File();
   $o->calculate(5,3);
?>
Result of addition two numbers:8
Result of multiplication of two numbers:15

Can the value of a constant change during the script’s execution?

No, the value of a constant cannot be changed, once it’s declared during the PHP execution.

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

Constructors:

When creating a new object, you can pass a list of arguments to the class being called. These are passed to a special method within the class, called the constructor, which initializes various properties. To do this you use the function name __construct (that is, construct preceded by two underscore characters)

<?php
    class Person {
        // first name of person
        private $fname;
        // last name of person
        private $lname;
        
        // Constructor
        public function __construct($fname, $lname) {
            echo "Initialising the object...<br/>"; 
            $this->fname = $fname;
            $this->lname = $lname;
        }
        
        // public method to show name
        public function showName() {
            echo "My name is: " . $this->fname . " " . $this->lname; 
        }
    }
    
    // creating class object
    $john = new Person("John", "Wick");
    $john->showName();
    
?>

Output:

Initialising the object…

My name is John Wick

Deconstructors:

You also have the ability to create destructor methods. This ability is useful when code has made the last reference to an object or when a script reaches the end.

PHP Destructor method is called just before PHP is about to release any object from its memory. Generally, you can close files, clean up resources etc in the destructor method.

Many system-wide problems are caused by programs reserving resources and forgetting to release them.

Let’s take an example

 

?php
    class Person {
        // first name of person
        private $fname;
        // last name of person
        private $lname;
        
        // Constructor
        public function __construct($fname, $lname) {
            echo "Initialising the object...<br/>"; 
            $this->fname = $fname;
            $this->lname = $lname;
        }
        
        // Destructor
        public function __destruct(){
            // clean up resources or do something else
            echo "Destroying Object...";
        }
        
        // public method to show name
        public function showName() {
            echo "My name is: " . $this->fname . " " . $this->lname . "<br/>"; 
        }
    }
    
    // creating class object
    $john = new Person("John", "Wick");
    $john->showName();
    
?>

OutPut:

Initialising the object…

My name is: John Wick

Destroying Object..

What are the 3 scope levels available in PHP and how would you define them?

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

What does MVC stand for and what does each component do?

MVC stands for Model View Controller.

How does one prevent the following Warning ‘Warning: Cannot modify header information – headers already sent’ and why does it occur in the first place?

Do not output anything to the browser before using code that modifies the HTTP headers. Once you call echo or any other code that clears the buffer you can no longer set cookies or headers.

This error message gets triggered when anything is sent before you send HTTP headers (with setcookie or header). Common reasons for outputting something before the HTTP headers are:

  • Accidental whitespace, often at the beginning or end of files
  • Explicit output, such as calls to echoprintfreadfilepassthru, code before <? etc

46.What are SQL Injections, how do you prevent them and what are the best practices?

SQL Injection (SQLi) is a type of an injection attack that makes it possible to execute malicious SQL statements.SQL injection is one of the most common web hacking techniques.SQL injection is the placement of malicious code in SQL statements, via web page input.

keep your database safe from the SQL Injection Attacks, you can apply some of these main prevention methods:

1. Using Prepared Statements (with Parameterized Queries)
2. Using Stored Procedures
3. Validating user input
4. Limiting privileges
5. Hidding info from the error message
6. Updating your system
7. Keeping database credentials separate and encrypted
8. Disabling shell and any other functionalities you don’t need

Why would you use === instead of ==?

Two of the many comparison operators used by PHP are ‘==’ (i.e. equal) and ‘===’ (i.e. identical). The difference between the two is that ‘==’ should be used to check if the values of the two operands are equal or not. On the other hand, ‘===’ checks the values as well as the type of operands.

How to submit a Form without a submit button?

On OnClick event of a label in the form, a JavaScript function can be called to submit the form.
document.form_name.submit()

What does isset() function?

The isset() function checks if the variable is defined and not null.

What are the functions to be used to get the image’s properties (size, width and height)?

The functions are getimagesize() for size, imagesx() for width and imagesy() for height

How to initiate a session in PHP?

The use of the function session_start() lets us activating a session.

 

Best 50 php Interview question for Php developer in 2020

Written By

vijay1983

Comments :

Leave a Reply