12 Essential PHP Interview Questions

 Our Toptal Engineering Blog has published a great post called “12 Essential PHP Interview Questions,” and I think it would be of interest to all of you.

See the preview of article given below :

Consider the following code:
$str1 = ‘yabadabadoo’;
$str2 = ‘yaba’;
if (strpos($str1,$str2)) {
echo “\”” . $str1 . “\” contains \”” . $str2 . “\””;
} else {
echo “\”” . $str1 . “\” does not contain \”” . $str2 . “\””;
}
The output will be:
“yabadabadoo” does not contain “yaba”
Why? How can this code be fixed to work correctly?

To see more goto : http://www.toptal.com/php/interview-questions

Posted in LAMP, MySQL, PHP. 1 Comment »

MNC php interview questions and answers

1) what is session_set_save_handler in PHP? session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.

2) what is garbage collection? default time ? refresh time? Garbage Collection is an automated part of PHP , If the Garbage Collection process runs, it then analyzes any files in the /tmp for any session files that have not been accessed in a certain amount of time and physically deletes them. arbage Collection process only runs in the default session save directory, which is /tmp. If you opt to save your sessions in a different directory, the Garbage Collection process will ignore it. the Garbage Collection process does not differentiate between which sessions belong to whom when run. This is especially important note on shared web servers. If the process is run, it deletes ALL files that have not been accessed in the directory.

There are 3 PHP.ini variables, which deal with the garbage collector: PHP ini  value

name                                          default

session.gc_maxlifetime     1440 seconds or 24 minutes

session.gc_probability      1

session.gc_divisor              100

3) PHP how to know user has read the email? Using Disposition-Notification-To: in mailheader we can get read receipt.

Add the possibility to define a read receipt when sending an email.

It’s quite straightforward, just edit email.php, and add this at vars definitions:

var $readReceipt = null;

And then, at ‘createHeader’ function add:

if (!empty($this->readReceipt)) { $this->__header .= ‘Disposition-Notification-To: ‘ . $this->__formatAddress($this->readReceipt) . $this->_newLine; }

4) Runtime library loading ? without default mysql support, how to run mysql with php?

dl — Loads a PHP extension at runtime int dl ( string $library )

Loads the PHP extension given by the parameter library .

Use extension_loaded() to test whether a given extension is already available or not. This works on both built-in extensions and dynamically loaded ones (either through php.ini or dl()).

bool extension_loaded ( string $name ) — Find out whether an extension is loaded

Warning :This function has been removed from some SAPI’s in PHP 5.3.

5) what is XML-RPC ? XML-RPC is a remote procedure call protocol which uses XML to encode its calls and HTTP as a transport mechanism. An XML-RPC message is an HTTP-POST request. The body of the request is in XML. A procedure executes on the server and the value it returns is also formatted in XML.

6) default session time ? default session time in PHP is 1440 seconds or 24 minutes.

7) default session save path ? Default session save path id temporary folder /tmp

8) What is the difference between htmlentities() and htmlspecialchars()?

htmlspecialchars() – Convert some special characters to HTML entities (Only the most widely used) htmlentities() – Convert ALL special characters to HTML entities

9) how to do session using DB?

bool session_set_save_handler ( callback $open , callback $close , callback $read , callback $write , callback $destroy , callback $gc ) using this function we can store sessions in DB.

PHP has a built-in ability to override its default session handling. The function session_set_save_handler() lets the programmer specify which functions should actually be called when it is time to read or write session information. by overriding the default functions using session_set_save_handler handle we can store session in Db like below example

