Fatskills
Practice. Master. Repeat.
Study Guide: All The Useful PHP Interview Questions & Answers - Part 2
Source: https://www.fatskills.com/php-programming/chapter/all-the-useful-php-interview-questions-answers-part-2

All The Useful PHP Interview Questions & Answers - Part 2

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~31 min read

Q. What do we mean by server?
A server is a computer program that provides a service to another computer programs (and its user). In the client/server programming model, a server program awaits and fulfills requests from client programs, which may be running in the same or other computers.

Q. What are PHP superglobals?
Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

The PHP superglobal variables are:

$GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_ENV $_COOKIE $_SESSION

Q. How will we get information sent via GET method?
The PHP provides $_GET associative array to access all the sent information using GET method.

Q. How will you get information sent via POST method?
The $_POST associative array to access all the sent information using POST method.

Q. What is the purpse $_REQUEST variable?
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.

Q. What is the purpose of $_FILES variable?
This is a global PHP variable. This variable is an associate double dimension array and keeps all the information related to uploaded file.

Q. What is the purpose of $GLOBALS variable in PHP?
It contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables.

Q. What is the purpose of $_SERVER variable in PHP?
$_SERVER − This is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these. See next section for a complete list of all the SERVER variables.

Q. What is the purpose of $_COOKIE variable in PHP?
An associative array of variables passed to the current script via HTTP cookies.

Q. What do you mean by environment variable in PHP?
PHP environment variables allow your scripts to glean certain types of data dynamically from the server. ...
You can access these variables using the $_SERVER and $_ENV arrays.

Q. What is the purpose of $_ENV variable in PHP?
$_ENV is a superglobal that contains environment variables. Environment variables are provided by the shell under which PHP is running, so they may vary according to different shells.

Q. What is the purpose of $_SESSION variable in PHP?
$_SESSION − An associative array containing session variables available to the current script.

Q. How will you redirect a page?
The header() function supplies raw HTTP headers to the browser and can be used to redirect it to another location. The redirection script should be at the very top of the page to prevent any other part of the page from loading. The target is specified by the Location: header as the argument to the header() function. After calling this function the exit() function can be used to halt parsing of rest of the code.

Q. What is the purpose $_PHP_SELF variable?
The default variable $_PHP_SELF is used for the PHP script name and when you click "submit" button then same PHP script will be called.

Q. How will you get the browser details using PHP?
One of the environment variables set by PHP is HTTP_USER_AGENT which identifies the user's browser and operating system.

Q. What do you mean by HTTP status codes?
Status codes are issued by a server in response to a client's request made to the server. The first digit of the status code specifies one of five standard classes of responses. The message phrases shown are typical, but any human-readable alternative may be provided.

Q. What are the HTTP client error codes?
The HTTP client error codes start with 4. Example: 404 is used for 'not found' status.

Q. What are the informational status codes?
1xx: Informational It means the request has been received and the process is continuing.

Q. What are the HTTP success codes?
2xx: Success It means the action was successfully received, understood, and accepted.

Q. How do you get the redirection related information?
3xx: Redirection It means further action must be taken in order to complete the request.

Q. What is API?
Application Program Interface is a set of functions and procedures that allow the creation of applications which access the features or data of an operating system, application, or other service.

Basically, an API specifies how software components should interact. Additionally, APIs are used when programming graphical user interface (GUI) components. A good API makes it easier to develop a program by providing all the building blocks. A programmer then puts the blocks together.

Most often-used types of web service:

SOAP.
XML-RPC.
JSON-RPC.
REST.

Q. What is REST API?
REST stands for "REpresentational State Transfer". It is a concept or architecture for managing information over the internet. REST concepts are referred to as resources. A representation of a resource must be stateless. It is usually represented by JSON. API stands for "Application Programming Interface". It is a set of rules that allows one piece of software application to talk to another. Those "rules" can include create, read, update and delete operations.

REST API can be used by any application that can connect to the internet. If data from an application can be created, read, updated or deleted using another application, it usually means a REST API is used.

