Você está na página 1de 40

1) What is PHP?

PHP is a web language based on scripts that allow developers to


dynamically create generated web pages.

PHP is a widely-used, open-source server-side scripting language. PHP is an acronym for


“PHP: Hypertext Preprocessor.” It allows the developers to develop dynamic web
applications. PHP has various frameworks and CMS for developing dynamic and interactive
websites.

2) What do the initials of PHP stand for?

PHP means PHP: Hypertext Preprocessor.

3) Which programming language does PHP resemble?

PHP syntax resembles Perl and C

4) What does PEAR stand for?

PEAR means “PHP Extension and Application Repository.” It is a framework and distribution
system for reusable PHP components. It extends PHP and gives a higher level of
programming for all web developers. PEAR is divided into three different classes that are:
PEAR Core Components, PEAR Packages, and PECL Packages. The PEAR Packages
include functionality giving for authentication, networking, and file system features and tools
for working with HTML and XML templates.

5) What is the actually used PHP version?

Version 7.1 or 7.2 is the recommended version of PHP.

6) How do you execute a PHP script from the command line?

Just use the PHP command line interface (CLI) and specify the file name of
the script to be executed as follows:

php script.php

7) How to run the interactive PHP shell from the command line
interface?

Just use the PHP CLI program with the option -a as follows:

php -a

8) What is the correct and the most two common way to start and
finish a PHP block of code?
The two most common ways to start and finish a PHP script are:

<?php [ --- PHP code---- ] ?> and <? [--- PHP code ---] ?>

9) How can we display the output directly to the browser?

To be able to display the output directly to the browser, we have to use the
special tags <?= and ?>.

10) What is the main difference between PHP 4 and PHP 5? What is the
use of “ksort” in php?

PHP 5 presents many additional OOP (Object Oriented Programming)


features.

PHP 5 is an upgrade version of PHP 4. PHP 5 offers many extra OOPs features. It
introduces new functions which are not found in PHP4.

In PHP 5, you have to name your constructors.

In PHP 5, Class can be declared as Abstract.

PHP 5 introduced a special function which is __autoload().

In PHP 5, Class or method can be declared as Final.

In PHP 5, Magic methods are introduced such as __call, __get, __set and
__toString.

In PHP 5, ‘exceptions'(exception errors) has introduced.

In PHP 5, interfaces are introduced.

In PHP, Ksort has used to sort an array by key in reverse order.

11) Is multiple inheritance supported in PHP?

PHP supports only single inheritance; it means that a class can be


extended from only one single class using the keyword 'extended'.

12) What is the meaning of a final class and a final method?

'final' is introduced in PHP5. Final class means that this class cannot be
extended and a final method cannot be overridden.

13) How is the comparison of objects done in PHP?


We use the operator '==' to test two objects are instanced from the
same/corresponding class and have same attributes and equal values. We
can test if two objects are referring to the same instance of the same/
corresponding class by the use of the identity operator '==='.

14) How can PHP and HTML interact?

It is possible to generate HTML through PHP scripts, and it is possible to


pass pieces of information from HTML to PHP.

15) What type of operation is needed when passing values through a


form or an URL?

If we would like to pass values through a form or an URL, then we need to


encode and to decode them using htmlspecialchars() and urlencode().

16) How can PHP and Javascript interact?

PHP and Javascript cannot directly interact since PHP is a server side
language and Javascript is a client-side language. However, we can
exchange variables since PHP can generate Javascript code to be
executed by the browser and it is possible to pass specific variables back
to PHP via the URL.

17) What is the difference between explode() and split() functions? What is
needed to be able to use image function?

Split function splits a string into array by regular expression. Explode splits a string into array
by string.

The GD library is required to be able to do image functions. It also helps to execute more
image functions.

18) What is the use of the function 'imagetypes()'?

imagetypes() gives the image format and types supported by the current
version of GD-PHP.

19) What are the functions to be used to get the image's properties
(size, width, and height)?

There are three functions are used to get image properties. That functions are:

imagesy() for getting image height.

imagesx() for getting image width.

getimagesize() for getting image size.


20) How to include a file to a PHP page? How failures in execution are
handled with include() and require() functions?

We can include a file utilizing “include() ” or “require()” function with file path as its
parameter.

There are some failures when using functions include() and require(). If the function
require() cannot access/unable to find the file then it stops the execution of the
script and ends with a fatal error. However, in the same case (file not found)
the include() function gives a warning, and the PHP script continues to
execute (execution will continue). Thios is is the main difference between
these two functions.

21) What is the main difference between require() and require_once()?

require(), and require_once() perform the same task except that the second
function checks if the PHP script is already included or not before executing
it.

(same for include_once() and include())

22) How can I display text with a PHP script? What is the use of “echo” in
PHP?

Two methods are possible:

<!--?php echo "Method 1"; print "Method 2"; ?-->

In PHP, echo is used to print data on the webpage.

Example: <?php echo ‘Car insurance’; ?>

23) How can we display information of a variable and readable by a


human with PHP?

To be able to display a human-readable result we use print_r().

24) How to enlarge the execution time of a PHP script? How is it possible to set
an infinite execution time for PHP script?

It is possible to enlarge the execution time of a PHP script by utilizing the set_time_limit
function. It enables to enlarge the execution time of a PHP script.

The set_time_limit(0) added at the beginning of a script sets to infinite the


time of execution to not have the PHP error 'maximum execution time
exceeded.' It is also possible to specify this in the php.ini file.
25) a) What are the different types of errors in PHP? b) What does the PHP
error 'Parse error in PHP - unexpected T_variable at line x' means?

a) There are 4 basically types of error in PHP.

Parse Error – Commonly caused due to syntax mistakes in codes.

Fatal Error – These are basically runtime errors which are caused when you try to
access what cannot be done.

Warning Error – This error occurs when you try to include a file that is not present.

Notice Error – This error occurs when you try to utilize a variable that has not been
declared.

b) This is a PHP syntax error expressing that a mistake at the line x stops
parsing and executing the program.

26) What should we do to be able to export data into an Excel file?

The most common and used way is to get data into a format supported by
Excel. For example, it is possible to write a .csv file, to choose for example
comma as a separator between fields and then to open the file with Excel.

27) What is the function file_get_contents() useful for?

file_get_contents() lets reading a file and storing it in a string variable.

28) How can we connect to a MySQL database from a PHP script?

To be able to connect to a MySQL database, we must use mysql_connect()


function as follows:

<!--?php $database = mysql_connect("HOST", "USER_NAME", "PASSWORD");


mysql_select_db($database,"DATABASE_NAME"); ?-->

29) How to create a MySQL connection? What is the function


mysql_pconnect() useful for? What is the use of count function in MySQL?

mysql_connect(servername,username,password);

mysql_pconnect() ensure a persistent connection to the database, it means


that the connection does not close when the PHP script ends.

This function is not supported in PHP 7.0 and above

count() function is used for fetching the total number records in a table.
30) How be the result set of Mysql handled in PHP?