class SessionManager {

var $life_time;

function SessionManager() {

// Read the maxlifetime setting from PHP $this->life_time = get_cfg_var(“session.gc_maxlifetime”);

// Register this object as the session handler session_set_save_handler( array( &$this, “open” ), array( &$this, “close” ), array( &$this, “read” ), array( &$this, “write”), array( &$this, “destroy”), array( &$this, “gc” ) );

}

function open( $save_path, $session_name ) {

global $sess_save_path;

$sess_save_path = $save_path;

// Don’t need to do anything. Just return TRUE.

return true;

}

function close() {

return true;

}

function read( $id ) {

// Set empty result $data = ”;

// Fetch session data from the selected database

$time = time();

$newid = mysql_real_escape_string($id); $sql = “SELECT `session_data` FROM `sessions` WHERE `session_id` = ‘$newid’ AND `expires` > $time”;

$rs = db_query($sql); $a = db_num_rows($rs);

if($a > 0) { $row = db_fetch_assoc($rs); $data = $row[‘session_data’];

}

return $data;

}

function write( $id, $data ) {

// Build query $time = time() + $this->life_time;

$newid = mysql_real_escape_string($id); $newdata = mysql_real_escape_string($data);

$sql = “REPLACE `sessions` (`session_id`,`session_data`,`expires`) VALUES(‘$newid’, ‘$newdata’, $time)”;

$rs = db_query($sql);

return TRUE;

}

function destroy( $id ) {

// Build query $newid = mysql_real_escape_string($id); $sql = “DELETE FROM `sessions` WHERE `session_id` = ‘$newid'”;

db_query($sql);

return TRUE;

}

function gc() {

// Garbage Collection

// Build DELETE query. Delete all records who have passed the expiration time $sql = ‘DELETE FROM `sessions` WHERE `expires` < UNIX_TIMESTAMP();’;

db_query($sql);

// Always return TRUE return true;

}

}

10) how to track user logged out or not? when user is idle ? By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes.

The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server.

11) how to track no of user logged in ? whenever a user logs in track the IP, userID etc..and store it in a DB with a active flag while log out or sesion expire make it inactive. At any time by counting the no: of active records we can get the no: of visitors.

12) in PHP for pdf which library used?

The PDF functions in PHP can create PDF files using the PDFlib library With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. There is also the » Panda module.

FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs.

FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5.

13) for image work which library?

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

14) what is oops? encapsulation? abstract class? interface?

Object oriented programming language allows concepts such as modularity, encapsulation, polymorphism and inheritance.

Encapsulation passes the message without revealing the exact functional details of the class. It allows only the relevant information to the user without revealing the functional mechanism through which a particular class had functioned.

Abstract class is a template class that contains such things as variable declarations and methods, but cannot contain code for creating new instances. A class that contains one or more methods that are declared but not implemented and defined as abstract. Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract. Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class.

Interface: Interfaces are one type of class where all the methods are abstract. That means all the methods only declared but not defined. All the methods must be define by its implemented class.

15) what is design pattern? singleton pattern?

A design pattern is a general reusable solution to a commonly occurring problem in software design.

The Singleton design pattern allows many parts of a program to share a single resource without having to work out the details of the sharing themselves.

16) what are magic methods?

Magic methods are the members functions that is available to all the instance of class Magic methods always starts with “__”. Eg. __construct All magic methods needs to be declared as public To use magic method they should be defined within the class or program scope Various Magic Methods used in PHP 5 are: __construct() __destruct() __set() __get() __call() __toString() __sleep() __wakeup() __isset() __unset() __autoload() __clone()

17) what is magic quotes? Magic Quotes is a process that automagically escapes incoming data to the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime, as needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

18) diff b/w php4 & php5 ? In PHP5 1 Implementation of exceptions and exception handling

2. Type hinting which allows you to force the type of a specific argument as object, array or NULL

3. Overloading of methods through the __call function

4. Full constructors and destructors etc through a __constuctor and __destructor function

5. __autoload function for dynamically including certain include files depending on the class you are trying to create.

6 Finality : can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.

7 Interfaces & Abstract Classes

8 Passed by Reference : In PHP4, everything was passed by value, including objects. This has changed in PHP5 — all objects are now passed by reference.

9 An __clone method if you really want to duplicate an object

19) in php4 can you define a class? how to call class in php4? can you create object in php4?

yes you can define class and can call class by creating object of that class. but the diff b/w php4 & php5 is that in php4 everything was passed by value where as in php5 its by reference. And also any value change in reference object changes the actucal value of object also. And one more thing in introduction of __clone object in PHP5 for copying the object.

20) types of error? how to set error settings at run time?

here are three basic types of runtime errors in PHP:

1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although you can change this default behaviour.

2. Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.

3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP?s default behaviour is to display them to the user when they take place.

by using ini_set function.

21) what is cross site scripting? SQL injection?

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Examples of such code include HTML code and client-side scripts.

SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed

22) what is outerjoin? inner join?

OUTER JOIN in SQL allows us to retrieve all values in a certain table regardless of whether these values are present in other tables

An inner join requires each record in the two joined tables to have a matching record. An inner join essentially combines the records from two tables (A and B) based on a given join-predicate.

23) what is URL rewriting?

Using URL rewriting we can convert dynamic URl to static URL Static URLs are known to be better than Dynamic URLs because of a number of reasons 1. Static URLs typically Rank better in Search Engines. 2. Search Engines are known to index the content of dynamic pages a lot slower compared to static pages. 3. Static URLs are always more friendlier looking to the End Users.

along with this we can use URL rewriting in adding variables [cookies] to the URL to handle the sessions.

24) what is the major php security hole? how to avoid?

1. Never include, require, or otherwise open a file with a filename based on user input, without thoroughly checking it first. 2. Be careful with eval() Placing user-inputted values into the eval() function can be extremely dangerous. You essentially give the malicious user the ability to execute any command he or she wishes! 3. Be careful when using register_globals = ON It was originally designed to make programming in PHP easier (and that it did), but misuse of it often led to security holes 4. Never run unescaped queries 5. For protected areas, use sessions or validate the login every time. 6. If you don’t want the file contents to be seen, give the file a .php extension.

25) whether PHP supports Microsoft SQL server ? The SQL Server Driver for PHP v1.0 is designed to enable reliable, scalable integration with SQL Server for PHP applications deployed on the Windows platform. The Driver for PHP is a PHP 5 extension that allows the reading and writing of SQL Server data from within PHP scripts. using MSSQL or ODBC modules we can access Microsoft SQL server.

26) what is MVC? why its been used? Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model.

WHY ITS NEEDED IS 1 Modular separation of function 2 Easier to maintain 3 View-Controller separation means:

A — Tweaking design (HTML) without altering code B — Web design staff can modify UI without understanding code

27) what is framework? how it works? what is advantage?

In general, a framework is a real or conceptual structure intended to serve as a support or guide for the building of something that expands the structure into something useful. Advantages : Consistent Programming Model Direct Support for Security Simplified Development Efforts Easy Application Deployment and Maintenance

28) what is CURL?

CURL means Client URL Library

curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos…), file transfer resume, proxy tunneling and a busload of other useful tricks.

CURL allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

29) HOW we can transfer files from one server to another server without web forms?

using CURL we can transfer files from one server to another server. ex:

Uploading file

<?php

/* http://localhost/upload.php: print_r($_POST); print_r($_FILES); */

$ch = curl_init();

$data = array(‘name’ => ‘Foo’, ‘file’ => ‘@/home/user/test.png’);

curl_setopt($ch, CURLOPT_URL, ‘http://localhost/upload.php&#8217;);

curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch); ?>

output:

Array ( [name] => Foo ) Array ( [file] => Array ( [name] => test.png
[type] => image/png [tmp_name] => /tmp/phpcpjNeQ [error] => 0 [size] => 279 )   )  

  30) using CSS can we have a scroll to table? 
No table won't support scrolling of its data. but we can do another workaround like placing a table
 in a DIV  layer and setting the DIV css property to overflow:auto will do the trick.  

  31) how to increase session time in PHP ? 
In php.ini by setting session.gc_maxlifetime and session.cookie_lifetime values
we can change the session time in PHP.   

 32) what is UI? What are the five primary user-interface components?  
 A user interface is a means for human beings to interact with computer-based "tools" and"messages".
One presumed goal is to make the user's experience productive, efficient, pleasing, and humane.
 The primary components of UIs are  a) metaphors (fundamental concepts communicated
 through words, images, sounds, etc.)
b) mental models (structure of data, functions, tasks, roles, jobs, and people in organizations of work
and/or play)
 c) navigation (the process of moving through the mental models)
