Loading image
Core PHP Interview Questions (2023)

Core PHP Interview Questions (2023)

  • showkat ali
  • 21st Nov, 2023
  • 232

 

PHP remains an excellent tool for creating interactive and dynamic websites in the fast-paced world of web development. Whether you're an experienced developer or new to PHP, this tutorial will provide you with useful insights and expertise to help you thrive in fundamental PHP programming. This material has been carefully chosen with SEO optimization in mind to ensure you receive the greatest results.

 

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 are PHP interview questions, which are very helpful for 1 year, 2 years, and 5 years of experience.

Quick Questions About PHP

Quick Questions and Answers

PHP is a Server-side scripting language

PHP is originally known as Personal home page

PHP is written in C programming language

PHP is the acronym for PHP: Hypertext Preprocessor

PHP file name extension are.php,.phar,.phtml, etc.

PHP is initially released on June 8, 1995

PHP is designed by Rasmus Lerdorf

PHP is licensed under Dual license GNU

PHP's top features are Easy to learn, server-side scripting, OOP-based, High performance, etc.

 

2) Where are sessions stored in PHP?

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

Also Read: Laravel Interview Questions

 

3) What are constructor and destructor in PHP ?

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;

    }

}

?>

 

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

 

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

?>

 

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

 

7) Is multiple inheritance supported in PHP ?

NO, multiple inheritance is not supported by PHP

 

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

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

?>

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

 

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

 

 

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

 

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

 

13) What is a composer in 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.

 

14) What is cURL in PHP ?

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

 

15) What is T_PAAMAYIM_NEKUDOTAYIM in PHP?

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

 

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

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

   }

?>  

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

}

?>

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





?>

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

 

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

 

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

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.



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

 }

}

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

?>

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

 

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

26) How is a constant defined in a PHP script?

Defining a Constant in PHP

define('CONSTANT_NAME',value); 

 

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

28) What are the encryption functions available in PHP ?

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

 

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

 

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

It handles the character encoding conversion between the possible encoding pairs.

Offers automatic encoding conversion between the possible encoding pairs.

Supports function overloading feature which enables to add multibyte awareness to regular string functions.

Provides multibyte specific string functions that properly detect the beginning or ending of a multibyte character. For example, mb_strlen() and mb_split()

 

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

 ?>

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

?>

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

 

 

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

 

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

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

 

  Get Post

History: Parameters remain in browser history because they are part of the URL Parameters 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-urlencoded multipart/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 64K Can send parameters, including uploading files, to the server.

Hacked: Easier to hack for script kiddies More 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 cached Not Cached

Large variable values: 7607 characters maximum size. 8 Mb max size for the POST method.

 

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

 

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

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

 

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

 

40) What is Mcrypt used for?

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.

 

41) 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/

 

42) 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) How to check curl is enabled or not in PHP

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

}

 

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

 

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

46) Explain Traits in PHP ?

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

}

?>

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

 

48) Which Scripting Engine PHP uses?

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.

 

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

 

50) What are differences between PECL and PEAR?

     

 

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

 

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

 

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

 

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

 

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

 

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

 

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

 

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

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"

 

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

 

60) What is list in PHP?

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”



?>

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

 

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

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

 

64) How can we convert the time zones using PHP?

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

 

Example

date_default_timezone_set('Asia/Karachi');

 

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

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 )

 

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

   

67) List few sensible functions in PHP?

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

 

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

 

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

 

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

 

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

 

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

 

 

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

 

74) How to create a public static method in PHP?

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

 

75) What is use of file_put_contents in PHP?

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)

Few Pros and Cons of PHP

Pros Cons

Simple to create web pages and it has the tools to create the main homepage in a well-designed manner Due to the low barrier of entry, it is not easy to explore a high stage of talent in PHP.

PHP is gigantic and is popular in the whole world thus it has a bunch of online training sites Best PHP application is less in financial status than that of the average Java application.

With the emerging of the mechanical and technical world, PHP programming has first-class debugging all over the world. It has no Internet of things community in it and it is due to the lack of asynchronous I/O framework.

It has automation tools that evaluate the PHP application. As compared to PHP application it creates complexity when a program is developed in the PHP framework.

It has a large open-source software community with around 70,000 of open source libraries available. It being a partial case sensitive creates confusion in programmer.

The latest version of functional and object-oriented programming is present in the updated version of the PHP platform. PHP hiring a person is quite hard as they have less market value due to their drawbacks.

It is partially case sensitive which makes the programmer easy to develop a program. It is not given priority by Microsoft/Windows i.e the OS companies.

Being PHP an open-source programming language and serving the web for more than 20 years, below points let you know why PHP shines

  • Open Source
  • Cross-Platform Compatibility
  • Loosely Typed Programming Language
  • PHP Traits
  • Magic Method
  • Supports nowdocs and heredocs String
  • Easy to Learn
  • Plenty of jobs
  • Real-Time Tracking and Error Reporting

showkat ali

Greetings, I'm a passionate full-stack developer and entrepreneur based in Pakistan. I specialize in PHP, Laravel, React.js, Node.js, JavaScript, and Python. I own interviewsolutionshub.com, where I share tech tutorials, tips, and interview questions. I'm a firm believer in hard work and consistency. Welcome to interviewsolutionshub.com, your source for tech insights and career guidance

Advertisements