Q. What is JSON?
JSON: JavaScript Object Notation.
JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation.

Q. Why do we need JSON?
For sending data
For receiving data

Q. How can you exchange data using JSON?
While exchanging data between a browser and a server, the data can only be text. JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server. We can also convert any JSON received from the server into JavaScript objects. This way we can work with the data as JavaScript objects, with no complicated parsing and translations.

Q. Differentiate between JSON & XML?

JSON doesn't use end tag
JSON is shorter
JSON is quicker to read and write
JSON can use arrays
XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function

Q. What are the advantages of JSON?
JSON is easier to parse. JSON follows simple steps like:

Fetch a JSON string
JSON.Parse the JSON string

Using XML:

Fetch an XML document
Use the XML DOM to loop through the document
Extract values and store in variables

Q. What is Session?
A session is a temporary and interactive information interchange between two or more communicating devices, or between a computer and user. Session is stored at the server side.

Q. What is Cookie?
Cookie is a small text file (generally up to 4KB) created by a website that is stored in the user's computer either temporarily for that session only or permanently. Cookies provide a way for the website to recognize you and keep track of your preferences and other functionalities like shopping cart.

Q. Differentiate between Session & Cookie?

Cookies Vs    Sessions
stored in browser as text file.     - server side
can store limited data    - can store unlimited data
data is on client side and hence easily accessible     -  data is on server side and is difficult ot access

Q. How do we start a session?
Using session_start() method at the beginning of the script.

Q. How can we set session variable?
Session variables are set with the PHP global variable $_SESSION

Example:

// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";

Q. How to destroy a session?
Using session_destroy() method at the end of the script.

Q. How to remove value from session variable?
session_unset() method

Q. When do we need to set session variables?
When a particular user signs in, adds items to cart - to track the particular user activity. Session variables must be set after using session_start();

Q. When do we need a session and not a cookie?
Cookies are stored on the client side
, so they can be viewed, edited and deleted by the user. So be careful to not store and sensitive information on cookies. Sessions are used when more sensitive information like password or id is being passed. Sessions are not accessible by users and hence more secure.
You want to store important information such as the user id more securely on the server where malicious users cannot temper with them.
You want to pass values from one page to another.
You want the alternative to cookies on browsers that do not support cookies.
You want to store global variables in an efficient and more secure way compared to passing them in the URL You are developing an application such as a shopping cart that has to temporary store information with a capacity larger than 4KB.

Q. When do we need a cookie and not a session?
Http is a stateless protocol; cookies allow us to track the state of the application using small files stored on the user's computer.
The path where the cookies are stored depends on the browser.

Internet Explorer usually stores them in Temporal Internet Files folder.

Personalizing the user experience - this is achieved by allowing users to select their preferences.

The page requested that follow are personalized based on the set preferences in the cookies.

Tracking the pages visited by a user

Also, cookies last longer than that of a session.

Q. How can we set a cookie?
Using setcookie(name, value, expire, path, domain, secure, httponly);

Q. How to modify a cookie value?
To modify a cookie, just set (again) the cookie using the setcookie() function.

Q. How will we make a check that a cookie is set or not?
You can use isset() function to check if a cookie is set or not.

Q. How to retrieve all cookie values?
print_r($_COOKIE);

Output:

Array ([user] => abhi [age] => 25 [profile] => developer)

Q. How to delete a cookie?
When deleting a cookie you should assure that the expiration date is in the past.

// set the expiration date to one hour ago
setcookie("user", "abhi", time()-60*60);

Q. How can we implement 'remember me' using PHP?
As the name indicate the meaning that cookies are the method to store the information of a web page in a remote browser,those information can be retrieved form the browser itself,when the same user comes back to that page.

The browser stores the message in a small text file that the server embeds on the user's system.You can set cookies using the setcookie()function.

PHP transparently supports HTTP cookies,so setcookie() must be called before any output is sent to the browser.

Q. Classify cookies.
There are 2 types of cookies:

Session Based which expire at the end of the session.
Persistent cookies which are written on harddisk.

