Core PHP Interview Questions

PHP is a recursive acronym for PHP Hypertext Preprocessor. It is a widely used open-source programming language especially suited for creating dynamic websites and mobile API's

Read Top PHP interview questions and answers

Below are the few Latest Php Programming Interview questions.

#1 Question

What is PHP ?

PHP: Hypertext Preprocessor is open source server-side scripting language that is widely used for creation of dynamic web applications.It was developed by Rasmus Lerdorf also know as Father of PHP in 1994.

PHP is a loosely typed language , we didn’t have to tell PHP which kind of Datatype a Variable is. PHP automatically converts the variable to the correct datatype , depending on its value.

#2 Question

What is T_PAAMAYIM_NEKUDOTAYIM ?

T_PAAMAYIM_NEKUDOTAYIM is scope resolution operator used as :: (double colon) .Basically, it used to call static methods/variables of a Class.

Example usage:-

	
 $Cache::getConfig($key);

#3 Question

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.

Example Usages:

<?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";
   }
?>  

#4 Question

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

#5 Question

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.

Example usage:

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

Also Read Laravel interview questions

#6 Question

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”.

#7 Question

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);
?>

#8 Question

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

#9 Question

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”);

#10 Question

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 .

Here is sample class with constructor and destructer in PHP.

<?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;
    }
}
?>

#11 Question

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

Read Zend Framework interview questions

#12 Question

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();
}
?>

#13 Question

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.

#14 Question

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

#15 Question

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.

#16 Question

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
?>

#17 Question

Code to upload a file in PHP ?

//PHP code to process uploaded file and moving it on server

if($_FILES['photo']['name'])
{
	//if no errors...
	if(!$_FILES['file']['error'])
	{
		//now is the time to modify the future file name and validate the file
		$new_file_name = strtolower($_FILES['file']['tmp_name']); //rename file
		if($_FILES['file']['size'] > (1024000)) //can't be larger than 1 MB
		{
			$valid_file = false;
			$message = 'Oops!  Your file\'s size is to large.';
		}
		
		//if the file has passed the test
		if($valid_file)
		{
			//move it to where we want it to be
			move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$new_file_name);
			$message = 'File uploaded successfully.';
		}
	}
	//if there is an error...
	else
	{
		//set that to be the returned message
		$message = 'Something got wrong while uploading file:  '.$_FILES['file']['error'];
	}
}

#18 Question

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);
?>

#19 Question

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');

#20 Question

Is multiple inheritance supported in PHP ?

NO, multiple inheritance is not supported by PHP

#21 Question

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

Code to post JSON Data in a URL using CURL in PHP

$url='https://www.onlineinterviewquestions.com/get_details';
$jsonData='{"name":"phpScots",
"email":"phpscots@onlineinterviewquestions.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);

#22 Question

How is a constant defined in a PHP script?

Defining a Constant in PHP

define('CONSTANT_NAME',value); 

#23 Question

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;

#24 Question

What are the encryption functions available in PHP ?

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

#25 Question

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

#26 Question

What is the use of Mbstring?

Mbstring

Mbstring is an extension used in PHP to handle non-ASCII strings. Mbstring provides multibyte specific string functions that help us to deal with multibyte encodings in PHP. Multibyte character encoding schemes are used to express more than 256 characters in the regular byte-wise coding system. Mbstring is designed to handle Unicode-based encodings such as UTF-8 and UCS-2 and many single-byte encodings for convenience PHP Character Encoding Requirements.

You may also Like Codeigniter interview questions

Below are some features of mbstring

  1. It handles the character encoding conversion between the possible encoding pairs.
  2. Offers automatic encoding conversion between the possible encoding pairs.
  3. Supports function overloading feature which enables to add multibyte awareness to regular string functions.
  4. Provides multibyte specific string functions that properly detect the beginning or ending of a multibyte character. For example, mb_strlen() and mb_split()

#27 Question

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;
?>

#28 Question

How will you calculate days between two dates in PHP?

Calculating 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;
?>

#29 Question

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.

#30 Question

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.

#31 Question

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 ;

#32 Question

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

#33 Question

What are the differences between GET and POST methods in form submitting, give the case where we can use get and we can use post methods?

In PHP, one can specify two different submission methods for a form. The method is specified inside a FORM element, using the METHOD attribute. The difference between METHOD=”GET” (the default) and METHOD=”POST” is primarily defined in terms of form data encoding. According to the technical HTML specifications, GET means that form data is to be encoded (by a browser) into a URL while POST means that the form data is to appear within the message body of the HTTP request.

 GetPost
