Interview question of php

php interview question

Which is the latest version of PHP

Which is the latest version of PHP+

The latest version of PHP is 7.1.0 released at December 1, 2016 .


Define PHP

Define PHP+

PHP is an open source server side scripting language used to develop dynamic websites . PHP stands for Hypertext Preprocessor , also stood for Personal Home Page . Now the implementations of PHP is produced by The PHP group .It was created by Rasmus lerdorf in 1995 . It is a free software released under the PHP license .


what is difference between die and exist.

what is difference between die and exist.+

Die() first terminate the script and then print message. Exit() first print message and then terminate the script. if you comment to die() statement then exit also print


How can we get the IP address of the client?

How can we get the IP address of the client?+
$_SERVER["REMOTE_ADDR"];

What is the output?+
<?php

$a = '1';
$b = &$a;
echo $b; // output : 1
echo "<br/>";
$b = "2$b";
echo $b; // output : 21
echo "<br/>";
echo $a; // output : 21
echo "<br/>";
echo $a.", ".$b; //output : 21, 21
?>

How can you enable error reporting in PHP?

How can you enable error reporting in PHP? +
Check if ?display_errors? is equal ?on? in the php.ini or declare ?ini_set('display_errors', 1)? in your script.
Then, include ?error_reporting(E_ALL)? in your code to display all types of error messages during the script execution.

How we can get the number of elements in an array?

How we can get the number of elements in an array? +
The count() function is used to return the number of elements in an array.

What is the function file_get_contents() useful for?

What is the function file_get_contents() useful for? +
file_get_contents() lets reading a file and storing it in a string variable.

How can we display the output directly to the browser?

How can we display the output directly to the browser? +
display the output directly to the browser, we have to use the special tags <?= and ?>.

The value of the variable input is a string 1,2,3,4,5,6,7. How would you get the sum of the integers contained inside input?

The value of the variable input is a string 1,2,3,4,5,6,7. How would you get the sum of the integers contained inside input? +
<?php

$input = "1,2,3,4,5";
echo array_sum(explode(',',$input));

?>
output :- 15

What does the following code output?

What does the following code output? $i = 016; echo $i / 2; +
The Output should be 7. The leading zero indicates an octal number in PHP, so the number evaluates to the decimal number 14 instead to decimal 16.

Why use $_SERVER['PHP_SELF'] instead of " "

Why use $_SERVER['PHP_SELF'] instead of " " +
The action attribute will default to the current URL. It is the most reliable and easiest way to say "submit the form to the same place it came from".
There is no reason to use $_SERVER['PHP_SELF'], and # doesn't submit the form at all.
in the action attribute of the form. Since echo $_SERVER['PHP_SELF'] does not pass variables for using GET and you have to use "".
<form action="<?php echo $_SERVER['PHP_SELF']; ?>">
or

<form action="#" ...>
or

<form action="" ...>

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

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

In PHP == is equal operator and returns TRUE if $a is equal to $b after type juggling and === is Identical operator and return TRUE if $a is equal to $b, and they are of the same data type.

<?php
$a=true ;
$b=1;
// Below condition returns true and prints a and b are equal
if($a==$b){
echo "a and b are equal";
}else{
echo "a and b are not equal";
}
//Below condition returns false and prints a and b are not equal because $a and $b are of different data types.
if($a===$b){
echo "a and b are equal";
}else{
echo "a and b are not equal";
}
?>


What is session in PHP. How to remove data from a session?

What is session in PHP. How to remove data from a session? +

As HTTP is a stateless protocol. To maintain states on the server and share data across multiple pages PHP session are used. PHP sessions are the simple way to store data for individual users/client against a unique session ID. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data, if session id is not present on server PHP creates a new session, and generate a new session ID.

Example Usage:-

<?php

// starting a session

session_start();

// Creating a session

$_SESSION['user_info'] = ['user_id' =>1,
'first_name' =>
'Ramesh', 'last_name' =>
'Kumar', 'status' =>
'active'];

// checking session

if (isset($_SESSION['user_info']))
{
echo "logged In";
}

// un setting remove a value from session

unset($_SESSION['user_info']['first_name']);

// destroying complete session

session_destroy();


?>


How to register a variable in PHP session ?

How to register a variable in PHP session ? +