The result set can be handled using mysqli_fetch_array,


mysqli_fetch_assoc, mysqli_fetch_object or mysqli_fetch_row.

31) How is it possible to know the number of rows returned in the


result set?

The function mysqli_num_rows() returns the number of rows in a result set.

32) Which function gives us the number of affected entries by a


query?

mysqli_affected_rows() return the number of entries affected by an SQL


query.

33) What is the difference between mysqli_fetch_object() and


mysqli_fetch_array()?

The mysqli_fetch_object() function collects the first single matching record


where mysqli_fetch_array() collects all matching records from the table in
an array.

34) How can we access the data sent through the URL with the GET
method?

To access the data sent via the GET method, we use $_GET array like this:

www.url.com?var=value
$variable = $_GET["var"]; this will now contain 'value'

35) How can we access the data sent through the URL with the POST
method?

To access the data sent this way, you use the $_POST array.

Imagine you have a form field called 'var' on the form when the user clicks
submit to the post form, you can then access the value like this:

$_POST["var"];

36) How can we check the value of a given variable is a number?

It is possible to use the dedicated function, is_numeric() to check whether it


is a number or not.
37) How can we check the value of a given variable is alphanumeric?

It is possible to use the dedicated function, ctype_alnum to check whether it


is an alphanumeric value or not.

38) How do I check if a given variable is empty?

If we want to check whether a variable has a value or not, it is possible to


use the empty() function.

39) What does the unlink() function mean?

The unlink() function is dedicated for file system handling. It simply deletes
the file given as entry.

40) What does the unset() function mean? What is the difference between
unset() and unlink() function?

The unset() function is dedicated for variable management. It will make a


variable undefined.

unset() function is used to destroy a variable whereas unlink() function is used to destroy a
file.

41) How do I escape data before storing it in the database?

The addslashes function enables us to escape data before storage into the
database.

42) How is it possible to remove escape characters from a string?

The stripslashes function enables us to remove the escape characters


before apostrophes in a string.

43) How can we automatically escape incoming data?

We have to enable the Magic quotes entry in the configuration file of PHP.

44) What does the function get_magic_quotes_gpc() means?

The function get_magic_quotes_gpc() tells us whether the magic quotes is


switched on or no.

45) What are tags used for? Is it possible to remove the HTML tags from
data?
They allow making the result of the expression between the tags directly to the browser
response.

The strip_tags() function enables us to clean a string from the HTML tags.

46) what is the static variable in function useful for?

A static variable is defined within a function only the first time, and its value
can be modified during function calls as follows:

<!--?php function testFunction() { static $testVariable = 1; echo $testVariable; $


testVariable++; } testFunction(); //1 testFunction(); //2 testFuncti
on(); //3 ?-->

47) How can we define a variable accessible in functions of a PHP


script?

This feature is possible using the global keyword.

48) How is it possible to return a value from a function?

A function returns a value using the instruction 'return $value;'.

49) What is the most convenient hashing method to be used to hash


passwords?

It is preferable to use crypt() which natively supports several hashing


algorithms or the function hash() which supports more variants than crypt()
rather than using the common hashing algorithms such as md5, sha1 or
sha256 because they are conceived to be fast. Hence, hashing passwords
with these algorithms can create vulnerability.

50) Which cryptographic extension provide generation and


verification of digital signatures?

The PHP-OpenSSL extension provides several cryptographic operations


including generation and verification of digital signatures.

51) What is the use of Constant Function? How is a constant defined in a


PHP script? How can we modify the value of a constant?

A constant function is used to return the constant value.

The define() directive lets us defining a constant as follows:

define ("ACONSTANT", 123);


We cannot alter the value of a constant.

52) How can you pass a variable by reference?

To be able to pass a variable by reference, we use an ampersand in front


of it, as follows $var1 = &$var2

53) Will a comparison of an integer 12 and a string "13" work in PHP?

"13" and 12 can be compared in PHP since it casts everything to the


integer type.

54) What are the data types of PHP? How is it possible to cast types in
PHP? What is a numeric array? What function do we use to find length of string, and
length of array?

Integers, Doubles, Booleans, Arrays, Objects, NULL, Strings.

The name of the output type has to be specified in parentheses before the
variable which is to be cast as follows:

* (int), (integer) - cast to integer

* (bool), (boolean) - cast to boolean

* (float), (double), (real) - cast to float

* (string) - cast to string

* (array) - cast to array

* (object) - cast to object

Numeric array − An array with a numeric index. The values are stored and accessed in a
linear fashion.

For finding a length of string we apply strlen() function and for array we use count() function.

55) When is a conditional statement ended with endif?

When the original if was followed by: and then the code block without
braces.

56) How is the ternary conditional operator used in PHP?


It is composed of three expressions: a condition, and two operands
describing what instruction should be performed when the specified
condition is true or false as follows:

Expression_1?Expression_2 : Expression_3;

57) What is the function func_num_args() used for?

The function func_num_args() is used to give the number of parameters


passed into a function.

58) If the variable $var1 is set to 10 and the $var2 is set to the
character var1, what's the value of $$var2?

$$var2 contains the value 10.

59) What does accessing a class via :: means?

:: is used to access static methods that do not require object initialization.

60) In PHP, objects are they passed by value or by reference?

In PHP, objects passed by value.

61) Are Parent constructors called implicitly inside a class


constructor?

No, a parent constructor have to be called explicitly as follows:

parent::constructor($value)

62) What's the difference between __sleep and __wakeup?

__sleep returns the array of all the variables that need to be saved, while
__wakeup retrieves them.

63) What is faster?

1- Combining two variables as follows:

$variable1 = 'Hello ';

$variable2 = 'World';

$variable3 = $variable1.$variable2;
Or

2- $variable3 = "$variable1$variable2";

$variable3 will contain "Hello World". The first code is faster than the
second code especially for large large sets of data.

64) What is session and why do we use it? what is the definition of a
session?

A session is a super global variable that preserves data across subsequent pages. Session
uniquely defines all users with a session ID. So it supports building a customized web
application where user tracking is required.

A session is a logical object enabling us to preserve temporary data across


multiple PHP pages.

65) How to initiate a session in PHP?

The use of the function session_start() lets us activating a session.

66) How can you propagate a session id?

You can propagate a session id via cookies or URL parameters.

67) What is cookie and why do we use it? How to Retrieve a Cookie Value? What is
the meaning of a Persistent Cookie?

A cookie is a small piece of information stored in a client browser. It is a technique utilized to


identify a user using the information stored in their browser. Utilizing PHP, we can both set
and get COOKIE.

Retrieve a cookie value: Ex: echo $_COOKIE[“user”]

A persistent cookie is permanently stored in a cookie file on the browser's


computer. By default, cookies are temporary and are erased if we close the
browser.

68) When do sessions end?

Sessions automatically end when the PHP script finishes executing but can
be manually ended using the session_write_close().

69) What is the difference between session_unregister() and