History:Parameters remain in browser history because they are part of the URLParameters are not saved in browser history.
Bookmarked:Can be bookmarked.Can not be bookmarked.
BACK button/re-submit behavior:GET requests are re-executed but may not be re-submitted to the server if the HTML is stored in the browser cache.The browser usually alerts the user that data will need to be re-submitted.
Encoding type (enctype attribute):application/x-www-form-urlencodedmultipart/form-data or application/x-www-form-urlencoded Use multipart encoding for binary data.
Parameters:can send but the parameter data is limited to what we can stuff into the request line (URL). Safest to use less than 2K of parameters, some servers handle up to 64KCan send parameters, including uploading files, to the server.
Hacked:Easier to hack for script kiddiesMore difficult to hack
Restrictions on form data type:Yes, only ASCII characters allowed.No restrictions. Binary data is also allowed.
Security:GET is less secure compared to POST because data sent is part of the URL. So it’s saved in browser history and server logs in plaintext.POST is a little safer than GET because the parameters are not stored in browser history or in web server logs.
Restrictions on form data length:Yes, since form data is in the URL and URL length is restricted. A safe URL length limit is often 2048 characters but varies by browser and web server.No restrictions
Usability:GET method should not be used when sending passwords or other sensitive information.POST method used when sending passwords or other sensitive information.
Visibility:GET method is visible to everyone (it will be displayed in the browsers address bar) and has limits on the amount of information to send.POST method variables are not displayed in the URL.
Cached:Can be cachedNot Cached
Large variable values:7607 characters maximum size.8 Mb max size for the POST method.

#34 Question

Why should I store logs in a database rather than a file?

A database provides more flexibility and reliability than does logging to a file. It is easy to run queries on databases and generate statistics than it is for flat files. Writing to a file has more overhead and will cause your code to block or fail in the event that a file is unavailable. Inconsistencies caused by slow replication in AFS may also pose a problem to errors logged to files. If you have access to MySQL, use a database for logs, and when the database is unreachable, have your script automatically send an e-mail to the site administrator.

#35 Question

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

#36 Question

How can you get web browser’s details using PHP?

  

#37 Question

How to access standard error stream in PHP?

You can access standard error stream in PHP by using following code snippet:

$stderr = fwrite("php://stderr");

$stderr = fopen("php://stderr", "w");

$stderr = STDERR;

#38 Question

Advantages and Application Areas of PHP

PHP (Hypertext Preprocessor) is an open source, a server-side scripting language that is used for the web applications development.

The web pages can be designed using HTML and the execution of the code is done on the user’s browser.

And, with PHP server-side scripting language, the code is executed on the server before being executed on the web browser of the user.

PHP programming language is considered as a friendly language with abilities to easily connect with Oracle, MySQL, and many other databases.

Uses and Application Areas of PHP

PHP scripts are used on popular operating systems like Linux, UNIX, Solaris, Windows, MAC OS, Microsoft and on many other operating systems. It supports many web servers that include Apache and IIS.
The use of PHP affords web developers the freedom to choose the operating system and the web server.
The following main areas of web development use the PHP programming language.

  • Command line scripting In this area of web development, with just the use of PHP parser, the PHP script is executed with no requirement of any server program or browser. This type of use of the PHP script is normally employed for simple and easy processing tasks.
  • Server-side scripting Server-side scripting is the main area of operation of PHP scripts in PHP. The following are involved in Server-side scripting:
    • Web server – It is a program that executes the files from web pages, from user requests.
    • Web browser – It is an application that is used to display the content on WWW (World Wide Web).
    • PHP parser – It is a program that converts the human-readable code into a format that is easier to understand by the computer.
  • Desktop Application Development PHP is also used to create the client-side application such as desktop applications. They are usually characterized by the GUI (Graphic User Interface). The client-side applications can be developed with knowledge of using the advanced features like PHP-GTK.

Advantages of PHP

Now, let's have a quick look at why PHP is used; that is the advantages of PHP.

  • Open Source 
    PHP is an open source software, which means that it is freely available for modifications and redistribution, unlike any other programming language. There is also an active team of PHP developers who are ready to provide any kind of technical support when needed.
  • Cross Platform
    The PHP programming language is easy to use and modify and is also highly compatible with the leading operating systems as well as the web browsers. And, that made the deployment of the applications across a wide range of operating systems and browsers much easier than before.
    PHP not only supports the platforms like Linux, Windows, Mac OS, Solaris but is also applied to web servers like Apache, IIS and many others.
  • Suits Web Development
    PHP programming language perfectly suits the web development and can be directly embedded into the HTML code.