In PHP 5.3 or below we can register a variable session_register() function.It is deprecated now and we can set directly a value in $_SESSION Global.

<?php
// Starting session
session_start();
// Use of session_register() is deprecated
$username = "PhpScots";
session_register("username");
// Use of $_SESSION is preferred
$_SESSION["username"] = "PhpScots";
?>


Where sessions stored in PHP ?

Where sessions stored in PHP ? +

PHP sessions are stored on server generally in text files in a temp directory of server. That file is not accessible from outside word. When we create a session PHP create a unique session id that is shared by client by creating cookie on clients browser.That session id is sent by client browser to server each time when a request is made and session is identified. The default session name is ?PHPSESSID?.


What is default session time and path in PHP. How to change it ?

What is default session time and path in PHP. How to change it ? +

Default session time in PHP is 1440 seconds (24 minutes) and Default session storage path is temporary folder/tmp on server.

You can change default session time by using below code

<?php
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);

// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);
?>


What are PHP Magic Methods/Functions. List them

What are PHP Magic Methods/Functions. List them +

In PHP all functions starting with __ names are magical functions/methods. Magical methods 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() .


What is difference between include,require,include_once and require_once() ?

What is difference between include,require,include_once and require_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.

Syntax:- include(?file_name.php?);

Include Once:-Include once include a file only one time in php script.Second attempt to include is ignored.

Syntax:- include_once(?file_name.php?);

Require:-Require is also used to include files more than once in single PHP script.Require generates a Fatal error and halts the script execution,if file is not found on specified location or path.You can require a file as many time you want in a single script.

Syntax:- require(?file_name.php?);

Require Once :-Require once include a file only one time in php script.Second attempt to include is ignored. Require Once also generates a Fatal error and halts the script execution ,if file is not found on specified location or path.

Syntax:- require_once(?file_name.php?);


What are constructor and destructor in PHP ?

What are constructor and destructor in PHP ? +

PHP constructor and a destructor are special type functions which are automatically called when a PHP class object is created and destroyed. Generally Constructor are used to intializes the private variables for class and Destructors to free the resources created /used by class .

<?php
class Foo {

private $name;
private $link;

public function __construct($name) {
$this->name = $name;
}

public function setLink(Foo $link){
$this->link = $link;
}

public function __destruct() {
echo 'Destroying: ', $this->name, PHP_EOL;
}
}
?>


List data types in PHP ?

List data types in PHP ? +

PHP supports 9 primitive types

4 scalar types:

integer
boolean
float
string
3 compound types:

array
object
callable
And 2 special types:

resource
NULL


Explain Type hinting in PHP ?

Explain Type hinting in PHP ? +

In PHP Type hinting is used to specify the excepted data type of functions argument.
Type hinting is introduced in PHP 5.

Example usage:-

//send Email function argument $email Type hinted of Email Class. It means to call this function you must have to pass an email object otherwise an error is generated.

<?php
function sendEmail (Email $email)
{
$email->send();
}
?>


How to increase the execution time of a PHP script ?

How to increase the execution time of a PHP script ? +

The default max execution time for PHP scripts is set to 30 seconds. If a php script runs longer than 30 seconds then PHP stops the script and reports an error.
You can increase the execution time by changing max_execution_time directive in your php.ini file or calling ini_set(?max_execution_time?, 300); //300 seconds = 5 minutes function at the top of your php script.


What is purpose of @ in Php ?

What is purpose of @ in Php ? +

In PHP @ is used to suppress error messages.When we add @ before any statement in php then if any runtime error will occur on that line, then the error handled by PHP


What are different types of errors available in Php ?

What are different types of errors available in Php ? +

There are 13 types of errors in PHP, We have listed all below

E_ERROR: A fatal error that causes script termination.
E_WARNING: Run-time warning that does not cause script termination.
E_PARSE: Compile time parse error.
E_NOTICE: Run time notice caused due to error in code.
E_CORE_ERROR: Fatal errors that occur during PHP initial startup.
(installation)
E_CORE_WARNING: Warnings that occur during PHP initial startup.
E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
E_USER_ERROR: User-generated error message.
E_USER_WARNING: User-generated warning message.
E_USER_NOTICE: User-generated notice message.
E_STRICT: Run-time notices.
E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
E_ALL: Catches all errors and warnings.