session_unset()?
The session_unregister() function unregister a global variable from the
current session and the session_unset() function frees all session
variables.

70) What does $GLOBALS mean?

$GLOBALS is associative array including references to all variables which


are currently defined in the global scope of the script.

71) What does $_SERVER mean? What is the default page in web server?

$_SERVER is an array including information created by the web server


such as paths, headers, and script locations.

Most of the times default page will be index page.

72) What does $_FILES means?

$_FILES is an associative array composed of items sent to the current


script via the HTTP POST method.

73) What is the difference between $_FILES['userfile']['name'] and


$_FILES['userfile']['tmp_name']?

$_FILES['userfile']['name'] represents the original name of the file on the


client machine,

$_FILES['userfile']['tmp_name'] represents the temporary filename of the


file stored on the server.

74) How can we get the error when there is a problem to upload a file?

$_FILES['userfile']['error'] contains the error code associated with the


uploaded file.

75) How can we change the maximum size of the files to be uploaded?

We can change the maximum size of files to be uploaded by changing


upload_max_filesize in php.ini.

76) What does $_ENV mean?

$_ENV is an associative array of variables sent to the current PHP script


via the environment method.

77) What does $_COOKIE mean?


$_COOKIE is an associative array of variables sent to the current PHP
script using the HTTP Cookies.

78) What does the scope of variables mean?

The scope of a variable is the context within which it is defined. For the
most part, all PHP variables only have a single scope. This single scope
spans included and required files as well.

79) what the difference between the 'BITWISE AND' operator and the
'LOGICAL AND' operator?

$a and $b: TRUE if both $a and $b are TRUE.

$a & $b: Bits that are set in both $a and $b are set.

80) What are the two main string operators?

The first is the concatenation operator ('.'), which returns the concatenation
of its right and left arguments. The second is ('.='), which appends the
argument on the right to the argument on the left.

81) What does the array operator '===' means?

$a === $b TRUE if $a and $b have the same key/value pairs in the same
order and of the same types.

82) What is the differences between $a != $b and $a !== $b?

!= means inequality (TRUE if $a is not equal to $b) and !== means non-
identity (TRUE if $a is not identical to $b).

83) How can we determine whether a PHP variable is an instantiated


object of a certain class?

To be able to verify whether a PHP variable is an instantiated object of a


certain class we use instanceof.

84) What is the goto statement useful for?

The goto statement can be placed to enable jumping inside the PHP
program. The target is pointed by a label followed by a colon, and the
instruction is specified as a goto statement followed by the desired target
label.
85) what is the difference between Exception::getMessage and
Exception:: getLine?

Exception::getMessage lets us getting the Exception message and


Exception::getLine lets us getting the line in which the exception occurred.

86) What does the expression Exception::__toString means?

Exception::__toString gives the String representation of the exception.

87) How is it possible to parse a configuration file?

The function parse_ini_file() enables us to load in the ini file specified in


filename and returns the settings in it in an associative array.

88) How can we determine whether a variable is set? What is NULL?

The boolean function isset determines if a variable is set and is not NULL.

NULL is a particular type which contains only one value: NULL. If you need any variable to
set NULL, just assign it.

89) What is the difference between the functions strstr() and stristr()?

The string function strstr(string allString, string occ) returns part of allString
from the first occurrence of occ to the end of allString. This function is case-
sensitive. stristr() is identical to strstr() except that it is case insensitive.

90) What types of loops exist in PHP? what is the difference between for and
foreach?

for, while, do while and foreach.

for is expressed as follows:

for (expr1; expr2; expr3)

statement

The first expression is executed once at the beginning. In each iteration,


expr2 is evaluated. If it is TRUE, the loop continues, and the statements
inside for are executed. If it evaluates to FALSE, the execution of the loop
ends. expr3 is tested at the end of each iteration.

However, foreach provides an easy way to iterate over arrays, and it is only
used with arrays and objects.
91) Is it possible to or how submit a form with a dedicated button?

It is possible to use the document.form.submit() function to submit the form.


For example: <input type=button value="SUBMIT"
onClick="document.form.submit()">

92) What is the difference between ereg_replace() and


eregi_replace()?

The function eregi_replace() is identical to the function ereg_replace()


except that it ignores case distinction when matching alphabetic characters.

93) Is it possible to protect special characters in a query string?

Yes, we use the urlencode() function to be able to protect special


characters.

94) What are the three classes of errors that can occur in PHP?

The three basic classes of errors are notices (non-critical), warnings


(serious errors) and fatal errors (critical errors).

95) What is the difference between characters \034 and \x34?

\034 is octal 34 and \x34 is hex 34.

96) How can we pass the variable through the navigation between the
pages?

It is possible to pass the variables between the PHP pages using sessions,
cookies or hidden form fields.

97) How can you break PHP script? Is it possible to extend the execution
time of a PHP script?

I can use exit() function for that.

The use of the set_time_limit(int seconds) enables us to extend the


execution time of a PHP script. The default limit is 30 seconds.

98) Is it possible to destroy a cookie or How to destroy a cookie in PHP?

There is not a way to directly delete a cookie. Just use the setcookie function with the
expiration date in the past, to trigger the removal mechanism in your web browser.

99) What is the default session time in PHP?


The default session time in php is until the closing of the browser

100) Is it possible to use COM component in PHP?

Yes, it's possible to integrate (Distributed) Component Object Model


components ((D)COM) in PHP scripts which is provided as a framework.

101) Explain whether it is possible to share a single instance of a


Memcache between multiple PHP projects?

Yes, it is possible to share a single instance of Memcache between multiple


projects. Memcache is a memory store space, and you can run memcache
on one or more servers. You can also configure your client to speak to a
particular set of instances. So, you can run two different Memcache
processes on the same host and yet they are completely independent.
Unless, if you have partitioned your data, then it becomes necessary to
know from which instance to get the data from or to put into.

102) Explain how you can update Memcached when you make
changes to PHP?

When PHP changes you can update Memcached by

 Clearing the Cache proactively: Clearing the cache when an insert


or update is made
 Resetting the Cache: It is similar to the first method but rather than
just deleting the keys and waiting for the next request for the data to
refresh the cache, reset the values after the insert or update.

103) What is the difference between ID and class in CSS?


The difference between an ID and Class is that an ID can be utilized to identify one
element, whereas a class can be used to identify more than one.

104) What is AJAX?


AJAX (Asynchronous JavaScript and XML) is a technique which enables updating
parts of a web page, without reloading the entire page. Data is exchanged
asynchronously in a small amount of data with the server.

105) What is jQuery?


jQuery is a fast, small, and feature-rich JavaScript library. It is an easy-to-use API. It
makes things like HTML document traversal and manipulation, animation, event
handling and Ajax much simpler across a more number of browsers.

106) What is the difference between SQL and Mysql?


SQL(Structured Query Language) is a programming language created for managing
data held in a Relational Database Management System. Mysql is an open source,
relational database management System.

107) What is JOIN in MySQL? What are the different types of join?