Also Read: PHP Interview Questions

#39 Question

What is Mcrypt used for?

#40 Question

What is PECL?

PECL is an online directory or repository for all known PHP extensions. It also provides hosting facilities for downloading and development of PHP extensions.

You can read More about PECL from https://pecl.php.net/

#41 Question

What is a composer in PHP?

#42 Question

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); ?>

#43 Question

What is cURL in PHP ?

#44 Question

How to check curl is enabled or not in PHP

#45 Question

What is Pear in PHP?

PEAR stand for Php Extension and Application Repository.PEAR provides:

  • A structured library of code
  • maintain a system for distributing code and for managing code packages
  • promote a standard coding style
  • provide reusable components.

#46 Question

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;
}

#47 Question

Explain Traits in PHP ?

#48 Question

What is the difference between runtime exception and compile time exception?

An exception that occurs at compile time is called a checked exception. This exception cannot be ignored and must be handled carefully. For example, in Java if you use FileReader class to read data from the file and the file specified in class constructor does not exist, then a FileNotFoundException occurs and you will have to manage that exception. For the purpose, you will have to write the code in a try-catch block and handle the exception. On the other hand, an exception that occurs at runtime is called unchecked-exception Note: Checked exception is not handled so it becomes an unchecked exception. This exception occurs at the time of execution.

#49 Question

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.

#50 Question

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.

#51 Question

What are differences between PECL and PEAR?

#52 Question

Explain preg_Match and preg_replace?

These are the commonly used regular expressions in PHP. These are an inbuilt function that is used to work with other regular functions.

preg-Match: This is the function used to match a pattern in a defined string. If the patterns match with string, it returns true otherwise it returns false.

Preg_replace: This function is used to perform a replace operation. In this, it first matches the pattern in the string and if pattern matched, ten replace that match with the specified pattern.

#53 Question

What is php.ini & .htacess file?

Both are used to make the changes to your PHP setting. These are explained below:

php.ini: It is a special file in PHP where you make changes to your PHP settings. It works when you run PHP as CGI. It depends on you whether you want to use the default settings or changes the setting by editing a php.ini file or, making a new text file and save it as php.ini.

.htaccess: It is a special file that you can use to manage/change the behavior of your site. It works when PHP is installed as an Apache module. These changes include such as redirecting your domain’s page to https or www, directing all users to one page, etc.

#54 Question

How to block direct directory access in PHP?

You can use a .htaccess file to block the direct access of directory in PHP. It would be best if you add all the files in one directory, to which you want to deny access.

For Apache, you can use this code:

<&lt  Order deny, allow  Deny from all</&lt

But first, you have to create a .htaccess file, if it is not present. Create the .htaccess file in the root of your server and then apply the above rule.

#55 Question

What is difference between ksort() and usort() functions.

  • ksort() function is used to sort an array according to its key values whereas asort() function is used to sort an array according to its values.
  • They both used to sort an associative array in PHP.

Example of asort():

<?php
$age = array("Peter"=>"37", "Ben"=>"27", "Joe"=>"43");
asort($age);
?>

Output: Key=Ben, Value=37 Key=Joe, Value=43 Key=Peter, Value=35

Example of ksort():

<?php
$age = array("Peter"=>"37", "Ben"=>"27", "Joe"=>"43");
ksort($age);
?>

Output: Key=Ben, Value=37

Key=Joe, Value=43
Key=Peter, Value=35

#56 Question

How can i execute PHP File using Command Line?

It is easy and simple to execute PHP scripts from the windows command prompt. You just follow the below steps:

1. Open the command prompt. Click on Start button->Command Prompt.

2. In the Command Prompt, write the full path to the PHP executable(php.exe) which is followed by the full path of a script that you want to execute. You must add space in between each component. It means to navigate the command to your script location.

For example,

let you have placed PHP in C:\PHP, and your script is in C:\PHP\sample-php-script.php,

then your command line will be:

C:\PHP\php.exe C:\PHP\sample-php-script.php

3. Press the enter key and your script will execute.

#57 Question

Write logic to print Floyd's triangle in PHP?

Floyd’s triangle is the right-angled triangle which starts with 1 and filled its rows with a consecutive number. The count of elements in next row will increment by one and the first row contains only one element.