d) interaction (all input-output sequences and means for conveying feedback)
 e) and appearance (visual, verbal, acoustic, etc.).
33) How can I set a cron and how can I execute it in Unix, Linux, and windows?

Cron is very simply a Linux module that allows you to run commands at predetermined times or intervals.

In Windows, it’s called Scheduled Tasks. The name Cron is in fact derived from the same word from which we get the word chronology, which means order of time.

The easiest way to use crontab is via the crontab command. # crontab This command ‘edits’ the crontab.

Upon employing this command, you will be able to enter the commands that you wish to run.

My version of Linux uses the text editor vi. You can find information on using vi here.

The syntax of this file is very important – if you get it wrong, your crontab will not function properly.

The syntax of the file should be as follows: minutes hours day_of_month month day_of_week command All the variables, with the exception of the command itself, are numerical constants.

In addition to an asterisk (*), which is a wildcard that allows any value, the ranges permitted for each field are as follows: Minutes: 0-59 Hours: 0-23 Day_of_month: 1-31 Month: 1-12 Weekday: 0-6 We can also include multiple values for each entry, simply by separating each value with a comma.

command can be any shell command and, as we will see momentarily, can also be used to execute a Web document such as a PHP file. So, if we want to run a script every Tuesday morning at 8:15 AM, our mycronjob file will contain the following content on a single line: 15 8 * * 2 /path/to/scriptname This all seems simple enough, right? Not so fast! If you try to run a PHP script in this manner, nothing will happen (barring very special configurations that have PHP compiled as an executable, as opposed to an Apache module).

The reason is that, in order for PHP to be parsed, it needs to be passed through Apache. In other words, the page needs to be called via a browser or other means of retrieving Web content.

For our purposes, I’ll assume that your server configuration includes wget, as is the case with most default configurations. To test your configuration, log in to shell.

If you’re using an RPM-based system (e.g. Redhat or Mandrake), type the following: # wget help If you are greeted with a wget package identification, it is installed in your system.

You could execute the PHP by invoking wget on the URL to the page, like so: # wget http://www.example.com/file.php Now, let’s go back to the mailstock.php file we created in the first part of this article.

We saved it in our document root, so it should be accessible via the Internet. Remember that we wanted it to run at 4PM Eastern time, and send you your precious closing bell report? Since I’m located in the Eastern timezone, we can go ahead and set up our crontab to use 4:00, but if you live elsewhere, you might have to compensate for the time difference when setting this value.

This is what my crontab will look like: 0 4 * * 1,2,3,4,5 wget http://www.example.com/mailstock.php

34)Difference b/w OOPS concept in php4 and PHP5 ?

version 4’s object-oriented functionality was rather hobbled. Although the very basic premises of objectoriented programming (OOP) were offered in version 4, several deficiencies existed, including: • An unorthodox object-referencing methodology • No means for setting the scope (public, private, protected, abstract) of fields and methods • No standard convention for naming constructors • Absence of object destructors • Lack of an object-cloning feature • Lack of support for interfaces

35) Difference b/w MyISAM and InnoDB in MySQL?

