Important PHP 2 mark questions and answers-part1

 

1. Differentiate between variables and constants in PHP

Few differences between variables and constants in PHP are given below:

Variables

Constants

The value of a variable can be changed during the execution.

The constant value can’t be changed during script execution.

Variables require compulsory usage of the $ sign at the start.

No dollar sign ($) is required before using a constant.

It is possible to define a variable by simple assignment.

Constants can’t be defined by simple assignments. They are defined using the define() function.

The default scope is the current access scope.

Constants can be accessed throughout without any scoping rules.

2. What is a session in PHP?

A session in PHP is a way to store information to be used across multiple pages of an entire website. The information is not stored on the user’s computer, unlike cookies. In a temporary directory on the server, a file will be created by the session where registered session variables and their values are stored. This information will be available to all pages on the site during that visit.

When you work with an application, you open it, do some modifications, and then you close it. This is much like a Session. The computer knows who you are. It knows when the application is started and ended by you.

But on the internet, the webserver does not know who you are or what you do, because the HTTP address doesn’t maintain a state. This problem is solved using session variables by storing user information to be used across multiple pages (e.g. username, favorite color, etc).

By default, session variables will last until the user closes the browser.

So Session variables hold single user information and are available to all pages in one application.

3. What does PEAR stands for?

PEAR stands for “PHP Extension and Application Repository”. PEAR is a framework and repository for all of the reusable PHP components.

PEAR provides a higher level of programming for web developers. It contains all kinds of PHP code snippets and libraries. It also provides you with a command-line interface to automatically install packages.

4. Explain the difference between $message and $$message.

The main difference between the $message and $$message is given below:

$message

$$message

$message is a regular variable.

$$message is a reference variable.

It has a fixed name and stores a fixed value.

It stores data about the variable.

Data stored in $message is fixed.

The value of the $$message can change dynamically as the value of the variable changes.

5. Is PHP a case-sensitive language?

PHP can be considered as a partial case-sensitive language. The variable names are completely case-sensitive but function names are not. Also, user-defined functions are not case-sensitive but the rest of the language is case-sensitive.

For example, user-defined functions in PHP can be defined in lowercase but later referred to in uppercase, and it would still function normally.

6. What are the different types of variables present in PHP?

Types of PHP Variables

There are 8 primary data types in PHP which are used to construct the variables. They are:

ü  Integers: Integers are whole numbers without a floating-point. Ex: 1253.

ü  Doubles: Doubles are floating-point numbers. Ex: 7.876

ü  Booleans: It represents two logical states- true or false.

ü  NULL: NULL is a special type that only has one value, NULL. When no value is assigned to a variable, it can be assigned with NULL.

ü  Arrays: Array is a named and ordered collection of similar type of data. Ex: $colors = array("red", "yellow", "blue");

ü  Strings: Strings are a sequence of characters. Ex: “Hello InterviewBit!”

ü  Resources: Resources are special variables that consist of references to resources external to PHP(such as database connections).

ü  Objects: An instance of classes containing data and functions. Ex: $mango = new Fruit();

7. What are the rules for naming a PHP variable?

The following two rules are needed to be followed while naming a PHP variable:

ü  A variable must start with a dollar symbol, followed by the variable name. For example: $price=100; where price is a variable name.

ü  Variable names must begin with a letter or underscore.

ü  A variable name can consist of letters, numbers, or underscores. But you cannot use characters like + , – , % , & etc.

ü  A PHP variable name cannot contain spaces.

ü  PHP variables are case-sensitive. So $NAME and $name both are treated as different variables.

8. What is the difference between “echo” and “print” in PHP?

The main difference between echo and print in PHP are given below:

echo

print

echo can output one or more strings.

print can only output one string and it always returns 1.

echo is faster than print because it does not return any value.

print is slower compared to echo.

If you want to pass more than one parameter to echo, a parenthesis should be used.

Use of parenthesis is not required with the argument list.

9. Tell me some of the disadvantages of PHP

The cons of PHP are:

ü  PHP is not suitable for giant content-based web applications.

ü  Since it is open-source, it is not secure. Because ASCII text files are easily available.

ü  Change or modification in the core behavior of online applications is not allowed by PHP.

ü  If we use more features of the PHP framework and tools, it will cause poor performance of online applications.

ü  PHP features a poor quality of handling errors. PHP lacks debugging tools, which are needed to look for warnings and errors. It has only a few debugging tools in comparison to other programming languages.

10. How can PHP and HTML interact?

PHP scripts have the ability to generate HTML, and it is possible to pass information from HTML to PHP.

PHP is a server-side language whereas HTML is a client-side language. So PHP executes on the server-side and gets its results as strings, objects, arrays, and then we use them to display its values in HTML.

This interaction helps bridge the gaps and use the best of both languages.

11. What is the purpose of @ in PHP?

In PHP, @ is used for suppressing error messages. If any runtime error occurs on the line which consists @ symbol at the beginning, then the error will be handled by PHP.

12. Explain the importance of Parser in PHP?

A PHP parser is software that converts source code into the code that computer can understand. This means whatever set of instructions we give in the form of PHP code is converted into a machine-readable format by the parser.

You can parse PHP code with PHP using the token_get_all() function.

13. What are the different types of Array in PHP?

There are 3 main types of arrays that are used in PHP:

Types of Arrays in PHP

Indexed Array

An array with a numeric key is known as the indexed array. Values are stored and accessed in linear order.

Associative Array

An array with strings for indexing elements is known as the associative array. Element values are stored in association with key values rather than in strict linear index order.

Multidimensional Array

An array containing one or more arrays within itself is known as a multidimensional array. The values are accessed using multiple indices.