Example of Floyd's triangle having 4 rows

The logic to print Floyd's triangle

<?php

echo "print Floyd's triangle"; echo "<pre>
$key = 1; for ($i = 1; $i <= 4; $i++) { for ($j = 1; $j <= $i; $j++) { echo $key; $key++; if ($j == $i) { echo "<br/>"; } } } echo ""; ?>

Output:

1

2 3

4 5 6

7 8 9 10

#58 Question

What is difference Between PHP 5 and 7?

There are many differences between PHP 5 and 7. Some of the main points are:

  • Performance: it is obvious that later versions are always better than the previous versions if they are stable. So, if you execute code in both versions, you will find the performance of PHP 7 is better than PHP5. This is because PHP 5 use Zend II and PHP & uses the latest model PHP-NG or Next Generation.
  • Return Type: In PHP 5, the programmer is not allowed to define the type of return value of a function which is the major drawback. But in PHP 7, this limitation is overcome and a programmer is allowed to define the return type of any function.
  • Error handling: In PHP 5, there is high difficulty to manage fatal errors but in PHP 7, some major errors are replaced by exceptions which can be managed effortlessly. In PHP 7, the new engine Exception Objects has been introduced.
  • 64-bit support: PHP 5 doesn’t support 64-bit integer while PHP 7 supports native 64-bit integers as well as large files.
  • Anonymous Class: Anonymous class is not present n PHP 5 but present in PHP 7. It is basically used when you need to execute the class only once to increase the execution time.
  • New Operators: Some new operators have added in PHP 7 such as <=> which is called a three-way comparison operator. Another operator has added is a null coalescing operator which symbol as?? and use to find whether something exists or not.
  • Group Use declaration: PHP 7 includes this feature whereas PHP 5 doesn’t have this feature.

#59 Question

How to access a Static Member of a Class in PHP?

#60 Question

What is difference between explode() or split() in PHP?

The explode() and split() functions are used in PHP to split the strings. Both are defined here:

Split() is used to split a string into an array using a regular expression whereas explode() is used to split the string by string using the delimiter.

Example of split():

split(":", "this:is:a:split"); //returns an array that contains this, is, a, split.

Output: Array ([0] => this,[1] => is,[2] => a,[3] => split)

Example of explode():

explode ("take", "take a explode example "); //returns an array which have value "a explode example"

Output: array([0] => "a explode example")

#61 Question

What is list in PHP?

List is similar to an array but it is not a function, instead it is a language construct. This is used for assignment of a list of variables in one operation. If you are using PHP 5 version, then the list values start from a rightmost parameter, and if you are using PHP 7 version, then your list starts with a left-most parameter. Code is like:

<?php
$info = array('red', 'sign', 'danger');
// Listing all the variables
list($color, $symbol, $fear) = $info;
echo "$color is $symbol of $fear”;?php>

#62 Question

What are access specifiers?

An access specifier is a code element that is used to determine which part of the program is allowed to access a particular variable or other information. Different programming languages have different syntax to declare access specifiers. There are three types of access specifiers in PHP which are:

  • Private: Members of a class are declared as private and they can be accessed only from that class.
  • Protected: The class members declared as protected can be accessed from that class or from the inherited class.
  • Public: The class members declared as public can be accessed from everywhere.

#63 Question

Difference between array_combine and array_merge?

array_combine is used to combine two or more arrays while array_merge is used to append one array at the end of another array.

array_combine is used to create a new array having keys of one array and values of another array that are combined with each other whereas array_merge is used to create a new array in such a way that values of the second array append at the end of the first array.

array_combine doesn't override the values of the first array but in array_merge values of the first array overrides with the values of the second one.

Example of array_combine

