PHP

Most Essential And Frequently Asked Interview Questions And Answer

Ans:

Session in php

A session is a global variable which is used to store users/sensitive information on the server. Each session register a unique session id which is use to fetch stored value. Session store data as an associative array. Once a session variable is created then it is used across multiple page. By default, session variables last until the user closes the browser or leave the site otherwise most of the server terminate the session variable if you are not active more than 24 minutes on the site.

View Detials
Ans:

header() function

  1. The header() function in php is use to sends a raw HTTP header to a client.
  2. With the help of header() function we can Change page location, set timezone, set caching control, etc.
  3. It does not return any value means it is a void type
  4. It accept three parameter(i.e.: string, replace and http_response_code)
  5. It is important to Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
View Detials
Ans:

PHP-MYSQL |  mysqli_fetch_assoc() VS  mysqli_fetch_array()

mysqli_fetch_assoc() function fetch a result row as an associative array where as mysqli_fetch_array() function fetch a result row as an associative array, a numeric array, or both.

View Detials
Ans:

 PHP | implode() and explode() function

implode() function is use to convert an array into a string where as explode() function is used to convert an string into an array

View Detials
Ans:

PHP-MYSQL |  mysqli_fetch_object () VS  mysqli_fetch_array()

mysqli_fetch_object()  fetch a result row as an object where as mysqli_fetch_array()  fetch a result row as an associative array, a numeric array, or both.

View Detials
Ans:

strstr() and stristr()

strstr() and stristr() both are use to find first occurence of a string, but the differences are strstr( ) is case sensitive where as stristr( ) is case insensitive.

View Detials
Ans:

Duplicate value can remove from an array by using array_unique function. If two or more array values are the same, the first appearance will be kept and the other will be removed. It takes an input array and returns a new array without duplicate values.

array_unique(array)
View Detials
Ans:

php.ini and .htaccess file

Both php.ini and .htaccess file is configuration file.

php.ini:

It is a configuration file for php setting. It is a special file by which you can make changes in PHP settings. php.ini file provide many setting such as changing of the default max_execution_time = 30, error_reporting = E_ALL & ~E_NOTICE, file_uploads = [on/off]  etc.

 

.htaccess:

It is configuration  file for server setting. With the help of .htaccess file you can make changes in server settings. It is supported by several web servers, including the popular Apache software which is used by most commercial web hosting providers. These files were first used to control user access on per-directory basis. It is used to control a couple of things such as error handling, enabling ssl, ip blocking and ip whitelisting, url redirect and url rewriting etc.

Ans:

Error type in php

There are three main error type in php

  1. Notice Error
  2. Warning Error
  3. Fatal Error
View Detials
Ans:

isset()

The isset () function is used to check whether a variable is set or not. It return true if a variable is set otherwise it return false.

View Detials
Ans:

session_id() function

There is a function session_id() in php which is use to get and/or set the current session id.

 string session_id ([ string $id ] )

for getting session id in php we have to use session_id() function without parameter.

 echo session_id()

if we want to set session id then we need to pass a parameter inside session_id() function. For this purpose we needs to be called session_id() function before session_start()

Ans:

Recursion 

PHP also supports recursive function call like C/C++. In such case, a function calls itself within function.

View Detials
Ans:

PHP | Combine two strings

There are several ways to concatenate two strings in PHP.

Use the concatenation operator [.] and [.=]

There are two string operators which is use for concatenation.

[.]    :  Concatenation operator | Used to combine two string values to create a new string.
[.=]  : Concatenation assignment operator | Appends the argument on the right side to the argument on the left side.

View Detials
Ans:

PHP | file_exists( ) Function

File's existence can be confirmed using file_exist() function which takes file name as an argument.

 file_exist("abc.jpg")
View Detials
Ans:

Session V/S Cookies

Cookie is an array of data stored by the browser on client location and sent to the server with every request. It store limited amount of data about 4kb(i.e.: 4096 bytes). It is less secure than session because it present in client's computer.

Session is an array of data stored on the server and associated with a given user (usually via a cookie containing an id code). It store unlimited amount of data. It is more secure because of stored on the server.

View Detials
Ans:

PHP-MYSQL |  Fetch Recoards From MySql table

There are 4 ways:

  1. mysqli_fetch_row() - Get a result row as an enumerated array
  2. mysqli_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  3. mysqli_fetch_object() - Fetch a result row as an object
  4. mysqli_fetch_assoc() - Fetch a result row as an associative array
View Detials
Ans:

A example code showing the nested ternary conditional operator in PHP.

 <?php

$background_color = ($num == 0 ? 'blue' : ($num > 0 ? 'green' : 'red'));

?>

Here we are assigning different strings to the $background_color variable based on a numeric value ($num). 

Ans:

A trick to check whether a number is even or odd without using any condition or loop.

 <?php

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

$check=13;

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

?>

 

Ans:

Bellow code is use for the same

 $date1 = date(‘Y-m-d’);
