PHP interview questions for freshers

PHP interview questions for freshers




What is PHP?

  1. Abbreviations of PHP is “PHP: Hypertext Preprocessor”.
  2. Old Name was Personal Home page;
  3. Its scripting language, It not base language like C, C++ , so it depends upon other language like HTML.
  4. It’s used to make ecommerce website, Blogging site, content management website, Database driven Website.
  5. Its licence is free for all means open source.

Who is known as the father of PHP?

Rasmus Lerdorf in 1994

What are type of framework and CMS Supports in PHP?

PHP is very vast like Java and .net. It also Provides lot of CMS and frameworks for easy and better development of software and Websites. In PHP CMS basically used for e-commerce website and blog posting website and frameworks used for dynamic data driven secure application development and API development.

CMS are listed below Built with by PHP language
1. WordPress
2. Drupal
3. Opencart
4. Zencart
5. Magento
6. Joomla

Frameworks are listed below built with PHP language
1. Zend Framework
2. Codeigniter
3. Cakephp
4. Symphony
5. Yii2. etc.

Write sample PHP  Syntax

<!DOCTYPE html>
<html>
<head>
<title>PHP Sample Code</title>
</head>
<body>
<?php echo 'Hello Dude'; ?>
</body>
</html>

Why  “echo” and “print” are different from each other in PHP?

Echo in PHP

  • echo has a void return type.
  • echo can take multiple parameters separated by comma.
  • echo is faster than print.
<?php
$name = "SubhaKalyana";
$profile = "Java developer";
$age = 30;
echo $name , $profile , $age, " years old";
// output is : SubhaKalyanaJava developer30 years old
?>

Print in PHP

  • print has a return value of 1 so it can be used in expressions.
  • print cannot take multiple parameters.
  • print is slower than echo.
<?php
$name = "SubhaKalyana";
$profile = "Java developer";
$age = 30;
print $name , $profile , $age, " years old";
//output will be syntax Error.
?>

How to include a file to a php page?

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

include(“my_file_name.php”);
require(“my_file_name.php”);

What’s the difference between include and require?

In PHP require() and include() are two in-built functions, these function generally used for merge a php file in a another  PHP webpage.

But if include() function is used in a and merged file is not exists then it will show warning message but execution not stop. If require() function is used to merge a file and merged file is missing then it will show fatal error and it will stop the execution.

What’s the difference between include and include_once()?

Include :-Include is used to include files more than once in single PHP script.You can include a file as many times you want.
include(“my_file_name.php”);
Include Once:-Include once include a file only one time in php script.if some one include again same file in same page it will be ignored by this function.
include_once(“my_file_name.php”);

How to set cookies in PHP?

Setcookie("username", "Subhakalyana", time()+3600);

How to Retrieve a Cookie Value in PHP?

Generally if any web browser have the cookie, we can get this cookie by PHP function $_COOKIE[];

echo $_COOKIE["username"]; // output : Subhakalyana 

How to Delete a Cookie Value in PHP?

Cookies can not delete directly, We can only Expire it By passing Past time.

$cookie_name = 'username';
unset($_COOKIE[$cookie_name]);
// empty value and expiration one hour before
setcookie($cookie_name, '', time() - 3600);

How to create a session? How to set a value in session ? How to Remove data from a session?