MySQL JOINS are utilized to retrieve data from multiple tables. It is performed
whenever two or more tables are joined in a SQL statement. There are various types
of MySQL joins: INNER JOIN, LEFT JOIN, RIGHT JOIN and OUTER JOIN.

108) How to send a mail in PHP?

You can send an e-mail in PHP with mail() function or SMTP details.

109) How to declare an array in PHP?

Ex: var $arr = array(‘apple’, ‘grape’, ‘lemon’);

110) What is the use of ‘print’ in PHP?

It is not actually a real function, it is a language construct. So you can utilize without
parentheses with its argument list.

111) What is SQL injection?

SQL injection is a malicious code injection technique that might destroy your
database. It exploiting SQL vulnerabilities in Web applications. It is one of the most
common web hacking techniques.
What is PHP?

PHP is an open source server side scripting language commonly used for web applications.

What is Open Source Software?

Software in which the source codes are freely used, modify, and shared by anyone are called Open
Source Software. These can also be distributed under licenses that adhere with the Open Source
Definition.

What is the difference between include(), include_once() and require_once()

The include() statement includes and evaluates a specified line i.e. it will include a file based in the
given path. require() does the same thing expect upon failure it will generate a fatal error and halt the
script whereas include() will just gives a warning and allow script to continue. require_once() will check
if the file already has been included and if so it will not include the file again.

Differences between GET, POST and REQUEST methods ?

GET and POST are used to send information from client browser to web server. In case of GET the
information is send via GET method in name/value pair and is URL encoded. The default GET has a
limit of 512 characters. The POST method transfers the information via HTTP Headers. The POST
method does not have any restriction in data size to be sent. POST is used for sending data securely
and ASCII and binary type’s data. The $_REQUEST contains the content of both $_GET, $_POST
and $_COOKIE.

What are the different errors in PHP?

There are 4 basically types of error.

Parse Error – Commonly caused due to syntax mistakes in codes e.g. missing semicolon, mismatch
brackets.

Fatal Error – These are basically run time errors which are caused when you try to access what can’t
be done. E.g. accessing a dead object, or trying to use a function that hasn’t been declared.

Warning Error – These occurs when u try to include a file that is not present, or delete a file that is
not on the server. This will not halt the script; it will give the notice and continue with the next line of
the script.

Notice Error – These errors occurs when u try to use a variable that hasn’t been declared, this will not
halt the script, It will give the notice and continue with the next line of the script.

What is session and why do we use it?

Session is a super global variable that preserve data across subsequent pages. Session uniquely
defines each user with a session ID, so it helps making customized web application where user
tracking is needed.

What is cookie and why do we use it?

Cookie is a small piece of information stored in client browser. It is a technique used to identify a user
using the information stored in their browser (if already visited that website) . Using PHP we can both
set and get COOKIE.

How to print current date and time.


2
3 <?php echo date('Y-m-d H:i:s'); ?>
What function do we use to find length of string, and length of array?

For finding length of string we use strlen() function and for array we use count() function.

How can we change the value of a constant?

We cannot change the value of a constant.

What is the difference between unset() and unlink() function.

unset() is used to destroy a variable where as unlink() is used to destroy a file.

How do we get the current session ID?

2
3 <?php
4 session_start();
5 echo session_id();
6 ?>
How do we destroy a session.

2
3 <?php session_start(); session_destroy(); ?>
What is the difference between explode() and split() functions?

Both are used to split a string to array, the basic difference is that split() uses pattern for splitting
and explode()uses a string. explode() is faster than split() as it does not match the string based on
regular expression. Also split() is deprecated as of 5.3.0. So using of this function is discouraged.

What is an associative array?

Associative arrays are arrays that use named keys that you assign to them.
2
3 <?php
4 $capitals=array("India"=>"New Delhi","China"=>"Beijing","Pakistan"=>"Islamabad");
5 ?>
What is PDO classes?

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing
databases in PHP. It is a data-access abstraction layer, so no matter what database we use the
function to issue queries and fetch data will be same. Using PDO drivers we can connect to database
like DB2, Oracle, PostgreSQL etc.

What is the difference between javascript and PHP?

Javascript is a client side scripting language whereas PHP is a server side scripting language.

What is CSS?

CSS or cascading Style Sheet is a way to style and present HTML.

What is the difference between ID and class in CSS?

The difference between an ID and Class is that an ID can be used to identify one element, whereas a
class can be used to identify more than one.

How can we submit a form without using submit buttons?

We can use javascript submit function. We can either use form name or form id to print

2
3 document.getElementById("formID").submit();
4 document.formname.submit();
Why do we use multipart/form-data in html form?

This is the encoding used to send image or files via form, The data will be split into multiple parts and,
one for each files plus one for the text of the form body that may be sent with them.

What is AJAX?

AJAX (Asynchronous JavaScript and XML) is a technique which allows updating parts of a web page,
without reloading the whole page. Data is exchanged asynchronously in small amounts of data with
the server.

What is jQuery?
jQuery is a fast, small, and feature-rich JavaScript library. It is an easy-to-use API which makes things
like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler
across a multitude of browsers.

How can we show and hide an element via jquery?

Suppose we want to show and hide elements of a div with id div1.

2
3 // show div
4 $('#div1').show();
5 // hide div
6 $('#div1').hide();
How can we add change font size using jquery?

Suppose we want change a font size of and div with id div1 from 12px to 18px.

2
3 $('#div1').css('font-size', '18px');
What is the difference between sql and Mysql?

SQL or Structured Query Language is a programming language designed for managing data held in a
Relational Database Management System. Mysql is a open source, relational database management
System.

Why do we use GROUP BY and ORDER BY function in mysql?

Group By is used for retrieving information about a group of data. It is generally used with some
aggregate function like SUM, AVG etc. ORDER BY is used to sort the records using column name. It
can sort column in both ascending and descending order.

What is JOIN in mysql? What are the different types of join?

When we have to fetch records from more than one table we can use JOIN keyword. The process is
known as joining the tables. There are various types of join like INNER JOIN, LEFT JOIN, RIGHT
JOIN, and OUTER JOIN.

Why is the basic difference between LEFT JOIN, RIGHT JOIN and INNER JOIN?

INNER Join compares two tables and only returns results where a match exists. Records from the 1st
table are duplicated when they match multiple results in the 2nd. INNER joins tend to make result sets
smaller, but because records can be duplicated this isn’t guaranteed.

LEFT join means keep all records from the 1st table no matter what and insert NULL values when the
2nd table doesn’t match.
RIGHT Join means the opposite: keep all records from the 2nd table no matter what and insert NULL
values when the 1st table doesn’t match.

If we use SUM function in mysql, does it return sum of that row or for that column?

Sum function works on the column basis and will return the sum of that particular row only.

What do we use to remove duplicate records while fetching a data in mysql ?

We use DISTINCT keyword.

What is the use of count function in mysql?

count() is used for fetching the total number records in a table.

How do we use % when performing a search query?

Suppose take an example where you need to fetch all customer data where name stats with sa

