PHP Interview Questions: Core PHP Interview Questions. PHP is a server-side scripting language designed for Web development, but also used as a general-purpose programming language.
PHP Interview Questions
Q. What is PHP?
PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language.
  • Created by Rasmus Lerdorf
  • Year 1994
  • PHP (Originally) Called Personal Home Page
  • PHP (Now) Called PHP: Hypertext Preprocessor
Note: Current Stable Version of PHP is 7.3.2. To check latest php version visit http://php.net/downloads.php
Q. What is the use of "echo" in PHP?

It is used to print a data in the webpage

echo "Core PHP Interview Questions and Answers"; //Output- Core PHP Interview Questions and Answers
Q. How do you define a constant?
define("SITE_MESSAGE", "PHP Interview Questions"); echo SITE_MESSAGE;
Q. What are Global variables in PHP?

Following are the built-in variables that are always available in all scopes, called "superglobals" in PHP.

  1. $GLOBALS
  2. $_SERVER
  3. $_GET
  4. $_POST
  5. $_REQUEST
  6. $_SESSION
  7. $_COOKIE
  8. $_FILES
  9. $_ENV
Q. Difference between echo and print in PHP?
Both are used to output a data. Echo is slightly faster than print. Echo does not return any value while print return 1.
Q. How many types of errors in php ? Explain in brief.
There are three main type error in PHP.
  1. Notices: As the name says, Notices are errors which occur while you may not initialize variable or any other things. This will generate only notice on the view page. This will not terminate the running script.
  2. Warnings: This is run-time warnings and does not terminate the script execution. This error mostly occurs when you forgot to include () a file.
  3. Fatal Errors:These are most critical error of the PHP. It can terminate your script. Example of this error is forgotten to semicolon (;) in the script. another example of a Fatal error would be accessing a property of a non-existent object or require() a non-existent file
Q. How to initialize error in PHP?
  1. error_reporting(E_ALL);
  2. ini_set(‘display_errors’, 1);
Q. What is difference between EMPTY ($variable = "") or NULL ($variable = NULL) variable in PHP?
Null means nothing. It’s just a literal. Null is the value of reference variable. But the empty string is blank. It gives the length=0. An empty string is a blank value, means the string does not have anything. (Source from Stack overflow)
You may also like: OOPS Interview Questions and Answers
Q. What is session and cookies in php?
  • Session: A session is a way to store data on the web-server. You can use session variables throughout all pages of your application. Normally session will destroy when you close the browser.
  • Cookie: A Cookies is a way to store data on the user’s computer. It is mostly used for identify user. You can set cookies, get cookies or delete cookies by php functions.
Sr.No Session Cookie
1 Sessions are small files that are stored on the website's server. in other words Sessions are server-side files that contain user information Cookies are small files that are stored in the visitor's browser. in other words Cookies are client-side files that contain user information
2 Sessions have a limited lifespan; they expire when the browser is closed. Cookies can have a long lifespan, lasting months or even years.
3 Sessions are only limited in size if you limit their size on the server. Cookies are limited in size depending on each browser's default settings.
4 Sessions cannot be disabled by the visitor because they are not stored in the browser. Cookies can be disabled if the visitor's browser does not allow them (uncommon).
5 Sessions cannot be edited by the visitor. Cookies can be edited by the visitor. (Do not use cookies to store sensitive data.)
6 Safe Not very safe
7 In php $_SESSION super global variable is used to manage session. In php $_COOKIE super global variable is used to manage cookie.
8 You can store as much data as you like within in sessions.The only limits you can reach is the maximum memory a script can consume at one time, which by default is 128MB. php.ini, memory_limit = 128M Official MAX Cookie size is 4KB
9 Before using $_SESSION, you have to write session_start(); In that way session will start and you can access $_SESSION variable on that page.To avoid header already sent issue use ob_start(); on top of script You don't need to start Cookie as It is stored in your local machine.
Q:- Whether session will work if we disable cookies in client browser?

Yes, session will work when cookies is disabled. In PHP, Sessions use cookies. By default the sessionid stores in Cookies.

This is most frequently asked interview question related to session and cookies

How PHP sessions work without cookies:
  1. Form -Hidden Input
  2. In URL using Query String
What is a disadvantage of using PHP sessions without cookies enabled?
There are three methods to propagate a session id:
  1. Cookies - recommended
  2. Form - not recommended
  3. URL parameter - A major disadvantage it is not safe and may be cause of session hijacking.

Note- Following config seeting should be taken care of (php.ini)

  1. session.use_cookies=1
  2. session.use_only_cookies=1
  3. session.use_trans_sid=0
OR
ini_set("session.use_cookies", 0); ini_set("session.use_only_cookies", 0); ini_set("session.use_trans_sid", 1); session_start();
Q. How to redirect page in PHP?