14. Explain the main types of errors.

The 3 main types of errors in PHP are:

·         Notices: Notices are non-critical errors that can occur during the execution of the script. These are not visible to users. Example: Accessing an undefined variable.

·         Warnings: These are more critical than notices. Warnings don’t interrupt the script execution. By default, these are visible to the user. Example: include() a file that doesn’t exist.

·         Fatal: This is the most critical error type which, when occurs, immediately terminates the execution of the script. Example: Accessing a property of a non-existent object or require() a non-existent file.

15. What are traits?

Traits are a mechanism that lets you create reusable code in PHP and similar languages where multiple inheritances are not supported. It’s not possible to instantiate it on its own.

A trait is intended to reduce the limitations of single inheritance by enabling a developer to reuse sets of methods freely in many independent classes living in different hierarchies of class.

16. Does JavaScript interact with PHP?

JavaScript is a client-side programming language, whereas PHP is a server-side scripting language. PHP has the ability to generate JavaScript variables, and this can be executed easily in the browser. Thereby making it possible to pass variables to PHP using a simple URL.

17. How does the ‘foreach’ loop work in PHP?

The foreach statement is a looping construct that is used in PHP to iterate and loop through the array data type.

The working of foreach is simple, with every single pass of the value, elements get assigned a value, and pointers are incremented. This process is repeatedly done until the end of the array has been reached.

The syntax for using the foreach statement in PHP is given below:

foreach($array as $value)

{

   Code inside the loop;

}

18. What is the most used method for hashing passwords in PHP?

The crypt() function is used for this functionality as it provides a large number of hashing algorithms that can be used. These algorithms include sha1, sha256, or md5 which are designed to be very fast and efficient.

19. What is the difference between the include() and require() functions?

include() function

This function is used to copy all the contents of a file called within the function, text wise into a file from which it is called.

When the file is included cannot be found, it will only produce a warning (E_WARNING) and the script will continue the execution.

require() function:

The require() function performs same as the include() function. It also takes the file that is required and copies the whole code into the file from where the require() function is called.

When the file is included cannot be found, it will produce a fatal error (E_COMPILE_ERROR) and terminates the script.

20. What are cookies? How to create cookies in PHP?

A cookie is a small record that the server installs on the client’s computer. They store data about a user on the browser. It is used to identify a user and is embedded on the user’s computer when they request a particular page. Each time a similar PC asks for a page with a program, it will send the cookie as well.

After verifying the user’s identity in encrypted form, cookies maintain the session id generated at the back end. It must reside in the browser of the machine. You can store only string values not object because you cannot access any object across the website or web apps.

By default, cookies are URL particular. For example, Gmail cookies are not supported by Yahoo and vice versa. Cookies are temporary and transitory by default. Per site 20 cookies can be created in a single website or web app. 50 bytes is the initial size of the cookie and 4096 bytes is the maximum size of the cookie.

In PHP, we can create cookies using the setcookie() function:

setcookie(name, value, expire, path, domain, secure, httponly);

Here name is mandatory and the remaining parameters are optional.

Example:
setcookie(“instrument_selected”, “guitar”)

21. What is the difference between ASP.NET and PHP?

The main difference between ASP.NET and PHP are given below:

ASP.NET

PHP

A web application framework.

A server-side scripting language.

It is designed for use on Windows.

It is Platform independent

Code is compiled and executed.

Interpreted mode of execution.

It has a license cost associated with it.

PHP is open-source and freely available.

22. What is the meaning of ‘escaping to PHP’?

The PHP parsing engine needs a way to differentiate PHP code from other page elements. The mechanism to achieve this is known as ‘escaping to PHP’. Escaping a string means reducing ambiguity in quotes used in that string.

For example, when you’re defining a string, you surround it in either double quotes or single quotes:
"Hello, InterviewBit." 

But what if I include double quotes within the string?
"Hello "InterviewBit."" 

Now I have ambiguity - the interpreter doesn’t know where does my string end. If I want to keep my double quotes, I have various options. I could use single quotes around my string:
'Hello "InterviewBit."' 

Or I can escape my quotes:
"Hello \"InterviewBit.\"" 

Any quote that is preceded by a slash is escaped and understood to be part of the value of the string.

23. Explain Path Traversal

Path traversal is a form of attack to read into the files of a web application. '../' (dot-dot-sequences) is a cross-platform symbol to go up in the directory. Path traversal makes use of this symbol to operate the web application file. The attacker can reveal the content of the file attacked using the path traversal outside the root directory of a web server or application. It is usually done to gain access to secret passwords, tokens, and other sensitive information stored in the files.

Path Traversal is also called “Directory Traversal”. It allows the attacker to exploit vulnerabilities present in the web file under attack.

Let’s take a simple example. Consider we have a “Show File” button that opens up some URL.

For a classic directory traversal attack, the attacker may try to access the system file /etc/passwd (assuming a UNIX/LINUX system). If the application receives the value of the file parameter from the URL and passes it to a system call, it would traverse the relative path ../../etc/passwd starting from /var/www and ask the system to load the password file.

This technique is also called a dot-dot-slash attack, because it usually uses the special characters ../ (or \.. on Windows) to climb to a higher-level directory.

24. What is the meaning of a final method and a final class?

The final keyword in a declaration of the method indicates that the method cannot be overridden by subclasses. A class that is declared as final cannot be subclassed.

This is especially useful when we are creating an immutable class like the String class. Only classes and methods may be declared final, properties cannot be declared as final.

Comments

Popular posts from this blog

How to create Animated 3d chart with R.

Linux/Unix Commands frequently used

R Programming Introduction