PHP Interview Questions for Beginners

PHP Interview Questions

What is PHP?

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.

Below PHP interview questions, which are very helpful for 1 year, 2 years, 5 years experience PHP developers.

Quick Questions About PHP

Answers
is aServer-side scripting language
is originally known asPersonal home page
is written inC programming language
PHP is the acronym forPHP: Hypertext Preprocessor
PHP file name extension is.php, .phar, .phtml, etc.
PHP is initially released on08 June 1995
PHP is designed byRasmus Lerdorf
PHP is licensed underDual license GNU
PHP top features areEasy to learn, Server side scripting, OOPs-based, High performance, etc.

Key Responsibilities of PHP Developer

As a PHP developer, some of your key responsibilities may include:

  • Writing clean, efficient, and maintainable code.
  • Developing and maintaining web-based applications using PHP and related technologies.
  • Collaborating with cross-functional teams to develop and launch new features.
  • Troubleshooting and debugging issues as they arise.
  • Maintaining and updating existing PHP applications.
  • Ensuring the security and performance of the applications you develop.
  • Staying up-to-date with the latest developments in the PHP ecosystem and implementing new technologies as needed.
  • Participating in code reviews and providing feedback to other team members.
  • Contributing to the development of technical specifications and documentation.
  • Mentoring and supporting junior developers on the team.
Download PHP Interview Questions PDF

Below are the list of Best PHP Interview Questions and Answers

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.

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

PHP constructor and destructor are special type functions that are automatically called when a PHP class object is created and destroyed.

Generally, Constructor is used to initializing the private variables for class and Destructors to free the resources created /used by the class.

Here is a sample class with a constructor and destructor 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 supports 9 primitive types

4 scalar types:

  • integer
  • boolean
  • float
  • string

3 compound types:

  • array
  • object
  • callable

And 2 special types:

  • resource
  • NULL

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

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

NO, multiple inheritance is not supported by PHP

The default session time in PHP is 1440 seconds (24 minutes) and the Default session storage path is temporary folder/tmp on the 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); ?>

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 ;

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

Take Free: Php MCQ & Quiz

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

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

It is an application-level package manager for PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.

cURL is a library in PHP that allows you to make HTTP requests from the server.

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

In PHP == is an 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"; } ?>

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

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

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.

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.

In PHP both functions are used to find the first occurrence of a 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.

//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'];
	}
}

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

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

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

Defining a Constant in PHP

define('CONSTANT_NAME',value); 

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;

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

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

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

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

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

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.

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.

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

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.

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.

get_browser() function is used to retrieve the client browser details in PHP. This is a library function is PHP which looks up the browscap.ini file of the user and returns the capabilities of its browser.

Syntax:

get_browser(user_agent,return_array)

Example Usage:

$browserInfo = get_browser(null, true);
print_r($browserInfo);

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

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

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

$stderr = STDERR;

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

MCrypt is a file encryption function and that is delivered as Perl extension. It is the replacement of the old crypt() package and crypt(1) command of Unix. It allows developers to encrypt files or data streams without making severe changes to their code.

MCrypt is was deprecated in PHP 7.1 and completely removed in PHP 7.2.

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/

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

use function_exists('curl_version') function to check curl is enabled or not. This function returns true if curl is enabled other false

Example :

if(function_exists('curl_version') ){
  echo "Curl is enabled";
}else{

echo "Curl is not enabled";

}

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.

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

Traits in PHP are similar to Abstract classes that are not be instantiated on its own. Traits allow us to declare methods that are used by multiple classes in PHP. trait keyword is used to create Traits in PHP and can have concrete and abstract methods.

Syntax

<?php
trait TraitName {
  // some code...
}
?>

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.

PHP uses Zend Engine. The current stable version of Zend Engine is 4.0. It is developed by Andi Gutmans and Zeev Suraski at Technion – Israel Institute of Technology.

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

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.

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.

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.

  • 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

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.

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

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.

Static Members of a Class can be accessed directly using a class name with a scope resolution operator. To access Static members we don't need to create an object of Class.

Example

class Hello {
    public static $greeting = 'Greeting from Hello Class';
}

echo Hello::$greeting; // outputs "Greeting from Hello Class"

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

The list is similar to an array but it is not a function, instead, it is a language construct. This is used for the 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”

?>

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.

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 )

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.

date_default_timezone_set() funtion is used to convert/change the time zones in PHP.

Example

date_default_timezone_set('Asia/Kolkata');

getimagesize() function is used to get the size of an image in PHP. This function takes the path of file with name as an argument and returns the dimensions of an image with the file type and height/width. Syntax:

array getimagesize( $filename, $image_info )

exec, passthru, system, proc_open, eval(),assert(),phpinfo,posix_mkfifo, posix_getlogin, posix_ttyname are few sensible or exploitable functions in PHP.

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.

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.

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

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.

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.

 

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.

Static method is a member of class that is called directly by class name without creating an instance.In PHP uou can create a static method by using static keyword.

Example:

class A {
    public static function sayHello() {
        echo 'hello Static';
    }
}

A::sayHello();

Overriding and Overloading both are oops concepts.

In Overriding, a method of the parent class is defined in the child or derived class with the same name and parameters. Overriding comes in inheritance.

An example of Overriding in PHP.

<?php

class A {
   function showName() {
      return "Ajay";
   }
}

class B extends A {
   function showName() {
      return "Anil";
   }
}

$foo = new A;
$bar = new B;
echo($foo->myFoo()); //"Ajay"
echo($bar->myFoo()); //"Anil"
?>

In Overloading, there are multiple methods with the same name with different signatures or parameters. Overloading is done within the same class. Overloading is also called early binding or compile time polymorphism or static binding.

An example of Overloading in PHP

<?php 
class A{

function sum($a,$b){
	return $a+$b;

}

function sum($a,$b,$c){
	return $a+$b+$c;

}

}

$obj= new A;
$obj->sum(1,3); // 4
$obj->sum(1,3,5); // 9
?>

You can use library function array_unique() for removing duplicated values for an array. Here is syntax to use it.

<?php
	$a=array("a"=>"home","b"=>"town","c"=>"town","php");
	print_r(array_unique($a));
?>


Both strstr() as well as stristr() in PHP are used for the purpose of finding the first occurrence of the string. The only difference between the two is while strstr() is case sensitive but on the other hand, stristr() is case insensitive.

In PHP5 or above, type hinting is a process used to specify the data type of a given argument. This is mainly used in a function declaration. Whenever the function is called, PHP checks if the arguments are of the type preferred by the user or not. If the argument is not of the specified type, the run time will display an error and the program will not execute.

file_get_contents in PHP is a library function that is used to write text to a file. This function creates a new file if the file doesn't exist.

Syntax

file_put_contents($file, $data, $mode, $context)