using header() funtion

#Example:
you should use die() or exit() after header() function
header("Location: http://www.fullstacktutorials.com/contact.html");
die();
Note: header() redirects only work before anything is written out.
You may also like: React Js Interview Questions and Answers
Q. What is difference between GET and POST Method?
GET and POST are two most popular HTTP methods normally uses for send data from one page to another page.
Key GET POST
Bookmarked Can be bookmarked Cannot be bookmarked
Cached Can be cached Not cached
Encoding application/x-www-form-urlencoded application/x-www-form-urlencoded or multipart/form-data. Use multipart encoding for binary data
History Parameters remain in browser history Parameters are not saved in browser history
Data length Yes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters) No restrictions
Data type Only ASCII characters allowed No restrictions. Binary data is also allowed
BACK button/Reload Harmless Data will be re-submitted (the browser should alert the user that the data are about to be re-submitted)
Security GET is less secure compared to POST because data sent is part of the URL

Never use GET when sending passwords or other sensitive information!
POST is a little safer than GET because the parameters are not stored in browser history or in web server logs
Visibility Data is visible to everyone in the URL Data is not displayed in the URL
Q. What is use of isset() function in PHP?
isset — Determine if a variable is set and is not NULL. The isset () function is used to check whether a variable is set or not. If a variable is already unset with unset() function, it will no longer be set. The isset() function return false if testing variable contains a NULL value.
Q. Difference between isset() and empty() in PHP?

isset(): checks if a variable has a value including ( False , 0 , or empty string) , but not NULL. Returns TRUE if var exists; FALSE otherwise.

empty(): function checks if the variable has an empty value empty string , 0, NULL ,or False. Returns FALSE if var has a non-empty and non-zero value."

Q. How to get current date and time using PHP?
date(‘d-m-Y h:i:s’);
Q. How to retrieve session data in PHP?
You can use $_SESSION to retrieve session variables.
Q. How to destroy session?
You can use destroy($_SESSION); or unset($_SESSION['VARIABLE_NAME']);
Q. How to set, get and delete cookie in php?
Set Cookie :
setcookie("CookieName", "Core PHP Interview Questions and Answers", time()+3600);
Get cookie :
$_COOKIE["CookieName"];
Delete Cookie :
unset($_COOKIE['CookieName']); Setcookie("CookieName", null, time()-3600);
Q. What is $_REQUEST in php? Where to use it?
An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
Q. How to get current page url in PHP?
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; echo $actual_link;
Q. How to get system name in PHP?
echo $_SERVER['HTTP_USER_AGENT'];
Q. How to send mail using PHP?
mail(to,subject,message,headers,parameters); #Example: $to = "fullstacktutorials@gmail.com"; $subject = "PHP Interview Questions"; $txt = "Core PHP Interview Questions and Answers"; $headers = "From: frommail@example.com" . "\r\n" . "CC: ccmail@example.com"; mail($to,$subject,$txt,$headers);
Note- Best you can use PHPMailer Class to send mail
Q. How to concate two string in PHP?
You can concate two string by using (.) Dot Operator.
Q. How to use conditional operator in php?
The syntax of ternary operator is as below Syntax: Condition ? true: false
Q. How to include a file in a PHP page?

We can include a file using "include()" or "require()" function with file path as its parameter.

Q. What difference is between include and require?
  • include() will attempt to load the specified file, but will allow the script to continue if not successfully loaded.
  • require(), on the other hand will cause a “Fatal Error” to occur if the specified file is not successfully loaded.
Use require() if you want the safeguard the script from completing upon failure to load external file.
Q. What is the difference between include(), include_once() and require(), require_once()?

The only difference between the two is that require and require_once throw a fatal error if the file is not found, whereas include and include_once only show a warning and continue to load the rest of the page.

Q. What is difference between implode() and explode()?

explode() function convert a string into an array, while implode() function convert an array into string.

Q. Which array function is used for count array elements?
  1. count($array)
  2. sizeof($array)
Q. What is difference between array_merge() and array_combine()?
array_merge()

array_merge() - merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one.

Note - If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
//1. Example: $array1 = array("one" => "PHP","two" => "MySQL"); $array2 = array("one" => "NodeJs","two" => "ReactJs","three"=>"MongoDB"); $result = array_merge($array1, $array2); print_r($result); //Output /* Array ( [one] => NodeJs [two] => ReactJs [three] => MongoDB ) */ //2. Example: $array1 = array("0" => "PHP","1" => "MySQL"); $array2 = array("one" => "NodeJs","two" => "ReactJs","three"=>"MongoDB"); $result = array_merge($array1, $array2); print_r($result); //Output /* Array ( [0] => PHP [1] => MySQL [one] => NodeJs [two] => ReactJs [three] => MongoDB ) */
array_combine()