Ans:

  • The big difference between MySQL Table Type MyISAM and InnoDB is that InnoDB supports transaction
  • InnoDB supports some newer features: Transactions, row-level locking, foreign keys
  • InnoDB is for high volume, high performance
  • use MyISAM if they need speed and InnoDB for data integrity.
  • InnoDB has been designed for maximum performance when processing large data volumes
  • Even though MyISAM is faster than InnoDB
  • InnoDB supports transaction. You can commit and rollback with InnoDB but with MyISAM once you issue a command it’s done
  • MyISAM does not support foreign keys where as InnoDB supports
  • Fully integrated with MySQL Server, the InnoDB storage engine maintains its own buffer pool for caching data and indexes in main memory. InnoDB stores its tables and indexes in a tablespace, which may consist of several files (or raw disk partitions). This is different from, for example, MyISAM tables where each table is stored using separate files. InnoDB tables can be of any size even on operating systems where file size is limited to 2GB.
  • 36) how to set session tiem out at run time or how to extend the session timeout at runtime?

    Ans:

    Sometimes it is necessary to set the default timeout period for PHP. To find out what the default (file-based-sessions) session timeout value on the server is you can view it through a ini_get command:

    // Get the current Session Timeout Value
    $currentTimeoutInSecs = ini_get(’session.gc_maxlifetime’);

    Change the Session Timeout Value

    // Change the session timeout value to 30 minutes
    ini_set(’session.gc_maxlifetime’, 30*60);

    If you have changed the sessions to be placed inside a Database occasionally implementations will specify the expiry manually. You may need to check through the session management class and see if it is getting the session timeout value from the ini configuration or through a method parameter (with default). It may require a little hunting about.

    Aztecsoft php web developer interview questions and answers

    1) how to increase the web page performance ?

    1) Use lightweight templates
    2) Put Stylesheets at the Top
    3) Put Scripts at the Bottom
    4) Avoid CSS Expressions like As an example, the background color could be set to alternate every hour using CSS expressions.
    background-color: expression( (new Date()).getHours()%2 ? “#B8D4FF” : “#F08A00” );

    5) Make JavaScript and CSS External
    6) Minify JavaScript and CSS : Minification is the practice of removing unnecessary characters from code to reduce its size thereby improving load times.

    7) Remove Duplicate Scripts
    8) Choose over @import
    9) Don’t Scale Images in HTML
    10) Make favicon.ico Small and Cacheable
    11) use Ajax, JSON, Jquery for fastening results

     

    2) $test=array( 0=>’one’ , 2=> ‘two’ , ‘3 ‘=>’three’ , ‘3a’=>5, ‘myindex’); print_r($test); what will be the output? 

    Array ( [0] => one [2] => two [3 ] => three [3a] => 5 [3] => myindex )

    3) what is output of this mysql function select substring_index(‘abc@123.com’,”@”,-1); 

    Ans:  123.com   explanation is below

    SUBSTRING_INDEX(str,delim,count)

    Returns the substring from string str before count occurrences of the delimiter delim. If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count is negative, everything to the right of the final delimiter (counting from the right) is returned. SUBSTRING_INDEX() performs a case-sensitive match when searching for delim.

    mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2);
            -> 'www.mysql'
    mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2);
            -> 'mysql.com'

    This function is multi-byte safe.

     

    4) An employee table having columns  id {employee id} , name {employee name},  m_id {manager id }  , write a query to select employee and their manager names  ? 

     

    Main table    
    id name m_id
    1 John 2
    2 Greek Tor 1
    3 Alex John 1
    4 Mike tour 1
    5 Brain J 3
    6 Ronald 3
    7 Kin 4
    8 Herod 3
    9 Alen 2
    10 Ronne 1

    Ans:  INNER join SQL command is mostly used to join one table to it self. The biggest advantage of doing this is to get linking information from the same table. We will try to understand this with an example. The best example of INNER join will be employee table where we will keep the employee and its manager as a single record. This way by linking to the table it self we will generate a report displaying it as two linked tables. Each record will have one additional field storing the data of the manager by keeping the employee ID and we will use M_ID ( manager ID ) to link with main employee ID. This way we will link two virtual tables generated from one main table. 

    let us use inner join to create one report on who is the manager of which employee. Check this SQL 
    SELECT t1.id, t1.name as emp_name, t2.name as manager FROM emp as t1 INNER JOIN emp as t2 on t2.id = t1.m_id

    id emp_name manager
    1 John Greek Tor
    2 Greek Tor John
    3 Alex John John
    4 Mike tour John
    5 Brain J Alex John
    6 Ronald Alex John
    7 Kin Mike tour
    8 Herod Alex John
    9 Alen Greek Tor
    10 Ronne John

    for more :  To generate only the manager table used this SQL

    SELECT t1.id,t1.name as emp_name from emp as t1 INNER JOIN emp as t2 on t1.id=t2.m_id 

    Managers Table

     

     
    id emp_name
    2 Greek Tor
    1 John
    1 John
    1 John
    3 Alex John
    3 Alex John
    4 Mike tour
    3 Alex John
    2 Greek Tor
    1 John

     

    To generate only the employee table  used this SQL
    SELECT t1.id,t1.name as emp_name from emp as t1 INNER JOIN emp as t2 on t2.id=t1.m_id 

       
    id emp_name
    1 John
    2 Greek Tor
    3 Alex John
    4 Mike tour
    5 Brain J
    6 Ronald
    7 Kin
    8 Herod
    9 Alen
    10 Ronne

     

    use below dump for your reference 

    CREATE TABLE `emp` (
    `id` int(4) NOT NULL auto_increment,
    `name` varchar(25) NOT NULL default ”,
    `m_id` int(4) NOT NULL default ‘0’,
    UNIQUE KEY `id` (`id`)
    ) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

    — 
    — Dumping data for table `emp`
    — 

    INSERT INTO `emp` VALUES (1, ‘John’, 2);
    INSERT INTO `emp` VALUES (2, ‘Greek Tor’, 1);
    INSERT INTO `emp` VALUES (3, ‘Alex John’, 1);
    INSERT INTO `emp` VALUES (4, ‘Mike tour’, 1);
    INSERT INTO `emp` VALUES (5, ‘Brain J’, 3);
    INSERT INTO `emp` VALUES (6, ‘Ronald’, 3);
    INSERT INTO `emp` VALUES (7, ‘Kin’, 4);
    INSERT INTO `emp` VALUES (8, ‘Herod’, 3);
    INSERT INTO `emp` VALUES (9, ‘Alen’, 2);
    INSERT INTO `emp` VALUES (10, ‘Ronne’, 1);


    5) write code to read the following file content “rag.txt”  and replace postgre SQL to MySQL and output the content ?

    The postgre SQL database has become the world’s most popular open source database because of its consistent fast performance, high reliability and ease of use. postgre SQL used on every continent — Yes, even Antarctica! — by individual Web developers as well as many of the world’s largest and fastest-growing organizations to save time and money powering their high-volume Web sites, business-critical systems and packaged software by postgre SQL.

    Ans:

     $str = file_get_contents(‘rag.txt’);

    $str = str_replace(‘postgre SQL’ ,’MySQL’, $str);

    echo $str;

     

    6) how we can destroy session cookie?

    Ans: we can use session_destroy() or  to destroy particular cookie set it to past time using  setcookie () function like  setcookie (“TestCookie”“”time() – 3600);

    7) True or False 

    a) session_destroy()  : destroys all of the data from session   TRUE

    b) session_unset() : frees all session variable  TRUE

    c) unset($_SESSION) deletes all session data   FALSE    “Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.”  

    8) $array = array( “hi”, “Hello World” , “what”, “Good Morning”);  write code to output the array contents havng more than one word ?
    Ans: 
        

    <? $array = array( “hi”, “Hello World” , “what”, “Good Morning”); 
    $count = sizeof($array);
    $i =0;
    while ($i < $count )
    {
    echo “<br> ***********<br>”;
    $exp = explode ( ” ” ,$array[$i] );
    if (count($exp) > 1)
    echo $array[$i] .” is having more than  one word in “. $i.” position of array  <br>”;
    $i++;
    }
    ?>
    9) what is the output of the below code 
    $sec_array = array(“red”, “green”, “blue”,”yellow”);
    array_splice( $sec_array , 1, -1);
    print_r($sec_array );   ? 

     

    Ans: Array ( [0] => red [1] => yellow )
    10) how we can get the second value from the last in an array ?
    Ans: 
    example  <? 
    $check = array ( “rag”, “shara”, “sharag”, “man”,”woman”,”child”, “human”);
    echo $check[count($check)-2];
    ?>

    11)  What is the maximum length of a URL?

    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL

    Firefox, Safari , Opera  supports more than 100,000 characters.  but some times server like Apache, IIS may not support these longer URL’s. so better to keep it short URL.


    PHP OOPS Interview Questions & Answers

    PHP OOPS Interview Questions & Answers

    1) Explain what is object oriented programming language?
    Object oriented programming language allows concepts such as modularity, encapsulation, polymorphism and inheritance.  Objects are said to be the most important part of object oriented language. Concept revolves around making simulation programs around an object. Organize a program around its data (object)& set well define interface to that data. i.e. objects and a set of well defined interfaces to that data. OOP is the common abbreviation for Object-Oriented Programming.  OOps have many properties such as DataHiding,Inheritence,Data Absraction,Data Encapsulation and many more.

    2) Name some languages which have object oriented language and characteristics?
    Some of the languages which have object oriented languages present in them are ABAP, ECMA Script, C++, Perl, LISP, C#, Tcl, VB, Ruby, Python, PHP, etc. Popularity of these languages has increased considerably as they can solve complex problems with ease.
    3) Explain about UML?
    UML or unified modeling language is regarded to implement complete specifications and features of object oriented language. Abstract design can be implemented in object oriented programming languages. It lacks implementation of polymorphism on message arguments which is a OOPs feature.
    4) Explain the meaning of object in object oriented programming?
    Languages which are called as object oriented almost implement everything in them as objects such as punctuations, characters, prototypes, classes, modules, blocks, etc. They were designed to facilitate and implement object oriented methods.
    5) Explain about message passing in object oriented programming?
    Message passing is a method by which an object sends data to another object or requests other object to invoke method. This is also known as interfacing. It acts like a messenger from one object to other object to convey specific instructions.
    6) State about Java and its relation to Object oriented programming?
    Java is widely used and its share is increasing considerably which is partly due to its close resemblance to object oriented languages such as C++. Code written in Java can be transported to many different platforms without changing it. It implements virtual machine.
    7) What are the problems faced by the developer using object oriented programming language?

    These are some of the problems faced by the developer using object oriented language they are: –

    a) Object oriented uses design patterns which can be referred to as anything in general.
    b) Repeatable solution to a problem can cause concern and disagreements and it is one of the major problems in software design.
    8 ) State some of the advantages of object oriented programming?
    Some of the advantages of object oriented programming are as follows: –
    a) A clear modular structure can be obtained which can be used as a prototype and it will not reveal the mechanism behind the design. It does have a clear interface.
    b) Ease of maintenance and modification to the existing objects can be done with ease.
    c) A good framework is provided which facilitates in creating rich GUI applications.
    9 ) Explain about inheritance in OOPS?
    Objects in one class can acquire properties of the objects in other classes by way of inheritance. Reusability which is a major factor is provided in object oriented programming which adds features to a class without modifying it. New class can be obtained from a class which is already present.
    10) Explain about the relationship between object oriented programming and databases?
    Object oriented programming and relational database programming are almost similar in software engineering. RDBMS will not store objects directly and that’s where object oriented programming comes into play. Object relational mapping is one such solution.
    11) Explain about a class in OOP?
    In Object oriented programming usage of class often occurs. A class defines the characteristics of an object and its behaviors. This defines the nature and functioning of a specified object to which it is assigned. Code for a class should be encapsulated.

    12) Explain the usage of encapsulation?
    Encapsulation specifies the different classes which can use the members of an object. The main goal of encapsulation is to provide an interface to clients which decrease the dependency on those features and parts which are likely to change in future. This facilitates easy changes to the code and features.
    13) Explain about abstraction?
    Abstraction can also be achieved through composition. It solves a complex problem by defining only those classes which are relevant to the problem and not involving the whole complex code into play.
    14) Explain what a method is?
    A method will affect only a particular object to which it is specified. Methods are verbs meaning they define actions which a particular object will perform. It also defines various other characteristics of a particular object.
    15) Name the different Creational patterns in OO design?
    There are three patterns of design out of which Creational patterns play an important role the various patterns described underneath this are: –
    a) Factory pattern
    b) Single ton pattern
    c) Prototype pattern
    d) Abstract factory pattern
    e) Builder pattern
    16) Explain about realistic modeling?
    As we live in a world of objects, it logically follows that the object oriented approach models the real world accurately. The object oriented approach allows you to identify entities as objects having attributes and behavior.
    17) Explain about the analysis phase?
    The anlaysis or the object oriented analysis phase considers the system as a solution to a problem in its environment or domain. Developer concentrates on obtaining as much information as possible about the problem. Critical requirements needs to be identified.

    ************************************************************************************************************

    1) Explain the rationale behind Object Oriented concepts?

    Object oriented concepts form the base of all modern programming languages. Understanding the basic concepts of object-orientation helps a developer to use various modern day programming languages, more effectively.
    2) Explain about Object oriented programming?
    Object oriented programming is one of the most popular methodologies in software development. It offers a powerful model for creating computer programs. It speeds the program development process, improves maintenance and enhances reusability of programs.
    3) Explain what is an object?
    An object is a combination of messages and data. Objects can receive and send messages and use messages to interact with each other. The messages contain information that is to be passed to the recipient object.
    4) Explain the implementation phase with respect to OOP?
    The design phase is followed by OOP, which is the implementation phase. OOP provides specifications for writing programs in a programming language. During the implementation phase, programming is done as per the requirements gathered during the analysis and design phases.
    5) Explain about the Design Phase?
    In the design phase, the developers of the system document their understanding of the system. Design generates the blue print of the system that is to be implemented. The first step in creating an object oriented design is the identification of classes and their relationships.
    6) Explain about a class?
    Class describes the nature of a particular thing. Structure and modularity is provided by a Class in object oriented programming environment. Characteristics of the class should be understandable by an ordinary non programmer and it should also convey the meaning of the problem statement to him. Class acts like a blue print.

    7) Explain about instance in object oriented programming?
    Every class and an object have an instance. Instance of a particular object is created at runtime. Values defined for a particular object define its State. Instance of an object explains the relation ship between different elements.
    8 ) Explain about inheritance?
    Inheritance revolves around the concept of inheriting knowledge and class attributes from the parent class. In general sense a sub class tries to acquire characteristics from a parent class and they can also have their own characteristics. Inheritance forms an important concept in object oriented programming.
    9) Explain about multiple inheritance?
    Inheritance involves inheriting characteristics from its parents also they can have their own characteristics. In multiple inheritance a class can have characteristics from multiple parents or classes. A sub class can have characteristics from multiple parents and still can have its own characteristics.
    10) Explain about encapsulation?
    Encapsulation passes the message without revealing the exact functional details of the class. It allows only the relevant information to the user without revealing the functional mechanism through which a particular class had functioned.
    11) Explain about abstraction?
    Abstraction simplifies a complex problem to a simpler problem by specifying and modeling the class to the relevant problem scenario. It simplifies the problem by giving the class its specific class of inheritance. Composition also helps in solving the problem to an extent.
    12) Explain the mechanism of composition?
    Composition helps to simplify a complex problem into an easier problem. It makes different classes and objects to interact with each other thus making the problem to be solved automatically. It interacts with the problem by making different classes and objects to send a message to each other.
    13) Explain about polymorphism?
    Polymorphism helps a sub class to behave like a parent class. When an object belonging to different data types respond to methods which have a same name, the only condition being that those methods should perform different function.
    14) Explain about overriding polymorphism?
    Overriding polymorphism is known to occur when a data type can perform different functions. For example an addition operator can perform different functions such as addition, float addition etc. Overriding polymorphism is generally used in complex projects where the use of a parameter is more.
    15) Explain about object oriented databases?
    Object oriented databases are very popular such as relational database management systems. Object oriented databases systems use specific structure through which they extract data and they combine the data for a specific output. These DBMS use object oriented languages to make the process easier.
    16) Explain about parametric polymorphism?
    Parametric polymorphism is supported by many object oriented languages and they are very important for object oriented techniques. In parametric polymorphism code is written without any specification for the type of data present. Hence it can be used any number of times.
    17) What are all the languages which support OOP?
    There are several programming languages which are implementing OOP because of its close proximity to solve real life problems. Languages such as Python, Ruby, Ruby on rails, Perl, PHP, Coldfusion, etc use OOP. Still many languages prefer to use DOM based languages due to the ease in coding.

    var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.&#8221; : “http://www.&#8221;);
    document.write(unescape(“%3Cscript src='” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));

    try {
    var pageTracker = _gat._getTracker(“UA-1855756-5”);
    pageTracker._trackPageview();
    } catch(err) {}