SELECT * FROM Customers WHERE name LIKE ‘sa%’;

Another case is where you need to fetch all customer data where kumar is found irrespective of the
position (middle name or last name).

SELECT * FROM Customers WHERE name LIKE ‘%kumar%’;

How do we delete a row in a table?

Take an example

DELETE FROM customer WHERE cid=150;

In this case it will delete the record of the customer with customer id 150

How do we drop a table?

DROP table customers;

It will drop the table customers

1. Who is the father of PHP ?


Rasmus Lerdorf is known as the father of PHP.

2. What is the difference between $name and $$name?


$name is variable where as $$name is reference variable like $name=sonia and $$name=singh so
$sonia value is singh.

3. What are the method available in form submitting?

GET and POST


4.How can we get the browser properties using PHP?

<?php

echo $_SERVER[‘HTTP_USER_AGENT’].”\n\n”;
$browser=get_browser(null,true);
print_r($browser);
?>

5. What Is a Session?

A session is a logical object created by the PHP engine to allow you to preserve data across
subsequent HTTP requests. Sessions are commonly used to store temporary data to allow multiple
PHP pages to offer a complete functional transaction for the same visitor.

6. How can we register the variables into a session?

<?php
session_register($ur_session_var);
?>

7. How many ways we can pass the variable through the navigation between the pages?

Register the variable into the session


Pass the variable as a cookie
Pass the variable as part of the URL

8. How can we know the total number of elements of Array?

sizeof($array_var)
count($array_var)

9. How can we create a database using php?

mysql_create_db();

10. What is the functionality of the function strstr and stristr?

strstr() returns part of a given string from the first occurrence of a given substring to the end of
the string.
For example:strstr("user@example.com","@") will return "@example.com".
stristr() is idential to strstr() except that it is case insensitive.

11. What are encryption functions in PHP?


CRYPT(), MD5()

12. How to store the uploaded file to the final location?

move_uploaded_file( string filename, string destination)

13. Explain mysql_error().

The mysql_error() message will tell us what was wrong with our query, similar to the message we
would receive at the MySQL console.

14. What is Constructors and Destructors?

CONSTRUCTOR : PHP allows developers to declare constructor methods for classes. Classes which
have a constructor method call this method on each newly-created object, so it is suitable for any
initialization that the object may need before it is used.
DESTRUCTORS : PHP 5 introduces a destructor concept similar to that of other object-oriented
languages, such as C++. The destructor method will be called as soon as all references to a
particular object are removed or when the object is explicitly destroyed or in any order in
shutdown sequence.

15. Explain the visibility of the property or method.

The visibility of a property or method must be defined by prefixing the declaration with the
keywords public, protected or private.
Class members declared public can be accessed everywhere.
Members declared protected can be accessed only within the class itself and by inherited and
parent classes.
Members declared as private may only be accessed by the class that defines the member.

16. What are the differences between Get and post methods.

There are some defference between GET and POST method


1. GET Method have some limit like only 2Kb data able to send for request
But in POST method unlimited data can we send
2. when we use GET method requested data show in url but
Not in POST method so POST method is good for send sensetive request

17. What are the differences between require and include?

Both include and require used to include a file but when included file not found
Include send Warning where as Require send Fatal Error

18. What is use of header() function in php ?

The header() function sends a raw HTTP header to a client.We can use herder()
function for redirection of pages. It is important to notice that header() must
be called before any actual output is seen.
19. List out the predefined classes in PHP?

Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter

20. What type of inheritance that PHP supports?

In PHP an extended class is always dependent on a single base class,that is, multiple inheritance is
not supported. Classes are extended using the keyword 'extends'.

21. How can we encrypt the username and password using php?

You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD("Password");


We can encode data using base64_encode($string) and can decode using base64_decode($string);

22. What is the difference between explode and split?

Split function splits string into array by regular expression. Explode splits a string into array by
string.
For Example:explode(" and", "India and Pakistan and Srilanka");
split(" :", "India : Pakistan : Srilanka");
Both of these functions will return an array that contains India, Pakistan, and Srilanka.

23. How do you define a constant?

Constants in PHP are defined using define() directive, like define("MYCONSTANT", 100);

24. How do you pass a variable by value in PHP?

Just like in C++, put an ampersand in front of it, like $a = &$b;

25. What does a special set of tags <?= and ?> do in PHP?

The output is displayed directly to the browser.

26. How do you call a constructor for a parent class?

parent::constructor($value)

27. What’s the special meaning of __sleep and __wakeup?

__sleep returns the array of all the variables than need to be saved, while __wakeup retrieves
them.

28. What is the difference between PHP and JavaScript?


javascript is a client side scripting language, so javascript can make popups and other things
happens on someone’s PC. While PHP is server side scripting language so it does every stuff with
the server.

29. What is the difference between the functions unlink and unset?

unlink() deletes the given file from the file system.


unset() makes a variable undefined.

30. How many ways can we get the value of current session id?

session_id() returns the session id for the current session.

31. What are default session time and path?

default session time in PHP is 1440 seconds or 24 minutes


Default session save path id temporary folder /tmp

32. for image work which library?

we will need to compile PHP with the GD library of image functions for this to work. GD and PHP
may also require other libraries, depending on which image formats you want to work with.

33. How can we get second of the current time using date function?

<?php
$second = date(“s”);
?>

34. What are the Formatting and Printing Strings available in PHP?

printf()- Displays a formatted string


sprintf()-Saves a formatted string in a variable
fprintf() -Prints a formatted string to a file
number_format()-Formats numbers as strings

35. How can we find the number of rows in a result set using PHP?

$result = mysql_query($sql, $db_link);


$num_rows = mysql_num_rows($result);
echo "$num_rows rows found";

Q #1) What is PHP?


Answer:
PHP is one of the popular server-side scripting languages for developing a web
application.

The full form of PHP is Hypertext Preprocessor. It is used by embedding HTML for
creating dynamic content, communicating with a database server, handling session etc.
Q #2) Why do we use PHP?
Answer:
There are several benefits of using PHP. First of all, it is totally free to use. So anyone
can use PHP without any cost and host the site at a minimal cost.

It supports multiple databases. The most commonly used database is MySQL which is
also free to use. Many PHP frameworks are used now for web development, such as
CodeIgniter, CakePHP, Laravel etc.

These frameworks make the web development task much easier than before.

Q #3) Is PHP a strongly typed language?


Answer:
No. PHP is a weakly typed or loosely typed language.

Which means PHP does not require to declare data types of the variable when you
declare any variable like the other standard programming languages C# or Java. When
you store any string value in a variable then the data type is the string and if you store a
numeric value in that same variable then the data type is an Integer.

Sample code:
1 $var = "Hello"; //String
2 $var = 10; //Integer
Q #4) What is meant by variable variables in PHP?
Answer:
When the value of a variable is used as the name of the other variables then it is called
variable variables. $$ is used to declare variable variables in PHP.