array_combine() - creates an array by using one array as keys and another array as its values.

Note - Both array must have same number of elements.
$array1 = array("one" => "PHP","two" => "NodeJs"); $array2 = array("one" => "MySQL","two" => "MongoDB"); $result = array_combine($array1, $array2); print_r($result); //Output /* Array ( [PHP] => MySQL [NodeJs] => MongoDB ) */
Q. How many loops in php?
Following loop exists in PHP
  • For loop
  • Foreach loop
  • While loop
  • Do…While loop
You may also like: Node Js Interview Questions and Answers
Q. What is use of explode and implode functions?
Use of explode() and implode() function
  • explode(): Convert string to Array
  • implode(): Convert Array to string
Q. How to get length of string in PHP?
use strlen() function
Q. How to get first and last element of array in php?
For first element: current($arrayname); For last element: end($arrayname);
Q. How to print array in php?
Use print_r($array); function to print array.
Q. How to get random number in php?
Use rand() function to generate random number
Q. How to sort array in PHP?
Some array sorting functions in php are listed below:
  • sort() – sort arrays in ascending order
  • rsort() – sort arrays in descending order
  • asort() – sort associative arrays in ascending order, according to the value
  • ksort() – sort associative arrays in ascending order, according to the key
  • arsort() – sort associative arrays in descending order, according to the value
  • krsort() – sort associative arrays in descending order, according to the key
Q. Methods to encrypt password in PHP

password_hash() – it uses a strong hash, generates a strong salt, and applies proper rounds automatically.

md5() – Note that md5() is not secure now days. Please take care.

bcrypt()The salt parameter is optional. However, crypt() creates a weak password without the salt.

Note: Note that md5() is not secure nowadays. Please take care.
Q. What is PHP $ and $$ Variables? OR What is the difference between $var and $$var?

$var (single dollar) is a normal variable with the name var that stores any type of value like string, integer, float, etc.

$$var (double dollar) is a reference variable that stores the value of the $var inside it.

Q. What is difference between "==" and "===" operator in php?
"==" checks the left and right values are equal or not whether "===" check the left and right values are equal with their data types (e.g. int, float etc)
Q. Is PHP’s functions are case-sensitive?
No, They are not. But as the manual suggest "Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration."
Q. How to delete element from array in php?
Use unset(array_element) function to delete array.
Q. Which function is used to dump the variable?
var_dump();
Q. Which function is used to remove blank element from array?
array_filter();
Q. What is purpose to use array_chunk() function?
array_chunk() is used to split array element in group of small arrays.
Q. How to get a sum of array element?
array_sum() function is used to get total sum of array elements.
Q. How to get unique value from array?
You can use array_unique() function to get unique values.
Q. What’s the difference between unset() and unlink()?
unset() sets a variable to "undefined" while unlink() deletes a file we pass to it from the file system.
Q. What’s the difference between == and === operator?

== and === both are comparison operator and using to check values.

== it check only values and return true if values are same.

=== it check value with it's datatype and return true if both value and datatype are same.

Q. How can we get the IP address of the client?
$_SERVER["REMOTE_ADDR"];
Q. How does one prevent the following Warning ‘Warning: Cannot modify header information – headers already sent’ and why does it occur in the first place?

Since PHP is scripting language so when script code gets parsed line by line PHP parser sent output to browser

if you will put ob_start(); at top of your script code it will tell the PHP parser to send the data to the browser at once when full code get parsed.

You may also like: Top 50 Laravel Interview Questions
Q. How to create a mysql connection?
PDO Connection
$servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); }
MySQLi Connection
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Optional // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully";
MYSQL Connection
$servername = "localhost"; $username = "username"; $password = "password"; $conn = mysql_connect($servername, $username, $password); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($conn);
Q. What are magic methods in PHP?

The Magic methods always start with double underscore "__" and Magic methods are member functions that are available to all the instance of class.

The Magic Methods are:

  1. __call()
  2. __toString()
  3. __sleep()
  4. __wakeup()
  5. __isset()
  6. __unset()
  7. __autoload()
  8. __clone()
  9. __construct()
  10. __destruct()
  11. __set()
  12. __get()
You may also like: MySQL Interview Questions and Answers
Q. What are PSRs? briefly describe it?

PSRs are PHP Standards Recommendations that aim at standardising common aspects of PHP Development.

An example of a PSR is PSR-4, This PSR describes a specification for autoloading classes from file paths

Q. Do you use Composer? If yes, what benefits have you found in it?