$date2 = ‘2006-08-15’;
$days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);
echo $days;

 

Ans:

Remove html tags from string

The strip_tags() function is use to remove any HTML, XML, and PHP tags from a string.

View Detials
Ans:

Access specifiers

An access specifier is a code element which is used to determine which part of the program is allowed to access a particular variable or other information.

View Detials
Ans:

For increaseing the speed of a query we have to do couple of things

  • First of all instead of using select * from table1, use select column1, column2, column3.. from table1.
  • Try to introduce index in the table.
  • Always use limit keyword if we are looking for any specific number of rows from the result set.
Ans:

PHP | max_execution_time directive in php.ini file

By changing the value of  max_execution_time in php.ini file

max_execution_time = 30; // in second
View Detials
Ans:

The default maximum size of a file that can be uploaded using PHP is 2MB.

 upload_max_filesize = 2M;

and we can change the maximum size by changing the value of upload_max_filesize in our php.ini file.

 upload_max_filesize = 5M;
Ans:

The explode() and split() both function is use to split a string into an array. But the difference is explode() function splits a string into array by string where as Split function splits string into array by regular expression.

View Detials
Ans:

Predefined classes in PHP are:

  1. Directory
  2. stdClass
  3. __PHP_Incomplete_Class
  4. exception
  5. php_user_filter
Ans:

$name and $$name both are variables but with a single difference that is $name is just a normal php variable where as $$name is known as reference variable. It allow you to use $name variable's value as a variable for getting $$name variable value. 

View Detials
Ans:

By using move_uploaded_file() function we can upload file in PHP.The move_uploaded_file() function moves an uploaded file to a new location.

This function returns TRUE on success, or FALSE on failure.

 move_uploaded_file(file,newloc)
View Detials
Ans:

Bellow code is use for the same

 $sql = "SELECT * FROM table1";
$result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo $num_rows;

 

Ans:

By default, session variables last until the user closes the browser or leave the site otherwise most of the server terminate the session variable if you are not active more than1440 sec or 24 minutes on the site.

Ans:

Constant in php

The define() function is use to defining a constant in php

 define("GREETING", "Welcome to StudyZone4U.com");
View Detials
Ans:

Send mail in PHP

The mail() function allows you to send emails directly from a script.

mail(to,subject,message,headers,parameters);
View Detials
Ans:

There are two ways to find number of elements in an array:

1. sizeof($arr), This function is an alias of count()

 echo sizeof($arr);

2. count($arr)

 echo count($arr);

 

Ans:

The three different way in PHP to connect with MySQL is:

  1. MySQL
  2. MySQLI
  3. PDO

Note: We should use MySQLI because MySQLI is imporoved version of MySQL and have more function then MySQL.

Ans:

$_SERVER['REMOTE_ADDR'] id use to get the IP address of the user.

View Detials
Ans:

magic fuction

In PHP all functions start with __ names are magical functions. Magical functions always lives in a PHP class.The definition of magical function are defined by programmer itself.

Here are list of magic functions available in PHP

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

Ans:

Inheritance

PHP mainly support two type of inheritance:

  • Single inheritance
  • Multilevel inheritance
Ans:

unlink() and unset()

The unlink() and unset() function in php have same functionality (i.e.: delete) but the difference is in the type of data on which they are applied to perform such delete functionalities.

unlink() used to delete files from directory where as unset() is used to unset or delete the variable.

View Detials
Ans:

Cross-site scripting (XSS)

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side script into web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same-origin policy.

Ans:

Length of a string

There is a string function called strlen() which is used to find the length of a string. It accept a string returns the length of the given string. 

strlen(string);
View Detials
Ans:

List 

List is a language construct and is similar to an array. It is used to assign a list of variables in one operation. If you are using PHP 5, then the list values start from a right parameter, and if you are using PHP 7, then the list starts with left parameter.

View Detials
Ans:

By using php date() function we can find the current date and time.

 <?php

echo date(“d-m-Y”); //This will print today date.

echo date (“d-m-Y h:i:s”) // This will print today’s date with current time.

?>

 

Ans:

"==" and "==="

The two operators known as comparison operator. "==" (i.e. equal)  and === (i.e. identical) both are use to check values are same or not. The difference between the two is that '==' should be used to check if the values of the two operands are equal or not whereas, '===' checks the values as well as the type of operands.

View Detials
Ans:

Increase default session  timeout

The "session.gc_maxlifetime" is use to modify the default timout of session.

server should keep session data for AT LEAST 1 hour by using the below code. It increase session default timeout by 1 hour.

 <?php

    //3600 is use for 1 hour

    ini_set('session.gc_maxlifetime', 3600);

?>

 

Ans:

htmlentities()

The htmlentities() function is used to convert all applicable characters to HTML entities.

View Detials
Ans:

:: operator

This operator is known as scope resolution operator. And this operator is use to access the static members of class. To access static members of class we do not need to create object/instance of class.