<?php
$arr1    = array("sub1","sub2","sub3");
$arr2    = array(("php","html","css");
$new_arr = array_combine($arr1, $arr2);
print_r($new_arr);
?>

OUTPUT:

 Array([sub1] => php [sub2] => html [sub3 =>css)

Example of array_merge

<?php
$arr1 = array("sub1" => "node", "sub2" => "sql");
$arr2 = array("s1"=>"jQuery", "s3"=>"xml", "sub4"=>"Css");
$result = array_merge($arr1, $arr2);
 print_r($result);
?>

OUTPUT:

 Array ([s1] => jquery [sub2] => sql [s3] => xml [sub4] =>Css )

#64 Question

What is MIME?

MIME stands for Multipurpose Internet Mail Extensions is an extension of the email protocol. It supports exchanging of various data files such as audio, video, application programs, and many others on the internet. It can also handle ASCII texts and Simple Mail Transport Protocol on the internet.

#65 Question

How can we convert the time zones using PHP?

#66 Question

How can you get the size of an image in PHP?

     

#67 Question

What is the difference between an interface and an abstract class?

#68 Question

List few sensible functions in PHP?

#69 Question

What is a path Traversal ?

Path Traversal also is known as Directory Traversal is referring to an attack which is attacked by an attacker to read into the files of the web application. Also, he/she can reveal the content of the file outside the root directory of a web server or any application. Path traversal operates the web application file with the use of dot-dot-slash (../) sequences, as ../ is a cross-platform symbol to go up in the directory.

Path traversal basically implements by an attacker when he/she wants to gain secret passwords, access token or other information stored in the files. Path traversal attack allows the attacker to exploit vulnerabilities present in web file.

#70 Question

What is the difference between nowdoc and heredoc?

Heredoc and nowdoc are the methods to define the string in PHP in different ways.

  • Heredoc process the $variable and special character while nowdoc doesn't do the same.
  • Heredoc string uses double quotes "" while nowdoc string uses single quote ''
  • Parsing is done in heredoc but not in nowdoc.

#71 Question

Explain mail function in PHP with syntax?

The mail function is used in PHP to send emails directly from script or website. It takes five parameters as an argument.

Syntax of mail (): mail (to, subject, message, headers, parameters);

  • to refers to the receiver of the email
  • Subject refers to the subject of an email
  • the message defines the content to be sent where each line separated with /n and also one line can't exceed 70 characters.
  • Headers refer to additional information like from, Cc, Bcc. These are optional.
  • Parameters refer to an additional parameter to the send mail program. It is also optional

#72 Question

What is difference between md5 and SHA256?

Both MD5 and SHA256 are used as hashing algorithms. They take an input file and generate an output which can be of 256/128-bit size. This output represents a checksum or hash value. As, collisions are very rare between hash values, so no encryption takes place.

  • The difference between MD5 and SHA256 is that the former takes less time to calculate than later one.
  • SHA256 is difficult to handle than MD5 because of its size.
  • SHA256 is less secure than MD5
  • MD5 result in an output of 128 bits whereas SHA256 result output of 256 bits.

Concluding all points, it will be better to use MDA5 if you want to secure your files otherwise you can use SHA256.

#73 Question

How to terminate the execution of a script in PHP ?

To terminate the script in PHP, exit() function is used. It is an inbuilt function which outputs a message and then terminates the current script. The message which is you want to display is passed as a parameter to the exit () function and this function terminates the script after displaying the message. It is an alias function of die () function. It doesn’t return any value.

Syntax: exit(message)

Where massage is a parameter to be passed as an argument. It defines message or status.

Exceptions of exit():

  • If no status is passed to exit(), then it can be called without parenthesis.
  • If a passed status is an integer then the value will not be printed but used as the exit status.
  • The range of exit status is from 0 to 254 where 255 is reserved in PHP.

Errors And Exceptions

  • exit() can be called without parentheses if no status is passed to it. Exit() function is also known by the term language construct.
  • If the status passed to an exit() is an integer as a parameter, that value will be used as the exit status and not be displayed.
  • The range of exit status should be in between 0 to 25. the exit status 255 should not be used because it is reserved by PHP.

 

#74 Question

What should be the length of variable for SHA256?

It is clear from the name SHA256 that the length is of 256 bits long. If you are using hexadecimal representation, then you require 64 digits to replace 256 bits, as one digit represents four bits. Or if you are using a binary representation which means one byte equals to eight bits, then you need 32 digits.

#75 Question

How to create a public static method in PHP?

#76 Question

What is difference between Method overriding and overloading?

#77 Question

How to remove duplicate values from a PHP Array?

#78 Question

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

  

#79 Question

What is Type hinting in PHP ?

Latest Posts.

PHP Tutorials
PHP as a career. Is Right Fit?

With the modernization of the world, everyone is trying to seek knowledge in the field of digital ma...

PHP Tutorials
Codeigniter and Angularjs Crud

Finding difficulty in creating a CRUD in Codeigniter? CRUD is an abbreviation for Create, Read, Upda...

PHP Tutorials
How to Face PHP Interview - Tips and Advice

PHP stands for Hypertext Preprocessor. It is an HTML embedded scripting language, which is also some...

Ask a Question