Composer have the following advantages:

  1. The dependencies required by the package you are pulling in are automatically taken care by Composer itself, leaving you free to focus on the programming instead of dependency management
  2. When the package you are using gets a new version, a simple composer update will do everything for you, without ever needing to do any file management manually
  3. With Composer you get a centralized autoload.php file which also is optimized with Composer. It loads everything you need and all you do is include one file.
  4. You can use psr-4 namespaces to load a specific path on your application and have it be included in the autoloader file. Then you can simply use the namespace and its available application wise!
Q. How to detect Ajax Request in PHP?

One way to detect an AJAX request is by using the following PHP code:

//Ajax request detection code in PHP if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ){ //write your ajax code here }
You may also like: MongoDB Interview Questions
Q. What is SQL injection?

SQL injection is a malicious code injection technique. It exploiting SQL vulnerabilities in Web applications

Q. How can we increase the execution time of a script in PHP?

By changing max_execution_time either in php.ini config file OR in code using ini_set

ini_set('max_execution_time', 600); //600 seconds = 10 minutes
Q. Write a program to swap two numbers without using third variable?
$a = 5; $b = 10; echo "Old values of a and b are $a, $b
"; $a = $a+$b; $b = $a-$b; $a = $a-$b; echo "New values of a and b are $a, $b
"; //Output //Old values of a and b are 5, 10 //New values of a and b are 10, 5
Q. Write a program to find factorial of a number?
//1. Factorial using Recursion function calFactorial($n = 0){ if($n <= 0){ $out = 1; }else{ $out = $n * calFactorial($n - 1); } return $out; } echo calFactorial(5); //Output //120 //2. Factorial without using Recursion function factorialWithoutRecursion($n = 0){ $out = 1; if($n > 0){ for($i=1;$i<=$n; $i++){ $out = $out * $i; } } return $out; } echo factorialWithoutRecursion(5); //Output //120
Q. Write a program to print all prime numbers from 1-n ?
function printPrimeNo($n = 1){ for($i=1;$i<=$n;$i++){ //numbers to be checked as prime $counter = 0; for($j=1;$j<=$i;$j++){ //all divisible factors if($i % $j==0){ $counter++; } } //prime requires 2 rules ( divisible by 1 and divisible by itself) //2 is only even prime number if($counter==2){ print $i." is Prime
"; } } } printPrimeNo(100); //print all prime numbers from 1-100
Q. Write a program to print the Fibonacci series?

Fibonacci series A series of numbers in which each number is the sum of the two preceding numbers.

A simple of Fibonacci series is 0, 1, 1, 2, 3, 5, 8, etc.

function printFibonacciSeries($n){ $a = 0; $b = 1; echo "Fibonacci Series: "; echo $a.", ".$b.", "; for($i=2;$i<$n;$i++){ $c = $a+$b; if($i != $n-1){ echo $c.", "; }else{ echo $c; } $a = $b; $b = $c; } } //Print Fibonacci series upto 10 numbers. printFibonacciSeries(10); //Output //Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Q. Write a program to reverse a string?
$output = ""; $input = "PHPINTERVIEWQUESTIONS"; $i = 1; echo $input."
"; //Output //PHPINTERVIEWQUESTIONS //First Method, Using PHP Inbuilt function echo strrev($input)."
"; //Output //SNOITSEUQWEIVRETNIPHP //Second Method for($i=1;$i<=strlen($input); $i++){ $data = substr($input, -$i, 1); $output .= $data; } echo $output; //Output //SNOITSEUQWEIVRETNIPHP
Q. Write the output of following code?
//Please consider latest version of php (PHP7) $x = 1; $y = 2; $z = 3; if($x > $y > $z){ echo "True"; }else{ echo "False"; } //Output //Parse error: syntax error, unexpected '>'
Q. Write a program to find maximum repeated words from a String?
$string = "PHP Interview Questions : Core PHP Interview Questions and Answers for freshers and experienced"; $dataArray = explode(' ', $string); $words = array_count_values($dataArray); arsort($words); // Sort associative array by value in descending. print_r($words); //Output /* Array ( [PHP] => 2 [Interview] => 2 [Questions] => 2 [and] => 2 [:] => 1 [Core] => 1 [Answers] => 1 [for] => 1 [freshers] => 1 [experienced] => 1 ) */
Q. Write a program for call by value and call by reference in PHP?
//Call By Value in PHP function callByValue($num) { $num = $num + 1; return $num."
"; } $n = 1; echo callByValue($n); /* Output 2 */ echo $n; /* Output 1 */ //Output /* 2 1 */ echo "
"; //Call by Reference in PHP //In call by reference, the address of a variable (their memory location) is passed. In the case of call by reference, we prepend an ampersand (&) to the argument name in the function definition. Any change in variable value within a function can reflect the change in the original value of a variable which we have shown in the following Example. function callByReference(&$num) { $num = $num + 1; return $num."
"; } $n = 1; echo callByReference($n); /* Output 2 */ echo $n; /* Output 2 */ //Output /* 2 2 */