Php Interview Questions Answer


The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.
PHP means PHP: Hypertext Preprocessor.
PHP syntax resembles Perl and C
We can include a file using "include() " or "require()" function with file path as its parameter.
If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.
GET Method: get method is used for submitting small amount of data. Data shows in the URL, so it is not secure. POST Method: post method is used for submitting small amount of data. Data does not show URL, so it is secure.
The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user's computers in the text file format. Cookies can not hold multiple variables,But Session can hold multiple variables.We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking
Split function splits string into array by regular expression. Explode splits a string into array by string.
It is used to escapes special characters in a string for use in an SQL statement.
The header() function sends a raw HTTP header to a client browser.Remember that this function must be called before sending the actual out put.
exit() function is used to stop the execution of a page
This function is used to determine if a variable is set and is not NULL
In PHP, there are three types of runtime errors, they are:
Warnings:
These are important errors. Example: When we try to include () file which is not available. These errors are showed to the user by default but they will not result in ending the script.
Notices:
These errors are non-critical and trivial errors that come across while executing the script in PHP. Example: trying to gain access the variable which is not defined. These errors are not showed to the users by default even if the default behavior is changed.
Fatal errors:
These are critical errors. Example: instantiating an object of a class which does not exist or a non-existent function is called. These errors results in termination of the script immediately and default behavior of PHP is shown to them when they take place. Twelve different error types are used to represent these variations internally.
The include() and require() functions are used to add a file to a script.
The function eregi_replace() is identical to the function ereg_replace() except that it ignores case distinction when matching alphabetic characters.
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.
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.
mysql_fetch_assoc function Fetch a result row as an associative array, While
mysql_fetch_array() fetches an associative array, a numeric array, or both
Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices.
Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.
$GLOBALS − 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.
PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function.
Like a constructor function you can define a destructor function using function __destruct(). You can release all the resourceses with-in a destructor.
Interfaces are defined to provide a common function names to the implementors. Different implementors can implement those interfaces according to their requirements.
index.php is the default name of the home page in php based sites
For finding length of string we use strlen() function and for array we use count() function.
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.
t is used for sort an array by key in reverse order.
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.
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.
count() is used for fetching the total number records in a table.
The following code can be used for it, header("Location:index.php");
unlink() deletes the given file from the file system.
unset() makes a variable undefined.
Just like in C++, put an ampersand in front of it, like $a = &$b;
They are both variables. But $var is a variable with a fixed name. $$var is a variable who's name is stored in $var.
There are two special characters you need to escape in a double-quote string: the double quote (") and the back slash ().
Variables included in double-quoted strings will be interpolated. Their values will be concatenated into the enclosing strings.
mysql_fetch_object() is similar to mysql_fetch_array(), with one difference – an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
session_id() returns the session id for the current session.
In PHP an extended class is always dependent on a single base class,that is, multiple inheritance is supported by interfaces. Classes are extended using the keyword 'extends'.
Primary Key: A column in a table whose values uniquely identify therows in the table. A primary key value cannot be NULL. Unique Key: Unique Keys are used to uniquely identify each row in thetable. There can be one and only one row for each unique key value. So NULL can be a unique key.There can be only one primary key for a table but there can be morethan one unique for a table.
Set char to occupy n bytes and it will take n bytes even if u r storing a value of n-m bytes Set varchar to occupy n bytes and it will take only the required space and will not use the n bytes.
We can achieve the above task by using JavaScript code linked to an event trigger of any form field and call the document.form.submit() function in JavaScript code.
A static method is accessible without needing instantiation of a class. It means there is no need to make an object to call the static methods .Static methods and properties can be directly call from its class name with (::) a scope resolution operator. They cannot be call from the object of its class. We need static methods to overcome long overhead of instantiation of classes .
Keywords public,protected and private are the three types of access control modifiers in php.With the help of these keywords we can manage the accessing of a method or property of a class in php.
Public :
The items which are declared public can be access from everywhere ie access from inside the class ,access in inherited class and access from outside the class.
Protected :
The items which are declared protected can be access inside the class that defines the item and can acess in its child classes (ie access in its inherited class) .
Private :
The items which are declared private can only be access inside its class that defines the item.
$this is called pseudo variable and this is availabel when a method is called from within an Object context.
$this is refrence to the calling object of the current class. When we need to call a method of a class within the same class instead of creating object of that class we can use $this to call the method of the existing class.
You can execute a PHP script by running the Command line interface program, in which you can enter the PHP script file as an argument. If the file is made for the web interface then it may not execute properly using command line. Command line allows faster execution of the statements and gives faster results.
PEAR stands for "PHP Extension and Application Repository". It gives advanced functionality to the PHP language and include many applications which can be used on fly. The purpose of it is as follows:-
- Open source structured library for PHP users
- Code distribution and package maintenance system
- Standard style for code written in PHP
echo and print are largely the same in PHP. Both are used to output data to the screen. The only differences are as follows:
- echo does not return a value whereas print does return a value of 1 (this enables print to be used in expressions).
- echo can accept multiple parameters (although such usage is rare) while print can only take a single argument.
.htaccess files are configuration files of Apache Server which provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.
var_dump function displays structured information about variables including its type,size and value.
print_r() displays information about a variable in a human readbale format.
Web services converts our applicaton into a web-application ,which can publish its functions and messages to the internet users.The main web services platform is XML and HTTP.Web services can be published ,found and used through web.
Keywords public,protected and private are the three types of access control modifiers in php.With the help of these keywords we can manage the accessing of a method or property of a class in php.
The header() function is used to send a raw HTTP header to a client. It must be called before sending the actual output.
Advantages of PHP list below :
  • It's a OPEN SOURCE
  • Database Integration
  • Built-In Libraries
  • Easy to learn
  • Portability
  • Free to access Sourcecode
The comments means to give information about the execution line. PHP supports 'C', 'C++' and Unix shell-style comments
  • Numeric Array
  • Associative Array
  • Multidimensional Array
PHP filters are used to validate and filter data coming from insecure sources, like user input. Almost all web applications depend on external input. By using filters you can be sure your application gets the correct input type.
Array is used to store multiple values in single value. In PHP, it orders maps of pairs of keys and values. It stores the collection of data type.
The exit() function is used to stop the execution of PHP script.
  • CakePHP
  • CodeIgniter
  • Yii 2
  • Symfony
  • Zend Framework etc.
mysql_pconnect() ensure a persistent connection to the database, it means that the connection do not close when the the PHP script ends.
The function func_num_args() is used to give the number of parameters passed into a function.
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.
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.
It is possible to use the dedicated function, is_numeric() to check whether it is a number or not.
PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters.
mail( to, subject, message, headers, parameters );
Persistent cookie is a cookie which is permanently stored on user’s computer in a cookie file. They are used for tracking the user information of the users who are browsing from a very long time. They also have the drawbacks of being unsecure, as user can see the cookies which are saved on the computer.
No, It is interpreted Language.
public,protected and private are the three types of access modifiers in php.
Set max_execution_time variable in php.ini file to your desired time in second.
Rules for naming a variable are following:
  • Variable names must begin with a letter or underscore character.
  • A variable name can consist of numbers, letters, underscores but you cannot use characters like + , - , % , ( , ) . & , etc.
  • mysql_fetch_row
  • mysql_fetch_array
  • mysql_fetch_object
  • mysql_fetch_assoc
SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications.
Interpreted language executes line by line , if there is some error on a line it stops the execution of script.
Compiler language can execute the whole script at a time and gives all the errors at a time. It does not stops the execution of script ,if there is some error on some line.
A static method is accessible without needing instantiation of a class. It means there is no need to make an object to call the static methods .Static methods and properties can be directly call from its class name with (::) a scope resolution operator. They cannot be call from the object of its class. We need static methods to overcome long overhead of instantiation of classes .
nl2br inserts HTML line breaks(
) before all new lines in a string .
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.
Javascript is a client side scripting language whereas PHP is a server side scripting language.
The ternary operator is a short form of doing if statement. We called it ternary operator because it takes three operands ie. 1 – condition , 2- result for true ,3 –result for false.
The extract() function imports variables into the local symbol table from an array. extract function uses array keys as variable names and array values as variable values. For each element of array it will create a variable in the current symbol table.
Create session : session_start();
Set value into session : $_SESSION['USER_ID']=1;
Remove data from a session : unset($_SESSION['USER_ID'];
The session_id( ) function is used to get the current session id. It returns the session id for the current session.
MVC stands for Model View and Controller. Php MVC is an effective way to manage the code into three different layers.
Model: Model represents the information in application.
View: View represents the visual representation of infromation and data that you have entered in the appliation.
Controller: Controller is actually how and in which way you want to read the information in application.
For, while, do-while and for each.
Sorting functions in PHP:
  • asort()
  • arsort()
  • ksort()
  • krsort()
  • uksort()
  • sort()
  • natsort()
  • rsort()
Use this for mysql>SELECT COUNT(*) FROM table_name;
To be able to pass a variable by reference, we use an ampersand in front of it, as follows $var1 = &$var2.
There are some difference between PHP4 and PHP5 that are as following:-
  1. In PHP5 abstract classes are used but not used in PHP4.
  2. In PHP5 interfaces are used but not used in PHP4.
  3. In PHP5 visibility are used but not used in PHP4.
  4. In PHP5 magic methods are used but not uesd in PHP4.
  5. In PHP5 typehinting are used but not used in PHP4.
  6. In PHP5 cloning are used but not used in PHP4.
  7. In PHP5 construtor are written as __construct keyword but in PHP4 are written as class name.
use mysql_real_escape_string() function.
We can create MySQL Database with the use of mysql_create_db("Database Name").
  • Directory
  • stdClass
  • __PHP_Incomplete_Class
  • exception
  • php_user_filter
The uses of special tags such as in order for the output is displayed directly on the browser.
System functions, handle forms like gathering and saving data to and from a file, send and return data to the user, add, delete, modify data within the database, access cookies, restrict users access and in encrypting data.
By using setcookie(name, value, expire, path, domain); function we can set the cookie in php;
Set the cookies in past for destroy. like
setcookie("user", "sonia", time()+3600); for set the cookie
setcookie("user", "", time()-3600); for destroy or delete the cookies;
Where include() function includes and evaluates a specific line, require() can do the exact same function, it will also generate a fatal error and stops the script; require() and require_once() functions the same way whereas require_once() is a way to check if files have been included or not, so that the same function is not repeated twice before executing it.
This function is used to ensure that there is a persistent connection to the database where the connection will not close when the php script ends.
The protocol that is used to communicate in the web during a web-page visit is called an HTTP and an HTTP request is the protocol that the browser follows during this web-page visit.
NULL is a special type that only has one value: NULL. To give a variable the NULL value.The special constant NULL is capitalized by convention, but actually it is case insensitive.
In PHP a variable does not need to be declared before being set. PHP automatically converts the variable to the correct data type, depending on how they are set. In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it. In PHP the variable is declared automatically when you use it. Hence php is a loosely typed language.
We use PHP language over other languages beacuse PHP language runs on different platforms like Windows, Linux, Unix, Mac OS X, etc. It is also compatible on all servers like Apache, IIS, etc.
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.
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;
  1. A data member belongs to an object of a class whereas local variable belongs to its current scope.
  2. A local variable is declared within the body of a function and can be used only from the point at which it is declared to the immediately following closing brace.
  3. Data members are accessible to all member function of the class. Local variable are not accessible in any another function or class.
  1. Static methods are that can be accessed by using the scope resolution operator(i.e ::) and object reference operator( i.e.-> ).
  2. The only rule is that static methods or properties are out of object context.
  3. Public function of class can be access by scope resolution operator (i.e ::) and Object Reference Operator (i.e ->) but public data member can't be access through scope resolution operator.
  • Register the variable into the session
  • Pass the variable as a cookie
  • Pass the variable as part of the URL
It is possible to generate HTML through PHP scripts, and it is possible to pass informations from HTML to PHP.
This feature is possible using the global keyword.
:: is used to access static methods that do not require object initialization.
__sleep returns the array of all the variables that need to be saved, while __wakeup retrieves them.
$a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
A static variable is defined within a function only the first time and its value can be modified during function calls as.
A function returns a value using the instruction 'return $value;'.
Array_merge merges the elements of one or more than one array such that the value of one array appended at the end of first array. If the arrays have same strings key then the later value overrides the previous value for that key.
Final class is a class that can not be inherited.Its protect the methods of class to be overriden by the child classes.
Magic methods are very easy to identify, that every magical method name is started with double underscore( __)sign. We can not declare any user-defined functions with __ sign.
Some magic methods are :
__construct() , __destruct() , __call(),__callStatic(),__get(),__set(), __isset(),__unset()
, __sleep(), __wakeup(),__toString(), __invoke(), __set_state(),__clone().
The function get_included_files () function is used to get the names of all required and included files in a page . It returns an array with the names of included and required files in a page.
End function can set the pointer of an array to the last element of array.
Strpos used to find the first occurrence of a string in another string.It return the position of the substring in a string . If the searched string will not exists in the searching string it return false.
When string is in single quotes php will not evaluate it . If there is a string with single quotes and if we place a variable in that it would not substitute its value in string, whereas double quotes support variable expansion. If we place variable in double quotes it would substitute its value in string.
strstr and stristr both are used to search for the first occurrence of a string inside another string.
Difference :
the strstr function is case sensitive and stristr is case insensitive.
List() function is used to assign values to a list of variable in one operation and list only works on numerical arrays.
The use of the function session_start() lets us activating a session.
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.
The default session timeout is 24 minutes (1440 seconds),
however we can change this value by setting session.gc_maxlifetime() in php ini file.
With autoloaders PHP is given a last chance to load the class or interface before it fails with an error. spl_autoload_register() function registers any number of autoloaders , enabling for classes and interfaces to be automatically loaded if they are not defined.
func_num_args () used to get the number of arguments passed to the function.
fgetc() function is used to read a file character by character.
Type hinting means the function specifies what type of parameters must be and if it is not of the correct type an error will occur.PHP 5 introduces type hinting and the functions are able to force the parameters to be objects, interfaces,array.
Ob_start used to active the output buffering .When output buffering is on all output of the page sent at one time to the browser ,otherwise sometimes we face headers already sent type errors.
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.
Yes, it is possible by setting the cookie with a past expiration time.
The default session time in php is until closing of browser.
Yes, it’s possible to integrate (Distributed) Component Object Model components ((D)COM) in PHP scripts which is provided as a framework.
'final' is introduced in PHP5. Final class means that this class cannot be extended and a final method cannot be overrided.
If we would like to pass values througn a form or an URL then we need to encode and to decode them using htmlspecialchars() and urlencode().
imagetypes() gives the image format and types supported by the current version of GD-PHP.
To be able to display a human-readable result we use print_r().
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.
This is a PHP syntax error expressing that a mistake at the line x stops parsing and executing the program.
file_get_contents() lets reading a file and storing it in a string variable.
mysql_pconnect() ensure a persistent connection to the database, it means that the connection do not close when the the PHP script ends.
The result set can be handled using mysql_fetch_array, mysql_fetch_assoc, mysql_fetch_object or mysql_fetch_row.