What is difference between strstr() and stristr() ?

What is difference between strstr() and stristr() ? +

In PHP both functions are used to find the first occurrence of substring in a string except
stristr() is case-insensitive and strstr is case-sensitive,if no match is found then FALSE will be returned.

Sample Usage:

<?php
$email = ?abc@xyz.com?;
$hostname = strstr($email, ?@?);
echo $hostname;
output: @xyz.com
stristr() does the same thing in Case-insensitive manner
?>


How to get length of an array in PHP ?

How to get length of an array in PHP ? +

PHP count function is used to get the length or numbers of elements in an array

<?php
// initializing an array in PHP
$array=['a','b','c'];
// Outputs 3
echo count($array);
?>


Code to open file download dialog in PHP ?

Code to open file download dialog in PHP ? +

You can open a file download dialog in PHP by setting Content-Disposition in the header.

Here is a usage sample:-

// outputting a PDF file
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');


How is a constant defined in a PHP script?

How is a constant defined in a PHP script? +

Defining a Constant in PHP
define('CONSTANT_NAME',value);


How to get no of arguments passed to a PHP Function?

How to get no of arguments passed to a PHP Function? +

func_get_args() function is used to get number of arguments passed in a PHP function.

Sample Usage:

function foo() {
return func_get_args();
}
echo foo(1,5,7,3);//output 4;
echo foo(a,b);//output 2;
echo foo();//output 0;


What are the encryption functions available in PHP ?

What are the encryption functions available in PHP ? +

crypt(),Mcrypt(),hash() are used for encryption in PHP


What is the difference between unset and unlink ?

What is the difference between unset and unlink ? +

Unlink: Is used to remove a file from server.
usage:unlink(?path to file?);

Unset: Is used unset a variable.
usage: unset($var);


How to get number of days between two given dates using PHP ?

How to get number of days between two given dates using PHP ? +

<?php
$tomorrow = mktime(0, 0, 0, date(?m?) , date(?d?)+1, date(?Y?));
$lastmonth = mktime(0, 0, 0, date(?m?)-1, date(?d?), date(?Y?));
echo ($tomorrow-$lastmonth)/86400;
?>


How will you calculate days between two dates in PHP?

How will you calculate days between two dates in PHP? +

<?Php
$date1 = date('Y-m-d');
$date2 = '2015-10-2';
$days = (strtotime($date1)-strtotime($date2))/(60*60*24);
echo $days;
?>


What is Cross-site scripting?

What is Cross-site scripting? +

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.


What are the difference between echo and print?

What are the difference between echo and print? +

Difference between echo and print in PHP

echo in PHP
echo is language constructs that display strings.
echo has a void return type.
echo can take multiple parameters separated by comma.
echo is slightly faster than print.
Print in PHP
print is language constructs that display strings.
print has a return value of 1 so it can be used in expressions.
print cannot take multiple parameters.
print is slower than echo.


What is namespaces in PHP?

What is namespaces in PHP? +

PHP Namespaces provide a way of grouping related classes, interfaces, functions and constants.

# define namespace and class in namespace
namespace Modules\Admin\;
class CityController {
}
# include the class using namesapce
use Modules\Admin\CityController ;


What are different types of Print Functions available in PHP?

What are different types of Print Functions available in PHP? +

PHP is a server side scripting language for creating dynamic web pages. There are so many functions available for displaying output in PHP. Here, I will explain some basic functions for displaying output in PHP. The basic functions for displaying output in PHP are as follows:

print() Function
echo() Function
printf() Function
sprintf() Function
Var_dump() Function
print_r() Function


How to add 301 redirects in PHP?

How to add 301 redirects in PHP? +

You can add 301 redirect in PHP by adding below code snippet in your file.

header("HTTP/1.1 301 Moved Permanently");
header("Location: /option-a");
exit();


What is Gd PHP?

What is Gd PHP? +

GD is an open source library for creating dynamic images.

PHP uses GD library to create PNG, JPEG and GIF images.
It is also used for creating charts and graphics on the fly.
GD library requires an ANSI C compiler to run.
Sample code to generate an image in PHP

<?php
header("Content-type: image/png");