View Detials
Ans:

PHP | Stop the execution of php script | exit() funtion

By using exit() function we can stop the execution of php script.

View Detials
Ans:

echo and print

PHP echo and print both are used to display the output in PHP. Both can be used with or without parenthese. The differences are small

  • echo has no return value while print has a return value of 1, so it can ve used in expressions.
  • echo can take multiple paramentrs whereas print can take only one argument.
  • echo is marginally faster than print.
View Detials
Ans:

We can use PHP inbuilt function error_reporting(0) to avoid all errors in PHP file.

 <?php

error_reporting(0);

?>

 

Ans:

Enable errors in PHP

There are two ways to enable error reporting in your PHP scripts:

1. You can add the following function in the the script:

error_reporting(E_ALL);

2. You can add the following option in your website's php.ini file:

error_reporting = E_ALL

 

Ans:

Redirect in PHP

PHP header() function is use to redirect a page to another page. It supplies raw HTTP headers to the browser and redirect it to another location. The redirection script should be at the very top of the page to prevent any other part of the page from loading. The target is specified by the Location: header as the argument to the header() function. After calling this function the exit() function can be used to halt parsing of rest of the code.

 header(location: www.studyzone4u.com); // This will redirect to www.studyzone4u.com.

 

Ans:

Superglobal variables 

Superglobal are out of scope limitation. These variables can be accessed from any function, class or any file without doing anything special such as declaring any global variable etc. These variables store information in an array. Commonly they are used to store and get information from one page to another in an application.

Below is the list of superglobal variables available in PHP:

  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_GET
  • $_POST
  • $_SESSION
  • $_COOKIE
  • $_FILES
  • $_ENV
Ans:

require() and require_once()

Both require() and require_once() is use to include a file but the difference is required_once() function checks if the file already included or not where  require() function does not check.

(same for include_once() and include())

Ans:

array to string

By using implode function we can convert any array to string.  In implode function first parameter is separator which specifies what to put between the array elements. Default is "" (an empty string)

View Detials
Ans:

string to array

There is a function in php called explode() which is use to convert any string to array. 

View Detials
Ans:

scopes of variable

Scopes define visibility of a variables. In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be used.

There are three scopes available in php

  1. global
  2. local
  3. static
View Detials
Ans:

PHP | Check data type in php | gettype() | var_dump()

By using gettype() function we can check the data type of a variable.

we can also use var_dump() function for the same.

View Detials
Ans:

require() and include()

The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

(same for require_once() and include_once())

Ans:

Variables can store data of different types, and different data types can do different things.

PHP supports the following data types:

  • String
  • Integer
  • Float (floating point numbers - also called double)
  • Boolean
  • Array
  • Object
  • NULL
  • Resource
Ans:

PHP | Case Sensitive

In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are not case sensitive but all variable names are case-sensitive.

View Detials

Q:What are the errors in below code? What will be output and how can you fix it?

 <?php

$arr = array();
$arr['var1'] = array(1, 2);
$arr['var2'] = 3;
$arr['var3'] = array(4, 5);

$test = array();

$test = array_merge($test, $arr['var1']);
var_dump($test);

$test = array_merge($test, $arr['var2']);
var_dump($test);

$test = array_merge($test, $arr['var3']);
var_dump($test);

?>

 

Ans:

PHP | Array error fix | array_merge()

The output will be as follows:

array(2) { [0]=> int(1) [1]=> int(2) }
NULL
NULL

It will also generate two warning messages as follows:

Warning: array_merge(): Argument #2 is not an array
Warning: array_merge(): Argument #1 is not an array
View Detials

Q:What will be the output of the following statements and why?

var_dump(0123 == 123);
var_dump('0123' == 123);
var_dump('0123' === 123);

 

Ans:

PHP | Output of the following statements var_dump(0123 == 123); var_dump('0123' == 123); var_dump('0123' === 123

 

var_dump(0123 == 123)

This will output bool(false) because the leading 0 in 0123 tells PHP interpreter to treat the value as octal rather than decimal, so the value of 0123 in decimal is equal to 83. so it is clear that 83 is not equal to 123 and will return false.

var_dump('0123' == 123) 

This will output bool(true) since the string '0123' will automatically be converted to integer 123 and the leading 0 is ignored. Now both are same so it will return true.

var_dump('0123' === 123) 

This will outputs bool(false) since "===" is an identical operator which checks value as well as data type, so it performs a more strict comparison and does not do the automatic type conversion of string to an integer. Hence will return false.

Ans:

PHP | Statement $x = 3 + "15%" + "$25"?

The correct answer is 18.

Here’s why:

PHP is a  losely typeed language, therefor it do automatic type conversion based on the context in which a variable or value is being used.

View Detials
Ans:

PHP | output of $a and $b once this code $a = '1'; $b = &$a; $b = "2$b" executed;

Both $a and $b will output a string "21".

View Detials