//Create session
session_start();
//Set value into session
$_SESSION['ID']=1;
//Remove data from a session
unset($_SESSION['ID'];

How to set an execution time for PHP script?

For infinite execution time php script we can set in main file or beginning of the php script

set_time_limit(300);
ini_set('max_execution_time', 300);
// Here We can set eg. 300 sec, or 500 sec as per requirement.

More ever we can set max execution time in directives like  php.ini file.

; Maximum execution time of each script, in seconds
; http://php.net/max-execution-time
; Note: This directive is hardcoded to 0 for the CLI SAPI
max_execution_time = 300

NB: Any changes in php.ini, server must be restart.

What is PHP session_start() and session_destroy() function?

PHP session_start() function is used to start the session. It starts a new or resumes the existing session. It returns the existing session if session is created already. If session is not available, it creates and returns new sessions.
PHP session_destroy() function is used to destroy all session variables completely.

What are string functions in php?

PHP string functions are used to manipulate string values.

strtolower()
strtoupper()
strlen()
explode()
str_replace()..etc.

What are different types of Print Functions available in PHP?

For Print or echo the data in web page PHP have so many functions. these are listed below.

print();
echo();
printf();
sprintf();
var_dump();
print_r();

What does the unlink() function means?

The unlink() function is responsible for file system handling. It simply deletes the file given as entry.

What does the unset() function means?

The unset() function is responsible for variable management. It will make a variable undefined.

How can you enable error reporting in PHP?

Enable  error in php is very important for developer during development to find the bugs or debugging.

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

Here if we go for change in global then, we can set in php.ini file.

 error_reporting=E_ALL

What are the different errors in PHP and what are difference between them?

As of now PHP have 3 types of error.

  1. Warning: Here If  suppose you include a file let “somefile.php” but file is not there then this errors are show to users. Its very important, but it does not stop the execution of PHP script.
  2. Notice: Here If suppose you access a variable but this variable is not declared, in this case error will show to users. But It wont stop the execution of PHP script. It not critical error.
  3. Error: Here If suppose Instantiating an object of a class which does not exist or you are calling a function which is not exist then in this case it will show errors. These errors results in termination of the script immediately, Its very critical,It should be to fixed to proceed further.More ever Twelve different error types are used to represent these variations internally.

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

The header() function sends a raw HTTP header to a client browser. This function must be called before sending the actual out put. For example, You do not print any HTML element before using this function.

How to redirect a page in php?

In PHP header() is the function used for redirect the page to another page, 

header("Location:mypage.php");

How to collect  IP address from an HTTP request ? 

$_SERVER['REMOTE_ADDR'];

How to collect  IP address of the Web server in php ? 

$_SERVER['SERVER_ADDR'];

What is $_GLOBAL ?

It is an associative array which containing references to all variables currently defined in the global scope of the script.

What is the difference between == and === operator in PHP ?

Equal operator:
$x == $y (if $x is equal to $y it will return True);
Identical operator:
$x === $y (if $x is equal to $y, and they are of the same data type then it will return true.)

What is default session time and path in PHP.

Default session time in PHP is 1440 seconds (24 minutes).

How to strip whitespace or other characters from the beginning and end of a string ?

trim(string,charlist)

The trim() function removes whitespaces or other predefined characters from both sides of a string.

<?php
$input = "some text@";
echo $input . "<br>";
echo trim($input,"@");
// Output will be : some text
?>

What is the difference between var_dump() and print_r() ?

var_dump() will display all the information of a variable including keys values and types.
print_r() display the keys and values only in a human readable format.

What is the importance of “action” attribute in a html form?

The action attribute determines where to send the form-data in the form submission.

How do you define a constant in PHP?

Using define() directive, like define (“MYCONSTANT”,”100″)

What is the use of “ksort” in php?

It is used for sort an array by key in reverse order.

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

<?php
$anyvar="Hello World";
$message="anyvar";
echo $message;
echo '<br>';
echo $$message;
?>

output:
anyvar
Hello World

What is the use of the function htmlentities?

htmlentities Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

How to find the position of the first occurrence of a substring in a string?

strpos() is used to find the position of the first occurrence of a substring in a string
The strpos() function is case-sensitive.

<?php
$string ="I am a human";
$match= "human";
if(strpos($string, $match) !== false)
{
echo "Present";
}
else
{
echo "Not Present";
}
?>

How can we get IP address of a client in PHP?

$_SERVER["REMOTE_ADDR"]; 

Explain PHP explode() function.

The PHP explode() function breaks a string into an array.

<?php
$str = "Hi Guys today is my Birth day.";
print_r (explode(" ",$str));
?>

Explain PHP split() function.

The PHP split() function splits string into an array by regular expression.

<?php

$anystring= "ram.111.sam.222";
$splitarr= split ("\.", $anystring);

echo "$splitarr[0] <br />";
echo "$splitarr[1] <br />" ;
echo "$splitarr[2] <br />" ;
echo "$splitarr[3] <br />" ;

?>

Output:

ram
111
sam
222

NB- This function is deprecated in PHP 7.X, Now they are using below functions instead.

  • preg_split()
  • explode()
  • str_split()

How many types of array are there in PHP?

There are three types of array in PHP:
Indexed array
Associative array
Multidimensional array

What is the difference between indexed and associative array?

The indexed array holds elements in an indexed form which is represented by number starting from 0 and incremented by 1. For example:

$pet_name=array("dog","cat","parrot"); 

The associative array holds elements with name. For example:

$name=array("Kumar"=>"35","Rony"=>"45","Subhakalyan"=>"4"); 

How can we connect to a MySQL database from a PHP script?

To connect  MySQL database, we must use mysql_connect() function as follows:

<?php

$con_flag= mysql_connect("localhost", "your_user", "your_password");

mysql_select_db("your_db",$con); ?>

To connect  MySQLi database, we must use mysqli_connect() function as follows:

<?php
$con_flag= mysqli_connect("localhost","your_user","your_password","your_db");
if (mysqli_connect_errno())
{
echo "Connection fail: " . mysqli_connect_error();
}
?>

What is the function persistent connection use full for?

mysql_pconnect() ensure a persistent connection to the database, it makes connection do not close when the the PHP script ends.But In mysql_connect() each time we have to connect after the script ends.

How the result set of Mysql be handled in PHP?

These are below funcions are used for result set in mysql.
mysql_fetch_array();
mysql_fetch_assoc();
mysql_fetch_object();
mysql_fetch_row();