$string = $_GET['text'];
$im = imagecreatefrompng("images/button1.png");
$mongo = imagecolorallocate($im, 220, 210, 60);
$px = (imagesx($im) - 7.5 * strlen($string)) / 2;
imagestring($im, 3, $px, 9, $string, $mongo);
imagepng($im);

imagedestroy($im);
?>


How to get the IP address of the client/user in PHP?

How to get the IP address of the client/user in PHP? +

You can use $_SERVER['REMOTE_ADDR'] to get IP address of user/client in PHP, But sometime it may not return the true IP address of the client at all time. Use Below code to get true IP address of user.

function getTrueIpAddr(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}


Which Scripting Engine PHP uses?

Which Scripting Engine PHP uses? +

Zend Engine is used by PHP. The current stable version of Zend Engine is 3.0. It is developed by Andi Gutmans and Zeev Suraski at Technion ? Israel Institute of Technology.


What is difference between session and cookie in PHP ?

What is difference between session and cookie in PHP ? +

Session and cookie both are used to store values or data.
cookie stores data in your browser and a session is stored on the server.
Session destroys that when browser close and cookie delete when set time expires.


How be the result set of Mysql handled in PHP?

How be the result set of Mysql handled in PHP? +

The result set can be handled using mysqli_fetch_array, mysqli_fetch_assoc, mysqli_fetch_object or mysqli_fetch_row.


How is it possible to know the number of rows returned in the result set?

How is it possible to know the number of rows returned in the result set? +

The function mysqli_num_rows() returns the number of rows in a result set.


Which function gives us the number of affected entries by a query?

Which function gives us the number of affected entries by a query? +

mysqli_affected_rows() return the number of entries affected by an SQL query.


How can we check the value of a given variable is a number?

How can we check the value of a given variable is a number? +

is_numeric() to check whether it is a number or not.


How can we check the value of a given variable is alphanumeric?

How can we check the value of a given variable is alphanumeric? +

ctype_alnum to check whether it is an alphanumeric value or not.


How do I check if a given variable is empty?

How do I check if a given variable is empty? +

empty() function.


What does the unlink() function mean?

What does the unlink() function mean? +

It simply deletes the file given as entry.


What does the unset() function mean?

What does the unset() function mean? +

It will make a variable undefined.


How do I escape data before storing it in the database?

How do I escape data before storing it in the database? +

The addslashes function enables us to escape data before storage into the database.


Is it possible to remove the HTML tags from data?

Is it possible to remove the HTML tags from data? +

The strip_tags() function enables us to clean a string from the HTML tags.


How can you pass a variable by reference?

How can you pass a variable by reference? +

To be able to pass a variable by reference, we use an ampersand in front of it, as follows $var1 = &$var2


What is the function func_num_args() used for?

What is the function func_num_args() used for? +

The function func_num_args() is used to give the number of parameters passed into a function.


How can we change the maximum size of the files to be uploaded?

How can we change the maximum size of the files to be uploaded? +

We can change the maximum size of files to be uploaded by changing upload_max_filesize in php.ini.


Where sessions stored in PHP ?

Where sessions stored in PHP ? +

PHP sessions are stored on server generally in text files in a temp directory of server. That file is not accessible from outside word. When we create a session PHP create a unique session id that is shared by client by creating cookie on clients browser.That session id is sent by client browser to server each time when a request is made and session is identified. The default session name is ?PHPSESSID?.


What is default session time and path in PHP. How to change it ?

What is default session time and path in PHP. How to change it ? +

Default session time in PHP is 1440 seconds (24 minutes) and Default session storage path is temporary folder/tmp on server.

You can change default session time by using below code

<?php
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);

// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);
?>


Code to open file download dialog in PHP ?

Code to open file download dialog in PHP ? +

Here is a usage sample:-

// outputting a PDF file
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');


How to Pass JSON Data in a URL using CURL in PHP ?

How to Pass JSON Data in a URL using CURL in PHP ? +

$url='https://www.itechtuto.com/get_details';
$jsonData='{"name":"phpScots",
"email":"info@itechtuto.com"
,'age':36
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_close($ch);


What are the encryption functions available in PHP ?

What are the encryption functions available in PHP ? +

crypt(), Mcrypt(), hash() are used for encryption in PHP


+


+


+


+


+


+


+


+


+


+


+


+


+


+


Output :-






Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here