Q. How will you delete a cookie?
To delete a cookie you should call setcookie() with the name argument only.

Q. How to track login and logout using PHP?
Session variable must be set when a user logs in and session needs to be destroyed upon logout.

Q. How to create a file?
touch() function is used to create a file.

Example:

// create text file
touch("data.txt");

Q. What are the other way to write in a file?
An alternative way to write data to a file is to create a file pointer with fopen(), and then write data to the pointer using PHP's fwrite() function.

Example:

// open and lock file 
$fo=fopen("output.txt","w");
flock($fo,LOCK_EX) or die('ERROR:cannot lock file');

// write string to file
$data="A fish out of water";
fwrite($fo, $data);

// unlock and close file
flock($fo,LOCK_UN) or die('ERROR:cannot unlock file');
fclose($fo);
echo "Data written to file";

Q. How will you check if a file exists or not using php?
File's existence can be confirmed using file_exist() function which takes file name as an argument.

Q. How to delete a file?
unlink( ) function is used to delete a file.

Example:

// delete text file
unlink("data.txt");

Q. How to copy a file?
Example:

// copy text file
copy("data.txt","update data.txt");

Q. How to rename file?
rename() function is used to rename file.

Example:

// rename text file
rename("data.txt","update data.txt");

Q. How to check whether a file or directory exists?
file_exists() function is used to check file or directory existence.

Example:

// check file existence
echo file_exists("Update resume.doc");

Output:

1

Q. How to check path of the file in PHP?
realpath() function is used to check real path of the file.

Example:

// check real path of the file
echo realpath("Update resume.doc");

Q. How to check size of the file in PHP?
The files length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.

Example:

// check file size
echo filesize("notes.txt")." Bytes";

Output:

190 Bytes

Q. How to write the contents inside file?
file_put_contents() accepts a filename and path, together with the data to be written to the file, and then writes the latter to the former

Example:

// write string to file
$data = "A fish out of water";
file_put_contents("output.txt", $data) or die('ERROR: Can not write file');
echo "data written inside  this file";

Q. Explain file() method.
A way of reading data from a file is file() function, which accepts the name and path to a file and reads the entire file into an array, with each element of the array representing one line of the file. Here's an example which reads a file into an array and then displays it using foreach loop.

Example:

// read file into array
$arr = file('output.txt') or die('ERROR: cannot file file');
foreach ($arr as $line) {
   echo $line;

Q. How To change the file permissions?
Permissions in PHP are very similar to UNIX. Each file has following three types of permissions.

Read
Write and
Execute. PHP uses the chmod() function to change the permissions of a specific file. It returns TRUE on success and FALSE on failure.
Following is the Syntax:

chmod(file,mode)

Q. What are different ways to get the extension of a file?
There are following two ways to retrieve the file extension.

$filename = $_FILES['image']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);`

Q. How to create a directory using PHP?

Example:

mkdir("mydocs");
In this program we use mkdir()function . Pass the directory name inside this function to create the directory.

Q. How to get files(contents) from directory?
$files =  scandir("mydocs");
print_r($files);
in the above example we get the contents of a directory. use scandir() function , directory name declare inside this. scandir() function returns the files in array so stored the return value in a variable( $files). Now print this using print_r($files) function i.e specially used to print the value and index of array. it gives an output of an array type with index and their corresponding value.

Q. How to open a directory?
$od =  openddir("mydocs");

In the above example if we open the directory use opendir() function with directory name ('mydocs'). store in variable $files because these open directory variable is going to used in further communication(for reading the contents).

Q. What is include in php?
Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing. The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal error.

If a path is defined  -  whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..)  -  the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.

Q. What is require_once in php?
The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.

"require_once" and "require" are language constructs and not functions. Therefore they should be written without "()" brackets!

Q. What is include_once in php?
The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and "include_once" returns TRUE. As the name suggests, the file will be included just once.

include_once may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.

Q. What is require() in PHP?
require() statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. require will produce a fatal error (E_COMPILE_ERROR) and stop the script.

Q. What is difference between require and include?
The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

Q. What is RegEx?
RegEx or Regular Expressions is a way to express how a computer program should look for a specified pattern in text and then what the program is to do when each pattern match is found. For example, a regular expression could tell a program to search for all text lines that contain the word "Windows 10" and then to print out each line in which a match is found or substitute another text sequence (for example, just "Windows") where any match occurs.

Q. Why do we need RegEx?
Regular expressions simplify identifying patterns in string data by calling a single function. This saves us coding time.
When validating user input such as email address, domain names, telephone numbers, IP addresses, Highlighting keywords in search results
When creating a custom HTML template. Regular expressions can be used to identify the template tags and replace them with actual data.

Q. How preg_match() function works?
The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.

$my_url = "www.bootsity.com";
echo preg_match("/boot/", $my_url); // prints true

Q. Regualar Expression Notations?

Expression    Description
p+    matches any string containing at least one p.
p*    matches any string containing zero or more p's.
p?    matches any string containing zero or one p's.
p{N}    matches any string containing a sequence of N p's
p{2,3}    matches any string containing a sequence of two or three p's.
p{2, }    matches any string containing a sequence of at least two p's.
p$    matches any string with p at the end of it.
^p    matches any string with p at the beginning of it.

Q. Regular Expression Examples?

Expression - Description
[^a-zA-Z] 
   matches any string not containing any of the characters ranging from a through z and A through Z.
p.p    matches any string containing p, followed by any character, in turn followed by another p.
^.{2}$    matches any string containing exactly two characters.
(.*)    It matches any string enclosed within and .
p(hp)*    matches any string containing a p followed by zero or more instances of the sequence php.

Q. What is OOPs?
Object Oriented Programming(OOPs) is a programming approach based upon objects and data. In OOP approach, we create templates known as classes and then create their runtime instances known as objects.

Q. What is an object?
Object is a real life entity which has an identity and behaviour. Each object is an instance of a particular class or subclass with the class's own methods or procedures and data variables.

Q. How can we create object of a class?
Once we define our class, we can create as many objects as we like of that class type. Following is an example of how to create object using new operator.

$physics = new Books();
$maths = new Books();
$chemistry = new Books();

Q. What is a class?
A class is a template that is used to create objects, and to define object data types and methods. Core properties include the data types and methods that may be used by the object. All class objects should have the basic class properties.

Q. What are the basic features of OOPs?
Abstraction
Encapsulation
Polymorphism
Inheritance

Q. Is PHP purely an object oriented language?
No, PHP is not purely object oriented. PHP supports object oriented approach as well as procedural approach.

Q. Differentiate between OOPs & POPs?

OOPs    Vs   POPs
Takes bottom-up approach.    - Follows top-down approach
Program is divided into objects    - Program is divided into functions
Each objects control it's own data -     Here, data is global
Data hiding and inheritance are available    - No such features are there
Java, C++    - Pascal, Fortran

Q. What is generalization?
Generalization is the process of extracting shared characteristics from two or more classes, and combining them into a generalized superclass. Shared characteristics can be attributes, associations, or methods.

Q. What is specialization?
Specialization is the reverse process of Generalization means creating new sub classes from an existing class.

Q. What is aggregation?
Aggregation is a relationship between two classes that is best described as a "has-a" and "whole/part" relationship. It is a more specialized version of the association relationship. The aggregate class contains a reference to another class and is said to have ownership of that class.

Q. What is composition?
Composition is a special case of aggregation. In other words, a restricted aggregation is called composition. When an object contains the other object and the contained object cannot exist without the other object, then it is called composition.

Q. What is association?
The association relationship indicates that a class knows about, and holds a reference to, another class. Associations can be described as a "has-a" relationship.

Q. What is abstraction?
An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.

Q. What is encapsulation?
Encapsulation is the process of binding both attributes and methods together within a class. Through encapsulation, the internal details of a class can be hidden from outside. The class has methods that provide user interfaces by which the services provided by the class may be used.

Q. What is inheritance?
Inheritance is a mechanism wherein a new class is derived from an existing class where a class inherits or acquires the properties and methods of other classes.

Q. What is super class?
The class from which it's derived is called the superclass.

Q. What is a sub class?
The derived class (the class that is derived from another class) is called a subclass.

Q. How can you inherit a class in PHP?
We declare a new class with additional keyword extends.

Q. What is a constructor?
If a class name and function name will be similar in that case function is known as constructor.

Constructor is special type of method because its name is similar to class name.

Constructor automatically calls when object will be initializing.

Q. Explain __construct().
By using this function we can define a constructor.

It is known as predefined constructor. Its better than user defined constructor because if we change class name then user defined constructor treated as normal method.

If predefined constructor and user defined constructor, both are defined in the same class, then predefined constructor will be treated as a Constructor while user defined constructor treated as normal method.

Q. Classify constructor.
Default constructor
Parameterized constructor
Copy constructor

Q. What is a destructor?
The Destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence. __destruct() is used to define destructor.

Q. Explain $this.
To access or change a class method or property within the class itself, it's necessary to prefix the corresponding method or property name with $this which refers to this class.

Q. Explain multiple inheritance.
Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit characteristics and features from more than one parent object or parent class.

Q. Does PHP support multiple inheritance?
No. PHP only supports multi-level inheritance.

Q. Explain multi-level inheritance.
When a class is derived from a class which is also derived from another class, i.e. a class having more than one parent classes, such inheritance is called Multilevel Inheritance. The level of inheritance can be extended to any number of level depending upon the relation.

Q. What is polymorphism?
The Greek word Poly means 'many' and morph means property which help us to assign more than one property with a single name.

Method overloading
Method overriding These are the example of polymorphism.

Q. What is method overloading?
Method overloading is the phenomenon of using same method name with different signature.

Q. Does PHP support method overloading?
PHP doesn't support method overloading concept.

Q. What is method overriding?
Method definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.

Q. What are interfaces in PHP?
Interfaces are defined to provide a common function names to the implementors. Different implementors can implement those interfaces according to their requirements. You can say, interfaces are skeltons which are implemented by developers.

Q. What does the presence of operator '::' represent?
The scope resolution operator :: allows any declaration/definition of methods, variables outside the body of a class.

Q. How to define a class in PHP?
Class always start with class keyword. After this write class name without parentheses.

class demo{
   function add() {   
       $x = 800;
       $y = 200;
       $sum = $x + $y;
       echo "sum of given no= ". $sum . "
";    
   }
   function sub() {
       $x = 1000;
       $y = 200;
       $sub = $x - $y;
       echo "Sub of given no = " . $sub;    
   }
}

Q. How will you add a constructor function to a PHP class?
PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function.

Q. How will you add a destructor function to a PHP class?
Like a constructor function you can define a destructor function using function __destruct(). You can release all the resourceses with-in a destructor.

Q. How will you access the reference to same object within the object in PHP?
The variable $this is a special variable and it refers to the same object ie. itself.

Q. What do you mean by access modifier?
Access Modifier allows you to alter the visibility of any class member(properties and method). In php, there are three scopes for class members.

Public
Protected
Private

Q. Explain access modifiers in PHP.
Public access modifier is open to use and access inside the class definition as well as outside the class definition.

Protected is only accessible within the class in which it is defined and its parent or inherited classes.

Private is only accessible within the class that defines it.( it can't be access outside the class means in inherited class).

Q. Explain final class in PHP.
The final keyword prevents child classes from overriding a method by prefixing the definition with final.

It means if we define a method with final then it prevent us to override the method.

Q. Explain abstract class.
There must be a abstract keyword that must be return before this class for it to be abstract class to implement Abstraction.

This class cannot be instantiated. only the class that implement the methods of abstract class can be instantiated.

There can be more than one methods that can left undefined.

Q. What is interface?
The class that is fully abstract is called interface.

Any class that implement this interface must use implements keyword and all the methods that are declared in the class must be defined here. otherwise this class also need to be defined as abstract.

Q. What do you mean by an exception?
An exception is a problem that arised during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program or application terminates abnormally.

Q. Define Exception class Hierarchy.
Throwable -- Error -- Arithmetic Error -- Parse Error -- Exception -- Logic Exception -- Runtime Exception

Q. How do we handle exceptions?
When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception". An exception can be thrown, and caught within PHP.

To handle exceptions, code may be surrounded in a try block. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions. Exceptions can be thrown (or re-thrown) within a catch block.

Consider:

try {
   print "this is our try block n";
   throw new Exception();
} catch (Exception $e) {
   print "something went wrong, caught yah! n";
} finally {
   print "this part is always executed n";
}

Q. Differentiate between exception and error?
Recovering from Error is not possible
. The only solution to errors is to terminate the execution. Where as you can recover from Exception by using either try-catch blocks or throwing exception back to caller.
You will not be able to handle the Errors using try-catch blocks. Even if you handle them using try-catch blocks, your application will not recover if they happen. On the other hand, Exceptions can be handled using try-catch blocks and can make program flow normal if they happen.
Exceptions are related to application where as Errors are related to environment in which application is running.

Q. What do we mean by error log?
By default, PHP sends an error log to the server's logging system or a file, depending on how the error_log configuration is set in the php.ini file. By using the error_log() function you can send error logs to a specified file or a remote destination.

Q. How do we see PHP errors?
Display errors could be turned off in the php.ini or your Apache config file. You can turn it on in the script: error_reporting(E_ALL); ini_set('display_errors', 1); You should see the same messages in the PHP error log.

Q. What are the exception class functions?
There are following functions which can be used from Exception class.
getMessage() − message of exception getCode() − code of exception getFile() − source filename getLine() − source line getTrace() − n array of the backtrace() getTraceAsString() − formated string of trace

Q. What does the expression Exception::__toString means?
Exception::__toString gives the string representation of the exception.

Q. Why do we need cryptography?
Cryptography can be used for non-technological reasons like hiding physical messages, or creating ciphers so that only you and your friends can read your messages, but nowadays it is used for more vital reasons. It is the basis for Data Encryption.
Cryptography is used to make sure all of the things that shouldn't happen. Shouldn't because nothing is perfect, and people can usually find loops holes or ways around the rules. Cryptography takes math and uses it to develop algorithms for computer systems to use to secure data either before data transfer or just for secure data storage.

Q. What do we mean by hash functions?
A hash function is any function that can be used to map data of arbitrary size to data of a fixed size. The values returned by a hash function are called hash values, hash codes, digests, or simply hashes.

Q. What is hash function in PHP?
It generates a hash value (message digest).

Syntax:

string hash ( string $algo , string $data [, bool $raw_output = FALSE ] )

Q. Example using hash().
echo hash('ripemd160', 'The quick brown fox jumped over the lazy dog.');
Output:

ec457d0a974c48d5685a7efa03d137dc8bbde7e3

Q. What is encoding and decoding?
Encoding means converting the message or information into a coded form in order to avoid hacking.

Decoding means converting signals into a different or usable form. The reverse process of encoding is known as decoding.

Q. What is SHA1?
In cryptography, SHA-1, Secure Hash Algorithm-1 is a cryptographic hash function which takes an input and produces a 160-bit hash value known as a message digest - typically rendered as a hexadecimal number, 40 digits long.

The sha1() function uses the US Secure Hash Algorithm 1.

Example:

$str = "Hello";
echo sha1($str);
Output:

f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0

Q. Can sha1 be decrypted?
We cannot say that it is impossible at all (only in our world with limited resources it is). If you have a simple SHA1 hash, you could decrypt it if you guess what has been encrypted. But this is of course not efficient. In reality decrypting a large SHA-1 hash is nearly impossible.

Q. What is sha1_file()?
The sha1_file() function calculates the SHA-1 hash of a file. This function returns the calculated SHA-1 hash on success, or FALSE on failure.

$filename = "test.txt";
$sha1file = sha1_file($filename);
echo $sha1file;

Output:

aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d

Q. What are the disadvantages of sha1()?
Google announced the first SHA1 collision in 2017. This requires a lot of computing power and resources. Since this never occurred naturally in real world under normal conditions we can rule out security risks today but not tomorrow.

SHA-1 for hashing passwords requires less computing power and this improves the performance of your application. Git still using SHA-1 for internal operations.

Q. What MD5 means?
MD5 (technically called MD5 Message-Digest Algorithm) is a cryptographic hash function whose main purpose is to verify that a file has been unaltered.

The md5() function calculates the MD5 hash of a string. The md5() function uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm.

$str = "Hello";
echo md5($str);

Output:

8b1a9953c4611296a827abf8c47804d7

Q. Why can not a MD5 hash be decrypted?
There are no services which allow you to "decrypt MD5" because, MD5 is not an encryption algorithm. Hash functions take an input and create an output which cannot be turned back into the input. Because its not encrypted. MD5 is a hashing algorithm.

Q. Is md5 reversible?
Now a days MD5 hashes or any other hashes for that matter are pre computed for all possible strings and stored for easy access. Though in theory MD5 is not reversible but using such databases you may find out which text resulted in a particular hash value. f(x) = 1 is irreversible. Hash functions aren't irreversible.

Q. Compare sha1() and md5().
MD5 and SHA-1 have a lot in common; SHA-1 was clearly inspired on either MD5 or MD4, or both (SHA-1 is a patched version of SHA-0, which was published in 1993, while MD5 was described as a RFC in 1992).

The main structural differences are the following:

SHA-1 has a larger state: 160 bits vs 128 bits.
SHA-1 has more rounds: 80 vs 64.
SHA-1 rounds have an extra bit rotation and the mixing of state words is slightly different (mostly to account for the fifth word).
Bitwise combination functions and round constants are different.
Bit rotation counts in SHA-1 are the same for all rounds, while in MD5 each round has its own rotation count.
The message words are pre-processed in SHA-0 and SHA-1. In MD5, each round uses one of the 16 message words "as is"; in SHA-0, the 16 message words are expanded into 80 derived words with a sort of word-wise linear feedback shift register. SHA-1 furthermore adds a bit rotation to these word derivation.

Q. What is enctype?
The enctype attribute specifies how the form-data should be encoded when submitting it to the server. The enctype attribute can be used only if method="post"

Following are different types of enctype.

application/x-www-form-urlencoded is the default value if the enctype attribute is not specified. This is the correct option for the majority of simple HTML forms.

multipart/form-data is necessary if your users are required to upload a file through the form.

text/plain is a valid option, although it sends the data without any encoding at all. It is not recommended, as its behavior is difficult to predict.

Q. Explain each Mcrypt function supported in PHP.
Mcrypt() supports many functions:

Mcrypt_cbc()- Encrypts data in Cipher block chain mode.
Mcrypt_cfb()- Encrypts data cipher feedback (CFB) mode
Mcrypt_decrypt()- Decrypts data.
mcrypt_encrypt- Encrypts plaintext with given parameters
mcrypt_generic- Encrypts data
mcrypt_get_key_size - Get the key size of the specified cipher
mdecrypt_generic - Decrypts data

Q. What is cryptography authentication?
In cryptography, a message authentication code (MAC), sometimes known as a tag, is a short piece of information used to authenticate a message - in other words, to confirm that the message came from the stated sender (its authenticity) and has not been changed.

Q. What is HTML?
Hypertext Markup Language (HTML)
is the standard markup language for creating web pages and web applications.

Example:

<HTML>
  <HEAD>
     <TITLE>Your Title Here</TITLE>
  </HEAD>
  <BODY BGCOLOR="FFFFFF">
     contents of page
  </BODY>
</HTML>

 

 

Also see: All The Useful PHP Interview Questions & Answers - Part 1

 

All The Useful PHP Interview Questions & Answers - Part 3