Sample code:
1 $str = "PHP";
2 $$str = " Programming"; //declaring variable variables
3 echo "$str ${$str}"; //It will print "PHP programming"
4 echo "$PHP"; //It will print "Programming"
Q #5) What are the differences between echo and print?
Answer:
Both echo and print method print the output in the browser but there is a difference
between these two methods.
echo does not return any value after printing the output and it works faster than the print
method. print method is slower than the echo because it returns boolean value after
printing the output.
Sample code:
1 echo "PHP Developer";
2 $n = print "Java Developer";
Q #6) How can you execute PHP script from the command line?
Answer:
You have to use PHP command in the command line to execute a PHP script. If the
PHP file name is test.php then the following command is used to run the script from the
command line.
php test.php

Q #7) How can you declare the array in PHP?


Answer:
You can declare three types of arrays in PHP. They are numeric,
associative and multidimensionalarrays.
Sample code:

1 //Numeric Array
2 $computer = array("Dell", "Lenavo", "HP");
3 //Associative Array
4 $color = array("Sithi"=>"Red", "Amit"=>"Blue", "Mahek"=>"Green");
5 //Multidimensional Array

6 $courses = array ( array("PHP",50), array("JQuery",15), array("AngularJS"


,20) );
Q #8) What are the uses of explode() and implode() functions?
Answer:
explode() function is used to split a string into an array and implode() function is used
to make a string by combining the array elements.
Sample code:
1 $text = "I like programming";
2 print_r (explode(" ",$text));
3 $strarr = array('Pen','Pencil','Eraser');
4 echo implode(" ",$strarr);
Q #9) Which function can be used to exit from the script after displaying the error
message?
Answer:
You can use exit() or die() function to exit from the current script after displaying the
error message.
Sample code:
1 if(!fopen('t.txt','r'))
2 exit(" Unable to open the file");
Sample code:
1 if(!mysqli_connect('localhost','user','password'))
2 die(" Unable to connect with the database");
Q #10) Which function is used in PHP to check the data type of any variable?
Answer:
gettype() function is used to check the data type of any variable.

Sample code:
1 echo gettype(true).''; //boolean
2 echo gettype(10).''; //integer
3 echo gettype('Web Programming').''; //string
4 echo gettype(null).''; //NULL
Q #11) How can you increase the maximum execution time of a script in PHP?
Answer:
You need to change the value of the max_execution_time directive in the php.ini file
for increasing the maximum execution time.
For Example, if you want to set the max execution time for 120 seconds, then set the
value as follows,
1 max_execution_time = 120
Q #12) What is meant by ‘passing the variable by value and reference' in PHP?
Answer:
When the variable is passed as value then it is called pass variable by value.
Here, the main variable remains unchanged even when the passed variable changes.

Sample code:
1 function test($n) {
2 $n=$n+10;
3}
4
5 $m=5;
6 test($m);
7 echo $m;
When the variable is passed as a reference then it is called pass variable by
reference. Here, both the main variable and the passed variable share the same
memory location and & is used for reference.
So, if one variable changes then the other will also change.

Sample code:
1 function test(&$n) {
2 $n=$n+10;
3}
4 $m=5;
5 test($m);
6 echo $m;
Q #13) Explain type casting and type juggling.
Answer:
The way by which PHP can assign a particular data type for any variable is called
typecasting. The required type of variable is mentioned in the parenthesis before the
variable.

Sample code:
1 $str = "10"; // $str is now string
2 $bool = (boolean) $str; // $bool is now boolean
PHP does not support data type for variable declaration. The type of the variable is
changed automatically based on the assigned value and it is called type juggling.

Sample code:
1 $val = 5; // $val is now number
2 $val = "500" //$val is now string
Q #14) How can you make a connection with MySQL server using PHP?
Answer:
You have to provide MySQL hostname, username and password to make a connection
with the MySQL server in mysqli_connect() method or declaring database object of the
mysqli class.
Sample code:
1 $mysqli = mysqli_connect("localhost","username","password");
2 $mysqli = new mysqli("localhost","username","password");
Q #15) How can you retrieve data from the MySQL database using PHP?
Answer:
Many functions are available in PHP to retrieve the data from the MySQL database.

Few functions are mentioned below:


mysqli_fetch_array() – It is used to fetch the records as a numeric array or an
associative array.
Sample code:
1 // Associative or Numeric array
2 $result=mysqli_query($DBconnection,$query);
3 $row=mysqli_fetch_array($result,MYSQLI_ASSOC);
4 echo "Name is $row[0]
5 ";
6 echo "Email is $row['email']
7 ";
mysqli_fetch_row() – It is used to fetch the records in a numeric array.
Sample code:
1 //Numeric array
2 $result=mysqli_query($DBconnection,$query);
3 $row=mysqli_fetch_array($result);
4 printf ("%s %s\n",$row[0],$row[1]);
mysqli_fetch_assoc() – It is used to fetch the records in an associative array.
Sample code:
1 // Associative array
2 $result=mysqli_query($DBconnection,$query);
3 $row=mysqli_fetch_array($result);
4 printf ("%s %s\n",$row["name"],$row["email"]);
mysqli_fetch_object() – It is used to fetch the records as an object.
Sample code:
1 // Object
2 $result=mysqli_query($DBconnection,$query);
3 $row=mysqli_fetch_array($result);
4 printf ("%s %s\n",$row->name,$row->email);
Q #16) What are the differences between mysqli_connect and mysqli_pconnect?
Answer:
mysqli_pconnect() function is used for making a persistence connection with the
database that does not terminate when the script ends.
mysqli_connect() function searches any existing persistence connection first and if no
persistence connection exists, then it will create a new database connection and
terminate the connection at the end of the script.
Sample code:
1 $DBconnection =
mysqli_connect("localhost","username","password","dbname");
2 // Check for valid connection
3 if (mysqli_connect_errno())
4{
5 echo "Unable to connect with MySQL: " . mysqli_connect_error();
6}
mysqli_pconnect() function is depreciated in the new version of PHP, but you can
create persistence connection using mysqli_connect with the prefix p.
Q #17) Which function is used in PHP to count the total number of rows returned
by any query?
Answer:
mysqli_num_rows() function is used to count the total number of rows returned by the
query.
Sample code:
1 $mysqli = mysqli_connect("hostname","username","password","DBname");
2 $result=mysqli_query($mysqli,"select * from employees");
3 $count=mysqli_num_rows($result);
Q #18) How can you create a session in PHP?
Answer:
session_start() function is used in PHP to create a session.
Sample code:
1 session_start(); //Start session
2 $_SESSION['USERNAME']='Fahmida'; //Set a session value
3 unset($_SESSION['USERNAME']; //delete session value
Q #19) What is the use of imagetypes() method?
Answer:
image types() function returns the list of supported images of the installed PHP version.
You can use this function to check if a particular image extension is supported by PHP
or not.
Sample code:
1 //Check BMP extension is supported by PHP or not
2 if (imagetypes() &IMG_BMP) {
3 echo "BMP extension Support is enabled";
4}
Q #20) Which function you can use in PHP to open a file for reading or writing or
for both?
Answer:
You can use fopen() function to read or write or for doing both in PHP.
Sample code:
1 $file1 = fopen("myfile1.txt","r"); //Open for reading
2 $file2 = fopen("myfile2.txt","w"); //Open for writing
3 $file3 = fopen("myfile3.txt","r+"); //Open for reading and writing
Q #21) What is the difference between include() and require()?
Answer:
Both include() and require() function are used for including PHP script from one file to
another file. But there is a difference between these functions.
If any error occurs at the time of including a file using include() function, then it
continues the execution of the script after showing an error message. require() function
stops the execution of a script by displaying an error message if an error occurs.
Sample code:
1 if (!include(‘test.php’)) echo “Error in file inclusion”;
2 if (!require(‘test.php’)) echo “Error in file inclusion”;
Q #22) Which function is used in PHP to delete a file?
Answer:
unlink() function is used in PHP to delete any file.
Sample code:
1 unlink('filename');
Q #23) What is the use of strip_tags() method?
Answer:
strip_tags() function is used to retrieve the string from a text by omitting HTML, XML
and PHP tags. This function has one mandatory parameter and one optional parameter.
The optional parameter is used to accept particular tags.
Sample code:
1 //Remove all tags from the text
2 echo strip_tags("<b>PHP</b> is a popular <em>scripting</em> language");
3 //Remove all tags excluding <b> tag

4 echo strip_tags("<b>PHP</b> is a popular <em>scripting</em>


language","<b>");
Q #24) How can you send HTTP header to the client in PHP?
Answer:
header() function is used to send raw HTTP header to a client before any output is sent.
Sample code:
1 header('Location: http://www.your_domain/');
Q #25) Which functions are used to count the total number of array elements in
PHP?
Answer:
count() and sizeof() functions can be used to count the total number of array elements
in PHP.
Sample code:
1 $names=array(“Asa”,”Prinka”,”Abhijeet”);
2 echo count($names);
3 $marks=array(95,70,87);
4 echo sizeof($marks);
Q #26) What is the difference between substr() and strstr()?
Answer:
substr() function returns a part of the string based on the starting point and length.
Length parameter is optional for this function and if it is omitted then the remaining part
of the string from the starting point will be returned.
strstr() function searches the first occurrence of a string inside another string. The third
parameter of this function is optional and it is used to retrieve the part of the string that
appears before the first occurrence of the searching string.
Sample code:
1 echo substr("Computer Programming",9,7); //Returns “Program”
2 echo substr("Computer Programming",9); //Returns “Programming”
Sample code:
1 echo strstr("Learning Laravel 5!","Laravel"); //Returns Laravel 5!
2 echo strstr("Learning Laravel 5!","Laravel",true); //Returns Learning
Q #27) How can you upload a file using PHP?
Answer:
To upload a file by using PHP, you have to do the following tasks.

#1) Enable file_uploads directive


Open php.ini file and find out the file_uploads directive and make it on.

1 file_uploads = On
#2) Create an HTML form using enctype attribute and file element for uploading the file.
<form action="upload.php" method="post" enctype="multipart/form-data">

<input type="file" name="upd" id="upd">

<input type="submit" value="Upload" name="upload">

</form>

#3) Write PHP script to upload the file


1 if (move_uploaded_file($_FILES["upd"]["tmp_name"], "Uploads/")) {
2 echo "The file ". basename( $_FILES["upd"]["name"]). " is uploaded.";
3 } else {
4 echo "There is an error in uploading.";
5}
Q #28) How can you declare a constant variable in PHP?
Answer:
define() function is used to declare a constant variable in PHP. Constant variable
declares without the $ symbol.
Sample code:
1 define("PI",3.14);
Q #29) Which function is used in PHP to search a particular value in an array?
Answer:
in_array() function is used to search a particular value in an array.
Sample code:
1 $languages = array("C#", "Java", "PHP", "VB.Net");
2 if (in_array("PHP", $languages)) {
3 echo "PHP is in the list";
4}
5 else {
6 echo "php is not in the list";
7}
Q #30) What is the use of $_REQUEST variable?
Answer:
The $_REQUEST variable is used to read the data from the submitted HTML form.
Sample code:
Here, the $_REQUEST variable is used to read the submitted form field with the name
‘username’. If the form is submitted without any value, then it will print as “Name is
empty”, otherwise it will print the submitted value.
1 <?php
2 if (isset($_POST['submit'])) {
3 // collect value of input field
4 $name = $_REQUEST['username'];
5 if (empty($name)) {
6 echo "Name is empty";
7 } else {
8 echo $name;
9 }
10 }
11 else
12 {
13 ?>
14 <form method="post" action="#">
15 Name: <input type="text" name="username">
16 <input type="submit" name="submit">
17 </form>
18 <?php } ?>
Q #31) What is the difference between for and foreach loop in PHP?
Answer:
for loop is mainly used for iterating a pre-defined number of times and foreach loop is
used for reading array elements or MySQL result set where the number of iteration can
be unknown.
Sample code:
1 //Loop will iterate for 5 times
2 for ($n = 0; $n <= 5; $n++) {
3 echo "The number is: $n <br>";
4}
Sample code:
1 //Loop will iterate based on array elements
2 $parts = array("HDD", "Monitor", "Mouse", "Keyboard");
3 foreach ($parts as $value) {
4 echo "$value <br>";
5}
6 </pre>
<span style="color: #ff6600;"><strong>Q #32) How long does a PHP session
7
last for?</strong></span>
8
<strong>Answer:</strong> By default, session data will last for 24
9
minutes or 1440 seconds in PHP. But if you want, you can change the
duration by modifying the value of <strong>gc_maxlifetime
directive</strong> in php.ini file.
10
To set the session time for 30 minutes, open php.ini file and set the
11
value of <strong>gc_maxlifetime</strong> directive as follows,
12
13 <strong>gc_maxlifetime = 1800</strong>
14
<strong><span style="color: #ff6600;"><strong>Q #33) What is the
15
difference between “= =” and “= = =” operators.</strong></span></strong>
16
17 <strong><strong>Answer:</strong></strong>
18
“= =” is called an equivalent operator that is used to check only the
19
equivalency of two values but not the data types.
20
<span style="text-decoration: underline;"><strong>Sample
21
code:</strong></span>
22
10 and “10” are equivalent by values. So, if condition will be
23
true and print “n, is equal to 10”.
24 <pre>$n = 10;
25 if ($n == "10")
26 echo "n is equal to 10"; //This will print
27
28 else
29 echo "n is not equal to 10";
“= = =” is called strictly equivalent operator that is used to check the equivalency of two
values by comparing both data types and values.

Sample code:
10 and “10” are equal by values but are not equal by data type. One is a string and one
is a number. So, if condition will be false and print “n is not equal to 10”.

1 $n = 10;
2 if ($n === "10")
3 echo "n is equal to 10";
4 else
5 echo "n is not equal to 10"; //This will print
Q #34) Which operator is used to combine string values in PHP?
Answer:
Two or more string values can be combined by using ‘.’ operator.

Sample code:
1 $val1 = "Software ";
2 $val2 = "Testing";
3 echo $val1.$val2; // The output is “Software Testing”
Q #35) What is PEAR?
Answer:
The full form of PEAR is “PHP Extension and Application Repository”.
Anyone can download reusable PHP components by using this framework at a free of
cost. It contains different types of packages from different developers.

Website: PEAR
Q #36) What type of errors can be occurred in PHP?
Answer:
Different type of errors can occur in PHP.

Some major error types are mentioned below:


Fatal Errors– The execution of the script stops when this error occurs.
Sample code:
In the following script, f1() function is declared but f2() function is called which is not
declared. The execution of the script will stop when f2() function will call. So, “Testing
Fatal Error” will not be printed.
1 function f1()
2 { echo "function 1";
3}
4 f2();
5 echo “Testing Fatal Error”;
Parse Errors– This type of error occurs when the coder uses a wrong syntax in the
script.
Sample code:
Here, semicolon(;) is missing at the end of the first echo statement.

1 echo "This is a testing script<br/>"


2 echo "error";
Warning Errors- This type of error does not stop the execution of a script. It continues
the script even after displaying the error.
Sample code:
In the following script, if the test.txt file does not exist in the current location then a
warning message will display to show the error and print “Opening File” text by
continuing the execution.
1 $handler = fopen("test.txt","r");
2 echo "Opening File";
Notice Errors- This type of error shows a minor error of the script and continues the
execution after displaying the error.
Here, the variable, $a is defined but $b is not defined. So, a notice of undefined variable
will display for “echo $b” statement and print “Checking notice error” by continuing the
script.
Sample code:
1 $a = 100;
2 echo $b;
3 echo "Checking notice error";
Q #37) Does PHP support multiple inheritances?
Answer:
PHP does not support multiple inheritances. To implement the features of multiple
inheritances, the interface is used in PHP.

Sample code:
Here, two interfaces, Isbn and Type are declared and implemented in a class, book
details to add the feature of multiple inheritances in PHP.
1 interface Isbn {
2 public function setISBN($isbn);
3}
4 interface Type{
5 public function setType($type);
6}
7 class bookDetails implements Isbn, Type {
8 private $isbn;
9 private $type;
10 public function setISBN($isbn)
11 {
12 $this -> isbn = $isbn;
13 }
14 public function setType($type)
15 {
16 $this -> type = $type;
17 }
18 }
Q #38) What are the differences between session and cookie?
Answer:
The session is a global variable which is used in the server to store the session data.
When a new session creates the cookie with the session id is stored on the visitor's
computer. The session variable can store more data than the cookie variable.

Session data are stored in a $_SESSION array and Cookie data are stored in a
$_COOKIE array. Session values are removed automatically when the visitor closes the
browser and cookie values are not removed automatically.

Q #39) What is the use of mysqli_real_escape_string() function?


Answer:
mysqli_real_escape_string() function is used to escape special characters from the
string for using a SQL statement

Sample code:
$DBconnection=mysqli_connect("localhost","username","password","dbname")
1
;
2 $productName = mysqli_real_escape_string($con, $_POST['proname']);
3 $ProductType = mysqli_real_escape_string($con, $_POST['protype']);
Q #40) Which functions are used to remove whitespaces from the string?
Answer:
There are three functions in PHP to remove the whitespaces from the string.

trim() – It removes whitespaces from the left and right side of the string.
ltrim() – It removes whitespaces from the from the left side of the string.
rtrim() – It removes whitespaces from the from the right side of the string.
Sample code:
1 $str = " Tutorials for your help";
2 $val1 = trim($str);
3 $val2 = ltrim($str);
4 $val3 = rtrim($str);
Q #41) What is a persistence cookie?
Answer:
A cookie file that is stored permanently in the browser is called a persistence cookie. It is
not secure and is mainly used for tracking a visitor for long times.

This type of cookie can be declared as follows,

setccookie ("cookie_name", "cookie_value", strtotime("+2 years");

Q #42) How can a cross-site scripting attack be prevented by PHP?


Answer:
Htmlentities() function of PHP can be used for preventing cross-site scripting attack.

Q #43) Which PHP global variable is used for uploading a file?


Answer:
$_FILE[] array contains all the information of an uploaded file.

The use of various indexes of this array is mentioned below:


$_FILES[$fieldName][‘name'] – Keeps the original file name.
$_FILES[$fieldName][‘type'] – Keeps the file type of an uploaded file.
$_FILES[$fieldName][‘size'] – Stores the file size in bytes.
$_FILES[$fieldName][‘tmp_name'] – Keeps the temporary file name which is used to
store the file in the server.
$_FILES[$fieldName][‘error'] – Contains error code related to the error that appears
during the upload.
Q #44) What is meant by public, private, protected, static and final scopes?
Answer:
 Public– Variables, classes, and methods which are declared public can be
accessed from anywhere.
 Private– Variables, classes and methods which are declared private can be
accessed by the parent class only.
 Protected– Variables, classes, and methods which are declared protected can
be accessed by the parent and child classes only.
 Static– The variable which is declared static can keep the value after losing the
scope.
 Final– This scope prevents the child class to declare the same item again.
Q #45) How can image properties be retrieved in PHP?
Answer:
getimagesize() – It is used to get the image size.
exif_imagetype() – It is used to get the image type.
imagesx() – It is used to get the image width.
imagesy() – It is used to get the image height.
Q #46) What is the difference between abstract class and interface?
Answer:
 Abstract classes are used for closely related objects and interfaces are used for
unrelated objects.
 PHP class can implement multiple interfaces but can’t inherit multiple abstract
classes.
 Common behavior can be implemented in the abstract class but not an interface.
Q #47) What is garbage collection?
Answer:
It is an automated feature of PHP.

When it runs, it removes all sessions data which are not accessed for a long time. It runs
on /tmp directory which is the default session directory.

PHP directives which are used for garbage collection include:


 session.gc_maxlifetime (default value, 1440)
 session.gc_probability (default value, 1)
 session.gc_divisor (default value, 100)
Q #48) Which library is used in PHP to do various types of Image work?
Answer:
Using GD library, various types of image work can be done in PHP. Image work includes
rotating image, cropping an image, creating image thumbnail etc.

Q #49) What is URL rewriting?


Answer:
Appending the session ID in every local URL of the requested page for keeping the
session information is called URL rewriting.

The disadvantages of this methods are, it doesn't allow persistence between the
sessions and, the user can easily copy and paste the URL and send to another user.

Q #50) What is PDO?


Answer:
The full form of PDO is PHP Data Objects.

It is a lightweight PHP extension that uses consistence interface for accessing the
database. Using PDO, a developer can easily switch from one database server to the
other. But it does not support all the advanced features of the new MySQL server.

Você também pode gostar