php interview question and answers1

Upload: cam-choudhary

Post on 08-Aug-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/22/2019 PHP Interview Question and Answers1

    1/36

    Q:1 What are the differences between Get and post methods in formsubmitting.give the case where we can use get and we can use post methods?

    A:1 When to use GET or POST

    The HTML 2.0 specification says, in section Form

    Submission (and the HTML 4.0 specification repeats this with minorstylistic changes):

    >If the processing of a form is idempotent(i.e. it has no lasting observable effect on the state of the

    world), then the form method should be GET. Many database searcheshave no visible side-effects and make ideal applications of query

    forms.

    >If the service associated with the processing of a form has sideeffects (for example, modification of a database or subscription to

    a service), the method should be POST.

    How the form data is transmitted?

    quotation from the HTML 4.0 specification

    > If the method is get - -, the user agent

    takes the value of action, appends a ? to it, then appends the formdata set, encoded using the application/x-www-form-urlencoded

    content type. The user agent then traverses the link to this URI. Inthis scenario, form data are restricted to ASCII codes.

    > If the method is post , the user agent conducts an HTTP posttransaction using the value of the action attribute and a message

    created according to the content type specified by the enctypeattribute.

    Quote from CGI FAQ

    Firstly, the the HTTP protocol specifies

    differing usages for the two methods. GET requests should always beidempotent on the server. This means that whereas one GET request

    might (rarely) change some state on the Server, two or moreidentical requests will have no further effect.

    This is a theoretical point which is also goodadvice in practice. If a user hits reload on his/her browser, an

    identical request will be sent to the server, potentially resultingin two identical database or

    guestbook entries, counter increments, etc. Browsers may reload aGET URL automatically, particularly if cacheing is disabled (as is

    usually the case with CGI output), but will typically prompt theuser before

  • 8/22/2019 PHP Interview Question and Answers1

    2/36

    re-submitting a POST request. This means youre far less likely to

    get inadvertently-repeated entries from POST.

    GET is (in theory) the preferred method for

    idempotent operations, such as querying a database, though it

    matters little if youre using a form. There is a further practicalconstraint that many systems have built-in limits to the length of a

    GET request they can handle: when the total size of a request (URL+params)approaches or exceeds 1Kb, you are well-advised to use POST in any

    case.

    I would prefer POST when I dont want the status tobe change when user resubmits. And GET

    when it does not matter.

    Q:2 Who is the father of PHP and explain the changes in PHP versions?

    A:2 Rasmus Lerdorf is known as the father of PHP.PHP/FI 2.0 is an early and no longersupported version of PHP. PHP 3

    is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current

    generation of PHP, which uses theZend engine

    under thehood. PHP 5 uses

    Zend engine 2 which,among other things, offers many additionalOOP features

    Q:3 How can we submit a form without a submit button?

    A:3 The main idea behind this is to use Java script submit() function inorder to submit the form without explicitly clicking any submit button.You can attach the document.formname.submit() method to onclick,

    onchange events of different inputs and perform the form submission. youcan even built a timer function where you can automatically submit the

    form after xx seconds once the loading is done.

    Q:4 In how many ways we can retrieve the data in the result set ofMySQL using PHP?

    A:4 You can do it by 4 Ways1. mysql_fetch_row.2. mysql_fetch_array

    3. mysql_fetch_object4. mysql_fetch_assoc

    Q:5 What is the difference between mysql_fetch_object andmysql_fetch_array?

    A:5 mysql_fetch_object() is similar tomysql_fetch_array(), with one difference -an object is returned, instead of an array. Indirectly, that means thatyou can only access the data by the field names, and not by their

  • 8/22/2019 PHP Interview Question and Answers1

    3/36

    offsets (numbers are illegal property names).

    Q:6 What is the difference between $message and $$message?

    A:6 It is a classic example of PHPs variable variables. take thefollowing example.$message = Mizan;$$message = is a moderator of

    PHPXperts.;$message is a simple PHP variable that we are used to. But the$$message is not a very familiar face. It creates a variable name $mizan

    with the value is a moderator of PHPXperts. assigned. break it likethis${$message} => $mizanSometimes it is convenient to be able to have variable

    variablenames. That is, a variable name which can be set and used dynamically.

    Q:7 How can we extract string abc.com from a string http://[email protected] regular expression of PHP?

    A:7 preg_match(/^http:\/\/.+@(.+)$/,http://[email protected],$found);echo $found[1];

    Q:8 How can we create a database using PHP and MySQL?

    A:8 We can create MySQL database with the use ofmysql_create_db(Database Name)

    Q:9 What are the differences between require and include,include_once and require_once?

    A:9 The include() statement includesand evaluates the specified file. The documentation below also applies to

    require(). The two constructsare identical in every way except how they handle

    failure. include() produces aWarning while require() resultsin a Fatal Error. In other words, userequire() if you want a missingfile to halt processing of the page.include() does not behave this way, the script willcontinue regardless.

    The include_once()statement includes and evaluates thespecified file during the execution of

    the script. This is a behavior similar

    to the include()statement, with the only difference

    being that if the code from a file has

    already been included, it will not beincluded again. As the name suggests, it

    will be included just once.include_once()should be used in cases where the same

    file might be included and evaluatedmore than once during a particular

  • 8/22/2019 PHP Interview Question and Answers1

    4/36

    execution of a script, and you want to

    be sure that it is included exactly onceto avoid problems with function

    redefinitions, variable valuereassignments, etc.

    require_once()should be used in cases where the samefile might be included and evaluated

    more than once during a particular

    execution of a script, and you want tobe sure that it is included exactly once

    to avoid problems with functionredefinitions, variable value

    reassignments, etc.

    Q:10 Can we use include (abc.PHP) two times in a PHP page makeit.PHP?A:10 Yes we can use include () more than one time in any page though it is

    not a very good practice.

    Q:11 What are the different tables present in MySQL, which type oftable is generated when we are creating a table in the following syntax:create table employee (eno int(2),ename varchar(10)) ?

    A:11 Total 5 types of tables we can create1. MyISAM2. Heap

    3. Merge4. INNO DB

    5. ISAMMyISAM is the default storage engine as of MySQL 3.23 and as a result if

    we do not specify the table name explicitly it will be assigned to thedefault engine.

    Q:12 Functions in IMAP, POP3 AND LDAP?

    A:12 You can find these specific information in PHP Manual.

    Q:13 How can I execute a PHP script using command line?

    A:13 As of version 4.3.0, PHP supports a new SAPI type (Server

    Application Programming Interface) named CLI which means Command LineInterface. Just run the PHP CLI (Command Line Interface) program and

    provide the PHP script file name as the command line argument. Forexample, php myScript.php, assuming php is the command to invoke the

    CLI program.Be aware that if your PHP script was written for the Web CGI interface,

    it may not execute properly in command line environment.

  • 8/22/2019 PHP Interview Question and Answers1

    5/36

    Q:14 Suppose your Zend engine supports the mode Then how can uconfigure your PHP Zend engine to support mode ?

    A:14 In php.ini file:setshort_open_tag=onto make PHP support

    Q:15 Shopping cart online validation i.e. how can we configure Paypal,etc.?

    A:15 We can find the detail documentation about different paypalintegration process at the following site

    PayPal PHP

    SDK : http://www.paypaldev.org

    Q:16 What is meant by nl2br()?A:16 Inserts HTML line breaks (

  • 8/22/2019 PHP Interview Question and Answers1

    6/36

    PHP Scripts are loadedinto memory and compiled into Zend opcodes.

    Q:18 What are the current versions of apache, PHP, and MySQL?

    A:18 As of February, 2007 the current versions arePHP: php5.2.1MySQL: MySQL 5.2

    Apache: Apache 2.2.4Note: visit www.php.net,

    http://dev.mysql.com/downloads/mysql/,www.apache.org to get current

    versions.

    Q:19 What are the reasons for selecting lamp (Linux, apache, MySQL,PHP) instead of combination of other software programs, servers andoperating systems?

    A:19 All of those are open source resource. Security of Linux is veryvery more than windows. Apache is a better server that IIS both infunctionality and security. MySQL is world most popular open source

    database. PHP is more faster that asp or any other scripting language.

    Q:20 How can we encrypt and decrypt a data present in a MySQL tableusing MySQL?

    A:20 AES_ENCRYPT () and AES_DECRYPT ()

    Q:21 How can we encrypt the username and password using PHP?

    A:21 The functions in this section perform encryption and decryption, andcompression and uncompression:

    encryption Decryption

    AES_ENCRYT() AES_DECRYPT()

    ENCODE() DECODE()

    DES_ENCRYPT() DES_DECRYPT()

    http://www.php.net/http://dev.mysql.com/downloads/mysql/http://www.apache.org/http://www.php.net/http://dev.mysql.com/downloads/mysql/http://dev.mysql.com/downloads/mysql/http://www.apache.org/
  • 8/22/2019 PHP Interview Question and Answers1

    7/36

    ENCRYPT() Not available

    MD5() Not available

    OLD_PASSWORD() Not available

    PASSWORD() Not available

    SHA() or SHA1() Not availableNot available UNCOMPRESSED_LENGTH()

    Q:22 What are the features and advantages of object-orientedprogramming?

    A:22 One of the main advantages of OO programming is its ease ofmodification; objects can easily be modified and added to a system there

    by reducing maintenance costs. OO programming is also considered to bebetter at modeling the real world than is procedural programming. It

    allows for more complicated and flexible interactions. OO systems arealso easier for non-technical personnel to understand and easier for

    them to participate in the maintenance and enhancement of a systembecause it appeals to natural human cognition patterns.

    For some systems, an OO approach can speed development time since manyobjects are standard across systems and can be reused. Components that

    manage dates, shipping, shopping carts, etc. can be purchased and easilymodified for a specific system

    Q:23 What are the differences between procedure-oriented languages andobject-oriented languages?

    A:23 Traditional programming has the following characteristics:Functions are writtensequentially, so that a change in programming canaffect any code that follows it.

    If a function is used multiple times in a system (i.e., a piece of codethat manages the date), it is often simply cut and pasted into each

    program (i.e., a change log, order function, fulfillment system, etc).If a date change is needed (i.e., Y2K when the code needed to be changed

    to handle four numerical digits instead of two), all these pieces ofcode must be found, modified, and tested.

    Code (sequences of computer instructions) and data (information on whichthe instructions operates on) are kept separate. Multiple sets of code

    can access and modify one set of data. One set of code may rely on datain multiple places. Multiple sets of code and data are required to work

    together. Changes made to any of the code sets and data sets can causeproblems through out the system.Object-Oriented programming takes a radically

    different approach:Code and data are merged into one indivisible item an object(the

    term component has also been used to describe an object.) An object isan abstraction of a set of real-world things (for example, an object may

    be created around date) The object would contain all information andfunctionality for that thing (A date

    object it may contain labels like January, February, Tuesday, Wednesday.It may contain functionality that manages leap years, determines if it

    is a business day or a holiday, etc., See Fig. 1). Ideally, information

  • 8/22/2019 PHP Interview Question and Answers1

    8/36

    about a particular thing should reside in only one place in a system.

    The information within an object is encapsulated (or hidden) from therest of the system.

    A system is composed of multiple objects (i.e., date function, reports,order processing, etc., See Fig 2). When one object needs information

    from another object, a request is sent asking for specific information.

    (for example, a report object may need to know what todays date is andwill send a request to the date object) These requests are calledmessages and each object has an interface that manages messages.

    OO programming languages include features such as class, instance,inheritance, and polymorphism that increase the power and

    flexibility of an object.

    Q:24 What is the use of friend function?

    A:24 Sometimes a function is best shared among a number of differentclasses. Such functions can be declared either as member functions ofone class or as global functions. In either case they can be set to be

    friends of other classes, by using a friend specifier in the class thatis admitting them. Such functions can use all attributes of the class

    which names them as a friend, as if they were themselves members of thatclass.

    A friend declaration is essentially a prototype for a member function,but instead of requiring an implementation with the name of that class

    attached by the double colon syntax, a global function or memberfunction of another class provides the match.

    Q:25 What are the differences between public, private, protected,static, transient, final and volatile?

    A:25 Public: Public declared items can be accessed everywhere.

    Protected: Protected limits access to inherited and parentclasses (and to the class that defines the item).

    Private: Private limits visibility only to the class that definesthe item.

    Static: A static variable exists only in a local function scope,but it does not lose its value when program execution leaves this scope.

    Final: Final keyword prevents child classes from overriding amethod by prefixing the definition with final. If the class itself is

    being defined final then it cannot be extended.transient: A transient variable is a variable that may notbe serialized.volatile: a variable that might be concurrently modified by multiple

    threads should be declared volatile. Variables declared to be volatilewill not be optimized by the compiler because their value can change atany time.

    Q:26 What are the different types of errors in PHP?

    A:26 Three are three types of errors:1. Notices: These are trivial,non-critical errors that PHP encounters while executing a script - forexample, accessing a variable that has not yet been defined. By default,

  • 8/22/2019 PHP Interview Question and Answers1

    9/36

    such errors are not displayed to the user at all - although, as you will

    see, you can change this default behavior.2. Warnings: These are more seriouserrors - for example, attempting

    to include() a file which does not exist. By default, these errors aredisplayed 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 anon-existent function. These errors cause the immediate termination ofthe script, and PHPs default behavior is to display them to the user

    when they take place.

    Q:27 What is the functionality of the function strstr and stristr?

    A:27 strstr:

    Returns part ofhaystackstring from the first occurrence of

    needle to the end of

    haystack.Ifneedle is not found,returns FALSE.

    Ifneedle is not a

    string, it is converted to an integer and applied as theordinal value of a character.

    This function is case-sensitive. Forcase-insensitive searches, use

    stristr().

    Q:28 What are the differences between PHP 3 and PHP 4 and PHP 5?

    A:28 Please read the release notes athttp://www.php.net.

    Q:29 How can we convert asp pages to PHP pages?

    A:29 there are lots of tools available for asp to PHP conversion. you cansearch Google for that. the best one is available athttp://asp2php.naken.cc./

    Q:30 What is the functionality of the function htmlentities?

    A:30 Convert all applicable characters to HTML entitiesThis function is identical to htmlspecialchars() in all ways, except

    with htmlentities(), all characters which have HTML character entityequivalents are translated into these entities.

    Q:31 How can we get second of the current time using date function?

    A:31 $second = date(s);

    Q:32 How can we convert the time zones using PHP?

    http://php.net./http://asp2php.naken.cc./http://php.net./http://asp2php.naken.cc./
  • 8/22/2019 PHP Interview Question and Answers1

    10/36

    A:32 By using date_default_timezone_get anddate_default_timezone_set function on PHP 5.1.0

    Q:33 What is meant by urlencode and urldocode?

    A:33 URLencode returns a string in which all non-alphanumeric charactersexcept -_. have been replaced with a percent (%)

    sign followed by two hex digits and spaces encoded as plus (+)

    signs. It is encoded the same way that the posted data from a WWW formis encoded, that is the same way as in

    application/x-www-form-urlencoded media type.

    urldecode decodes any %##

    encoding in the given string.

    Q:34 What is the difference between the functions unlink and unset?

    A:34 unlink() deletes the given file from the file system.unset() makes a variable undefined.

    Q:35 How can we register the variables into a session?

    A:35 $_SESSION[name] = Mizan;

    Q:36 How can we get the properties (size, type, width, height) of animage using PHP image functions?

    A:36 To know the Image type use exif_imagetype () function

    To know the Image size use getimagesize () functionTo know the image width use imagesx () functionTo know the image height use imagesy() function t

    Q:37 How can we get the browser properties using PHP?

    A:37 By using$_SERVER['HTTP_USER_AGENT']variable.

  • 8/22/2019 PHP Interview Question and Answers1

    11/36

    Q:38 What is the maximum size of a file that can be uploaded using PHPand how can we change this?

    A:38 By default the maximum size is 2MB. and we can change the followingsetup at php.iniupload_max_filesize = 2M

    Q:39 How can we increase the execution time of a PHP script?

    A:39 by changing the following setup at php.inimax_execution_time = 30; Maximum execution time of each script, in seconds

    Q:40 How can we take a backup of a MySQL table and how can we restoreit. ?

    A:40 To backup: BACKUP TABLE tbl_name[,tbl_name] TO/path/to/backup/directoryRESTORE TABLE tbl_name[,tbl_name] FROM

    /path/to/backup/directorymysqldump: Dumping Table Structure and DataUtility todump a database or a collection of database for backup or

    for transferring the data to another SQL server (not necessarily a MySQLserver). The dump will contain SQL statements to create the table and/or

    populate the table.-t, no-create-info

    Dont write table creation information (the CREATE TABLE statement).-d, no-data

    Dont write any row information for the table. This is very useful ifyou just want to get a dump of the structure for a table!

    Q:41 How can we optimize or increase the speed of a MySQL select

    query?A:41 first of all instead of using select * from table1, use select

    column1, column2, column3.. from table1

    Look for the opportunity to introduce index in the table you are

    querying.

    use limit keyword if you are looking for any specific number of

    rows from the result set.

    Q:42 How many ways can we get the value of current session id?

    A:42 session_id() returns the session id for the current session.

    Q:43 How can we destroy the session, how can we unset the variable ofa session?

    A:43 session_unregister Unregister a global variable from the currentsessionsession_unset Free all session variables

  • 8/22/2019 PHP Interview Question and Answers1

    12/36

    Q:44 How can we destroy the cookie?

    A:44 Set the cookie in past.

    Q:45 How many ways we can pass the variable through the navigationbetween the pages?

    A:45 GET/QueryString

    POST

    Q:46 What is the difference between ereg_replace() and eregi_replace()?

    A:46 eregi_replace() function is identical to ereg_replace() except thatthis ignores case distinction when matching alphabetic

    characters.eregi_replace() function is identical to ereg_replace()except that this ignores case distinction when matching alphabetic

    characters.

    Q:47 What are the different functions in sorting an array?

    A:47 Sort(), arsort(),asort(), ksort(),natsort(), natcasesort(),

    rsort(), usort(),array_multisort(), and

    uksort().

    Q:48 How can we know the count/number of elements of an array?

    A:48 2 ways

    a) sizeof($urarray) This function is an alias of count()b) count($urarray)

    Q:49 What is the PHP predefined variable that tells the What types ofimages that PHP supports?

    A:49 Though i am not sure if this is wrong or not, With the exifextension you are able to work with image meta data.

    Q:50 How can I know that a variable is a number or not using aJavaScript?

    A:50 bool is_numeric ( mixed var)Returns TRUE if var is a number or a numeric string, FALSE otherwise.or useisNaN(mixed var)The isNaN() function is used to check if a value is not a number.

    Q:51 List out some tools through which we can draw E-R diagrams formysql.

    A:51 Case StudioSmart Draw

  • 8/22/2019 PHP Interview Question and Answers1

    13/36

    Q:52 How can I retrieve values from one database server and store themin other database server using PHP?

    A:52 we can always fetch from one database and rewrite to another. hereis a nice solution of it.$db1 = mysql_connect(host,user,pwd)

    mysql_select_db(db1, $db1);$res1 = mysql_query(query,$db1);$db2 = mysql_connect(host,user,pwd)mysql_select_db(db2, $db2);

    $res2 = mysql_query(query,$db2);At this point you can only fetch records from

    you previous ResultSet,i.e $res1 - But you cannot execute new query in $db1, even if you

    supply the link as because the link was overwritten by the new db.so at this pointthe following script will fail

    $res3 = mysql_query(query,$db1); //this will failSo how to solve that?

    take a look below.

    $db1 = mysql_connect(host,user,pwd)mysql_select_db(db1, $db1);

    $res1 = mysql_query(query,$db1);

    $db2 = mysql_connect(host,user,pwd, true)

    mysql_select_db(db2, $db2);$res2 = mysql_query(query,$db2);

    So mysql_connect has another optional boolean parameter which

    indicates whether a link will be created or not. as we connect to the

    $db2 with this optional parameter set to true, so both link willremain live.

    now the following query will execute successfully.

    $res3 = mysql_query(query,$db1);

    Thanks goes to Hasan and Hasin for this solution.

    Q:53 List out the predefined classes in PHP?

    A:53 DirectorystdClass

    __PHP_Incomplete_Class

    exceptionphp_user_filter

    Q:54 How can I make a script that can be bi-language (supportsEnglish, German)?

    A:54 You can maintain two separate language file for each of thelanguage. all the labels are putted in both language files as variables

    and assign those variables in the PHP source. on runtime choose the

    required language option.

  • 8/22/2019 PHP Interview Question and Answers1

    14/36

    Q:55 What are the difference between abstract class and interface?

    A:55 Abstract class: abstract classes are the class where one or moremethods are abstract but not necessarily all method has to be abstract.

    Abstract methods are the methods, which are declare in its class but notdefine. The definition of those methods must be in its extending class.Interface:

    Interfaces are one type of class where all the methods areabstract. That means all the methods only declared but not defined. All

    the methods must be define by its implemented class.

    Q:56 How can we send mail using JavaScript?

    A:56 JavaScript does not have any networking capabilities as it isdesigned to work on client site. As a result we can not send mails usingJavaScript. But we can call the client side mail protocol mailtovia JavaScript to prompt for an email to send. this requires the clientto approve it.

    Q:57 How can we repair a MySQL table?A:57 The syntex for repairing a MySQL table is

    REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended]

    This command will repair the table specified if the quick is given theMySQL will do a repair of only the index tree if the extended is given

    it will create index row by row

    Q:58 What are the advantages of stored procedures, triggers, indexes?

    A:58 A stored procedure is a set of SQL commands that can be compiled andstored in the server. Once this has been done, clients dont need to

    keep re-issuing the entire query but can refer to the stored procedure.

    This provides better overall performance because the query has to beparsed only once, and less information needs to be sent between the

    server and the client. You can also raise the conceptual level by havinglibraries of functions in the server. However, stored procedures of

    course do increase the load on the database server system, as more ofthe work is done on the server side and less on the client (application)

    side.Triggers will also be implemented. A trigger is effectively a type ofstored procedure, one that is invoked when a particular event occurs.

    For example, you can install a stored procedure that is triggered eachtime a record is deleted from a transaction table and that stored

    procedure automatically deletes the corresponding customer from acustomer table when all his transactions are deleted.Indexes are used to find rows

    with specific column values quickly.

    Without an index, MySQL must begin with the first row and then readthrough the entire table to find the relevant rows. The larger thetable, the more this costs. If the table has an index for the columns in

    question, MySQL can quickly determine the position to seek to in themiddle of the data file without having to look at all the data. If a

    table has 1,000 rows, this is at least 100 times faster than readingsequentially. If you need to access most of the rows, it is faster to

    read sequentially, because this minimizes disk seeks.

  • 8/22/2019 PHP Interview Question and Answers1

    15/36

    Q:59 What is the maximum length of a table name, database name, andfieldname in MySQL?

    A:59 The following table describes the maximum length for each type ofidentifier.

    Identifier Maximum Length(bytes)

    Database 64

    Table 64

    Column 64

    Index 64

    Alias 255

    There are some restrictions on the characters that may appear in

    identifiers:

    Q:60 How many values can the SET function of MySQL take?

    A:60 MySQL set can take zero or more values but at the maximum it cantake 64 values

    Q:61 What are the other commands to know the structure of table usingMySQL commands except explain command?

    A:61 describe Table-Name;

    Q:62 How many tables will create when we create table, what are they?

    A:62 The .frm file stores the table definition.The data file has a .MYD (MYData) extension.

    The index file has a .MYI (MYIndex) extension,

    Q:63 What is the purpose of the following files having extensions 1) .frm2) .myd 3) .myi? What do these files contain?

    A:63 In MySql, the default table type is MyISAM.Each MyISAM table is stored on disk in three files. The files have names

    that begin with the table name and have an extension to indicate thefile type.

    The .frm file stores the table definition.

    The data file has a .MYD (MYData) extension.The index file has a .MYI (MYIndex) extension,

    Q:64 What is maximum size of a database in MySQL?

    A:64 If the operating system or filesystem places a limit on the numberof files in a directory, MySQL is bound by that constraint.The efficiency of theoperating system in handling large numbers of

    files in a directory can place a practical limit on the number of tables

  • 8/22/2019 PHP Interview Question and Answers1

    16/36

    in a database. If the time required to open a file in the directory

    increases significantly as the number of files increases, databaseperformance can be adversely affected.

    The amount of available disk space limits the number of tables.MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM

    storage engine in MySQL 3.23, the maximum table size was increased to

    65536 terabytes (2567 1 bytes). With this larger allowed table size,the maximum effective table size for MySQL databases is usuallydetermined by operating system constraints on file sizes, not by MySQL

    internal limits.The InnoDB storage engine maintains InnoDB tables within atablespace

    that can be created from several files. This allows a table to exceedthe maximum individual file size. The tablespace can include raw disk

    partitions, which allows extremely large tables. The maximum tablespace

    size is 64TB.The following table lists some examples of operating system file-size

    limits. This is only a rough guide and is not intended to be definitive.

    For the most up-to-date information, be sure to check the documentationspecific to your operating system.

    Operating System File-size LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB)Linux 2.4+ (using ext3 filesystem) 4TB

    Solaris 9/10 16TBNetWare w/NSS filesystem 8TB

    Win32 w/ FAT/FAT32 2GB/4GBWin32 w/ NTFS 2TB (possibly larger)

    MacOS X w/ HFS+ 2TB

    Q:65 Give the syntax of Grant and Revoke commands?

    A:65 The generic syntax for grant is as following> GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY

    [password]now rights can bea) All privileges

    b) combination of create, drop, select, insert, update and delete etc.We can grantrights on all databse by using *.* or some specific

    database by database.* or a specific table by database.table_nameusername@hotsname can be either username@localhost, username@hostname

    and username@%where hostname is any valid hostname and % represents any name, the *.*

    any conditionpassword is simply the password of userThe generic syntax for revoke is as

    following> REVOKE [rights] on [database/s] FROM [username@hostname]

    now rights can be as explained abovea) All privileges

    b) combination of create, drop, select, insert, update and delete etc.username@hotsname can be either username@localhost, username@hostname

    and username@%where hostname is any valid hostname and % represents any name, the *.*

    any condition

  • 8/22/2019 PHP Interview Question and Answers1

    17/36

    Q:66 Explain Normalization concept?

    A:66 The normalization process involves getting our data to conform tothree progressive normal forms, and a higher level of normalization

    cannot be achieved until the previous levels have been achieved (thereare actually five normal forms, but the last two are mainly academic and

    will not be discussed).First Normal FormThe First Normal Form (or 1NF) involvesremoval of redundant data

    from horizontal rows. We want to ensure that there is no duplication ofdata in a given row, and that every column stores the least amount of

    information possible (making the field atomic).Second Normal FormWhere the First

    Normal Form deals with redundancy of data across ahorizontal row, Second Normal Form (or 2NF) deals with redundancy of

    data in vertical columns. As stated earlier, the normal forms are

    progressive, so to achieve Second Normal Form, your tables must alreadybe in First Normal Form.Third Normal Form

    I have a confession to make; I do not often use Third Normal Form. InThird Normal Form we are looking for data in our tables that is not

    fully dependant on the primary key, but dependant on another value inthe table

    Q:67 How can we find the number of rows in a table using MySQL?

    A:67 Use this for mysql>SELECT COUNT(*) FROM table_name;

    Q:68 How can we find the number of rows in a result set using PHP?

    A:68 $result = mysql_query($sql, $db_link);$num_rows = mysql_num_rows($result);echo $num_rows rows found;

    Q:69 How many ways we can we find the current date using MySQL?

    A:69 SELECT CURDATE();CURRENT_DATE() = CURDATE()for time use

    SELECT CURTIME();CURRENT_TIME() = CURTIME()

    Q:70 What are the advantages and disadvantages of Cascading StyleSheets?

    A:70 External Style SheetsAdvantagesCan control styles for multiple documents at once.Classes can becreated for use on multiple HTML element types in many documents.

    Selector and grouping methods can be used to apply styles under complexcontextsDisadvantagesAn extra download is required to import style information for

    eachdocument The rendering of the document may be delayed until the external

    style sheet is loaded Becomes slightly unwieldy for small quantities ofstyle definitionsEmbedded Style Sheets

  • 8/22/2019 PHP Interview Question and Answers1

    18/36

    Advantages

    Classes can be created for use on multiple tag types in the document.Selector and grouping methods can be used to apply styles under complex

    contexts. No additional downloads necessary to receive style information

    Disadvantages

    This method can not control styles for multiple documents at once

    Inline Styles

    Advantages

    Useful for small quantities of style definitions. Can override otherstyle specification methods at the local level so only exceptions need

    to be listed in conjunction with other style methods

    Disadvantages

    Does not distance style information from content (a main goal of

    SGML/HTML). Can not control styles for multiple documents at once.Author can not create or control classes of elements to control multiple

    element types within the document. Selector grouping methods can not beused to create complex element addressing scenarios

    Q:71 What type of inheritance that PHP supports?

    A:71 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.

    Q:72 What is the difference between Primary Key andUnique key?

    A:72 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.

    Q:73The structure of table view buyers is as follows:

    Field Type Null Key Default Extra

    user_pri_id int(15) PRI null auto_increment

    userid varchar(10) YES null

  • 8/22/2019 PHP Interview Question and Answers1

    19/36

    the value of user_pri_id the last row 999 then What will happen in

    the following conditions?

    Condition1: Delete all the rows and insert another row then.What is the starting value for this auto incremented field user_pri_id ,

    Condition2: Delete the last row(having the field value 999) andinsert another row then. What is the value for this auto incremented

    field user_pri_id

    A:73 In both cases let the value for auto increment field be n then nextrow will have value n+1 i.e. 1000

    Q:74 What are the advantages/disadvantages of MySQL and PHP?

    A:74 Both of them are open source software (so free of cost), supportcross platform. php is faster then ASP and JSP.

    Q:75 What is the difference between GROUP BY and ORDER BY in Sql?

    A:75 ORDER BY [col1],[col2],,[coln]; Tels DBMS according to what columnsit should sort the result. If two rows will hawe the same value in col1

    it will try to sort them according to col2 and so on.GROUP BY[col1],[col2],,[coln]; Tels DBMS to group results with same value of

    column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, ifyou want to count all items in group, sum all values or view average

    Q:76 What is the difference between char and varchar data types?

    A:76 Set char to occupy n bytes and it will take n bytes even if u rstoring a value of n-m bytes

    Set varchar to occupy n bytes and it will take only the required spaceand will not use the n bytes

    eg. name char(15) will waste 10 bytes if we store mizan, if each chartakes a byte

    eg. name varchar(15) will just use 5 bytes if we store mizan, if eachchar takes a byte. rest 10 bytes will be free.

    Q:77 What is the functionality of md5 function in PHP?

    A:77 Calculate the md5 hash of a string. The hash is a 32-characterhexadecimal number. I use it to generate keys which I use to identify

    users etc. If I add random no techniques to it the md5 generated nowwill be totally different for the same string I am using.

    Q:78 How can I load data from a text file into a table?

    A:78 you can use LOAD DATA INFILE file_name; syntax to load datafrom a text file. but you have to make sure thata) data is delimited

    b) columns and data matched correctly

  • 8/22/2019 PHP Interview Question and Answers1

    20/36

    Q:79 How can we know the number of days between two given dates usingMySQL?

    A:79 SELECT DATEDIFF(2007-03-07,2005-01-01);

    Q:80 How can we know the number of days between two given dates using

    PHP?

    A:80 $date1 = date(Y-m-d);$date2 = 2006-08-15;$days = (strtotime($date1) - strtotime($date2)) / (60 * 60 * 24);

    Q:81 What is float property in CSS?

    A:81 The float property sets where an image or a text will appear in another element.

    Q:82 What is descendant structure in CSS?

    A:82 Descendant selectors are used to select elements that are descendants of anotherelement in the document tree.For example, you may wish to target a specific element on the page, but not all elements. A sample document could

    contain the following code: Heading here Lorem ipsum dolor sit amet.

    The document tree diagram (with the element to be targeted)

    would be: If you use a type selector like the example below,

    you will select all elements on the page:

    em {color: blue; } However, if you use a descendant selector, you can refine

    the elements that you select. The rule below will only select elementsthat are descendants of

    elements. If this rule is applied, the element

    within the will not be colored blue.

    p em {color: blue; } You can also jump levels in the document tree structure

    to select descendants. For example, the following code:

    Lorem ipsum dolor sit amet.

    item 1

  • 8/22/2019 PHP Interview Question and Answers1

    21/36

    item 2

    item 3

    The document tree (with a third-level element highlighted) would

    be:

    Using the following rule you can isolate any element inside a element,without having to describe the element. If this rule is applied, any

    element within a element will be colored blue. However, the elementwithin the

    will not be colored blue:

    ul em {color: blue; } Descendant selectors are well supported across

    standards-compliant browsers.

    Q:83 What is Child Descendant structure in CSS?

    A:83 Child selectors

    A child selector is used to select an element that is a direct child of anotherelement (parent). Child selectors will not select all descendants, only direct

    children.

    For example, you may wish to target an that is a direct child of a , but

    not other elements that are descendants of the . A sample document

    could contain the following code:

    Heading text

    This is some text

    This is a paragraph of text

    The document tree (highlighting the that is a child of the

  • 8/22/2019 PHP Interview Question and Answers1

    22/36

    Using the following rule you can target any element that is a child of the

    . Other elements that are descendants but not direct children of the will not be targeted.

    div > em { color: blue; }

    OR

    div>em { color: blue; }Child selectors are not supported by Windows Internet Explorer 5, 5.5 and 6, butare supported by most other standards-compliant browsers.

    Q:84 How to create a class in JavaScript?

    A:84 Classes can seem off-putting at first, but once you see the point of them, their usecan be invaluable.We have already met objects. A computer object is a

    representation of a real object. For an estate agent the object may be a house,including information about the number of rooms and the price.An estate agent

    may have a lot of houses available. These houses all have different characteristics,and as objects they all go through the same processes. They are viewed, surveyed

    and bought, and so on.A full estate agent program would be difficult todemonstrate here, but we can introduce the use of classes.In this example, we

    have the house class. The house class produces house objects, all with objectproperties, such as number of rooms and price, and all having access to the same

    methods, such as sold and bought.

    So a class can create objects with a group of properties and methods.

    JavaScript doesnt have a keyword specific to class, so we must go back to basicsand develop classes in a different way. This isnt very difficult.

    Class Properties

    Let us examine a very small estate agent program.

    Estate Agent

    http://www.webdevelopersjournal.com/articles/jsintro3/estateagent.htmhttp://www.webdevelopersjournal.com/articles/jsintro3/estateagent.htm
  • 8/22/2019 PHP Interview Question and Answers1

    23/36

    function House(rooms,price,garage) {

    this.rooms=rooms;this.price=price;

    this.garage=garage;}

    house1=new House(4,100000,false);house2=new House(5,200000,true);

    with (house1) document.write(House 1 has +rooms+ rooms, +(garage?a':no)+ garage, and costs +price+
    );

    with (house2) document.write(House 2 has +rooms+ rooms, +(garage?a':no)

    + garage, and costs +price+
    );

    We define a House function that takes three parameters, rooms, price and garage.

    The function uses the this keyword to create an object.

    When we call the House function, we assign the result to our variable, which

    becomes an object.

    So, identical code would be:

    house1=new Object();

    house1.rooms=4;

    house1.price=100000;house1.garage=false;

    We would have to type this in for all houses, which would be very tedious and is

    why we use the class structure instead.

    When we display the details for a house, I have introduced the ternary operator,?:. The ternary operator is a compacted version of:

    if (garage) str=a'; else str=no;

    (garage?a':no) means if garage is true, return a else return no. Using theternary operator removes a line of code, and avoids having to create a new

    variable.

    Class Methods

    The House class we have so far defined only contains object properties. We could

    add a method to replace the document.write() action we used before. (Seeexample)

    Estate Agent 2

    http://www.webdevelopersjournal.com/articles/jsintro3/estateagent2.htmhttp://www.webdevelopersjournal.com/articles/jsintro3/estateagent2.htmhttp://www.webdevelopersjournal.com/articles/jsintro3/estateagent2.htmhttp://www.webdevelopersjournal.com/articles/jsintro3/estateagent2.htm
  • 8/22/2019 PHP Interview Question and Answers1

    24/36

    function House(name,rooms,price,garage) {

    this.name=name;this.rooms=rooms;

    this.price=price;this.garage=garage;

    this.view=view;}

    function view() {with (this) document.write(name+ has +rooms+ rooms, +(garage?a':no)+

    garage, and costs +price+
    );

    }house1=new House(House 1,4,100000,false);

    house2=new House(Big House,5,200000,true);

    house1.view();house2.view();

    Much better!

    Note how we must add another property, name, so that we can identify the housein question. This offers more flexibility than re-using the variable name, and the

    variable name is inaccessible anyway, i.e. it is very difficult, if not impossible, toget the view() function to use the string house1.

    Q:85 Are namespaces are there in JavaScript?

    A:81 A namespace is a container and allows you to bundle up all your functionality usinga unique name. In JavaScript, a namespace is really just an object that youve

    attached all further methods, properties and objects. But it is not always necessaryto use namespace.

    Q:86 What is JSON? What are the notations used in JSON?

    A:86 JSON (JavaScript Object Notation) is a lightweight data-interchange format. It iseasy for humans to read and write. It is easy for machines to parse and generate.

    It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely

    language independent but uses conventions that are familiar to programmers ofthe C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python,

    and many others. These properties make JSON an ideal data-interchange

    language.

    Q:87 How to get Query String in PHP for http request?

    A:87 $_GET[] and $_REQUEST[]

    Q:88 How to get the http Request in PHP?

    A:88 When PHP is used on a Web server to handle a HTTP request, it converts

    http://javascript.crockford.com/http://www.ecma-international.org/publications/files/ecma-st/ECMA-262.pdfhttp://www.ecma-international.org/publications/files/ecma-st/ECMA-262.pdfhttp://javascript.crockford.com/http://www.ecma-international.org/publications/files/ecma-st/ECMA-262.pdfhttp://www.ecma-international.org/publications/files/ecma-st/ECMA-262.pdf
  • 8/22/2019 PHP Interview Question and Answers1

    25/36

    information submitted in the HTTP request as predefined variables:

    $_GET - Associate array of variables submitted with GET method.

    $_POST - Associate array of variables submitted with POST method.

    $_COOKIE - Associate array of variables submitted as cookies.

    $_REQUEST - Associate array of variables from $_GET, $_POST, and

    $_COOKIE.

    $_SERVER - Associate array of all information from the server and the HTTP

    request.

    Q:89 How you provide security for PHP application?

    A:89 There are many ways to accomplish the security tasks but the most common 7ways are1. Validate Input. Never trust your user and always filter input beforetaking it to any operation.2. Provide access control.3. Session ID protection4.

    preventing Cross Site Scripting (XSS) flaws

    5. SQL injection vulnerabilities.

    6. Turning off error reporting and exposing to the site for hackers. Instead use logfile to catch exceptions

    7. Effective Data handling

    Q:90 What is SQL Injection in PHP security?

    A:90 SQL injection attacks are extremely simple to defend against, but manyapplications are still vulnerable. Consider the following SQL statement:

  • 8/22/2019 PHP Interview Question and Answers1

    26/36

    statement becomes the following:

  • 8/22/2019 PHP Interview Question and Answers1

    27/36

    many sites. Lets say we are taking some information passed in on a querystring

    (the string after the (?) character within a URL), with the purpose of displaying thecontent of a variable, for example, the visitors name:

    http://www.yourdomain.com/welcomedir/welcomepage.php?name=John

    As we can see in this simple querystring, we are passing the visitors name as a

    parameter in the URL, and then displaying it on our welcomepage.php page withthe following PHP code:

    The result of this snippet is shown below:

    Welcome to our site John

    This is pretty simple and straightforward. Were displaying the content of thename variable, by using the $_GET superglobal PHP array, as we have done

    probably hundreds of times. Everything seems to be fine. Now, whats wrong with

    this code? Nothing really. But lets modify the querystring by replacing our visitorsname passed in the URL:

    http://www.yourdomain.com/welcomedir/welcomepage.php?name=John

    with something like this:

    http://www.yourdomain.com/welcomedir/welcomepage.php?name=alert(Hey, you are going to be hijacked!);

    Do you remember the PHP code included in our welcome.php page? Yes, youre

    correct. When we modify the querystring, the following code is executed:

    The output of this code is an alert JavaScript box telling you Hey, you are going behijacked! after the Welcome to our site phrase.

    Very ugly stuff, right? Thats a simple example of the Cross Site Scriptingvulnerability. This means that any pasted JavaScript code into the URL will be

    executed happily with no complaints at all.

    Q:92 Which method do you follow to get a record from a million records?(Searching, . not from database, from an array in php)

    A:92 use array_search(), array_keys(), array_values(), array_key_exists(), andin_array().

    http://www.devshed.com/http://www.devshed.com/
  • 8/22/2019 PHP Interview Question and Answers1

    28/36

    Q:93 Which sorting method is lowest time consumable?

    A:93 HeapSort, Merge sort are the lowest time consumable sorting algorithm.

    Q:94 Which sorting method is lowest memory consumable?A:94

    95. What is meant by PEAR in php?

    Answer:PEAR is short for PHP Extension and Application Repository and is pronounced justlike the fruit. The purpose of PEAR is to provide:A structured library of open-sourced code for PHP usersA system for code distribution and package maintenance

    A standard style for code written in PHPThe PHP Foundation Classes (PFC),The PHP Extension Community Library (PECL),A web site, mailing lists and download mirrors to support the PHP/PEAR communityPEAR is a community-driven project with the PEAR Group as the governing body. Theproject has been founded by Stig S. Bakken in 1999 and quite a lot of people have joinedthe project since then.

  • 8/22/2019 PHP Interview Question and Answers1

    29/36

    96. How can I use the COM components in php?

    Answer:

    The COM class provides a framework to integrate (D)COM components into your PHPscripts.string COM::COM ( string module_name [, string server_name [, int codepage]])

    COM class constructor. Parameters:module_namename or class-id of the requested component.server_namename of the DCOM server from which the component should be fetched. If NULL,localhost is assumed. To allow DCOM com.allow_dcom has to be set to TRUE inphp.ini.codepagespecifies the codepage that is used to convert php-strings to unicode-strings and viceversa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL,CP_THREAD_ACP, CP_UTF7 and CP_UTF8.

    Usage:Version}\n"; //bring it to front $word->Visible = 1; //open an empty document $word->Documents->Add(); //do some weird stuff $word->Selection->TypeText("This is atest..."); $word->Documents[1]->SaveAs("Useless test.doc"); //closing word $word->Quit(); //free the object $word->Release(); $word = null; ?>

    97. How can I load the dlls dynamically?

    98. How many ways we can give the output to a browser?Answer:

    HTML outputPHP, ASP, JSP, Servlet FunctionScript Language output FunctionDifferent Type of embedded Package to output to a browser

    99. How can we know that a session is started or not?Answer:

    a session starts by session_start()function.this session_start() is always declared in header portion.it always declares first.then wewrite session_register().

    100. What is the default session time in php and how can I change it?Answer:

    The default session time in php is until closing of browser

    101. What changes I have to done in php.ini file for file uploading?Answer:

    Make the following Line uncomment like:; Whether to allow HTTP file uploads.file_uploads = On

  • 8/22/2019 PHP Interview Question and Answers1

    30/36

    ; Temporary directory for HTTP uploaded files (will use system default if not; specified).upload_tmp_dir = C:\apache2triad\temp; Maximum allowed size for uploaded files.upload_max_filesize = 2M

    102. What are the differences between mysql_fetch_array(), mysql_fetch_object(),

    mysql_fetch_row()?

    Answer:mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both.mysql_fetch_object ( resource result )Returns an object with properties that correspond to the fetched row and moves theinternal data pointer ahead. Returns an object with properties that correspond to thefetched row, or FALSE if there are no more rowsmysql_fetch_row() fetches one row of data from the result associated with the specifiedresult identifier. The row is returned as an array. Each result column is stored in an array

    offset, starting at offset 0.

    103. How can I set a cron and how can I execute it in Unix, Linux, and windows?Answer:

    Cron is very simply a Linux module that allows you to run commands at predeterminedtimes or intervals. In Windows, its called Scheduled Tasks. The name Cron is in factderived from the same word from which we get the word chronology, which means orderof time.The easiest way to use crontab is via the crontab command.# crontab eThis command edits the crontab. Upon employing this command, you will be able toenter 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 notfunction properly. The syntax of the file should be as follows:minutes hours day_of_month month day_of_week commandAll the variables, with the exception of the command itself, are numerical constants. Inaddition to an asterisk (*), which is a wildcard that allows any value, the ranges permittedfor each field are as follows:Minutes: 0-59Hours: 0-23Day_of_month: 1-31Month: 1-12Weekday: 0-6We can also include multiple values for each entry, simply by separating each value witha comma.command can be any shell command and, as we will see momentarily, can also be used toexecute 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 willcontain the following content on a single line:

  • 8/22/2019 PHP Interview Question and Answers1

    31/36

    15 8 * * 2 /path/to/scriptnameThis all seems simple enough, right? Not so fast! If you try to run a PHP script in thismanner, nothing will happen (barring very special configurations that have PHP compiledas an executable, as opposed to an Apache module). The reason is that, in order for PHPto 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, Ill assume that your server configuration includes wget, as is the casewith most default configurations. To test your configuration, log in to shell. If youreusing an RPM-based system (e.g. Redhat or Mandrake), type the following:# wget --helpIf 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.phpNow, lets go back to the mailstock.php file we created in the first part of this article. Wesaved it in our document root, so it should be accessible via the Internet. Remember thatwe wanted it to run at 4PM Eastern time, and send you your precious closing bell report?

    Since Im located in the Eastern timezone, we can go ahead and set up our crontab to use4:00, but if you live elsewhere, you might have to compensate for the time differencewhen setting this value.This is what my crontab will look like:0 4 * * 1, 2,3,4,5

    104. Steps for the payment gateway processing?

    Ans:

    An online payment gateway is the interface between your merchant account and yourWeb site. The online payment gateway allows you to immediately verify credit cardtransactions and authorize funds on a customer's credit card directly from your Web site.It then passes the transaction off to your merchant bank for processing, commonlyreferred to as transaction batching

    105. How many ways I can register the variables into session?

    Answer:session_register(); $_SESSION[]; $HTTP_SESSION_VARS[];

    106. Explain different types of errors in php (i.e. arguments in error reportingfunction)?

    Answer:

    Three are three types of errors:1. Notices: These are trivial, non-critical errors that PHP encounters while executing ascript - for example, accessing a variable that has not yet been defined. By default, sucherrors are not displayed to the user at all - although, as you will see, you can change thisdefault behaviour.2. Warnings: These are more serious errors - for example, attempting to include() a filewhich does not exist. By default, these errors are displayed to the user, but they do notresult in script termination.3. Fatal errors: These are critical errors - for example, instantiating an object of a non-

  • 8/22/2019 PHP Interview Question and Answers1

    32/36

    existent class, or calling a non-existent function. These errors cause the immediatetermination of the script, and PHP's default behaviour is to display them to the user whenthey take place.

    107. How many ways I can redirect a php page?

    Answer;Here are the possible ways of php page redirection.Using Java script:'; echo 'window.location.href="'.$filename.'";'; echo ''; echo ''; echo ''; echo ''; } }redirect('http://maosjb.com'); ?>Using php function:Header("Location:http://maosjb.com ");

    108. List out different arguments in php header function?

    Answer:

    void header ( string string [, bool replace [, int http_response_code]])

    109. What type of headers have to add in the mail function in which file a attached?

    Answer:$boundary = '-----=' . md5( uniqid ( rand() ) );$headers = "From: \"Me\"\n";$headers .= "MIME-Version: 1.0\n";$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"";

    111. What are the differences between php3 and php4 versions?Answer:

    As has already been mentioned by many PHP4 has native support for sessionsand the much touted XML. While this makes PHP a competitor in theApplication server languages arena, there is another core aspect to PHP4. Itis faster.PHP3 used to parse line by line, while PHP acts like a compiler. This alongwith the ZEND optimizer makes PHP4 almost always faster than PHP3.I'm not sure about support for COM, it has caught my attention only in PHP4.If it was present in PHP3 I was not aware of it.Plus PHP4 can run as an Apache module, again this could have come in thelate versions of PHP3.

    112. What are the differences between include() and include_once()functions?

    Answer:

    include_once() will use the specified file only once. include and require will use thespecified file as many time we want. If include_once() is used before with same name, itcan not done again

    114. Explain mysql optimization?Answer:

  • 8/22/2019 PHP Interview Question and Answers1

    33/36

    Optimization is a complex task because ultimately it requires understanding of the entiresystem. Although it may be possible to perform some local optimizations with littleknowledge of your system or application, the more optimal you want your system tobecome, the more you will have to know about it. The most important factor in making asystem fast is the basic design. You also need to know what kinds of things your system

    will be doing, and what your bottlenecks are.

    115. What is the difference between using copy() and move() function

    in php file uploading?copy ( string source, string dest)Makes a copy of the file source to dest. Returns TRUE on success or FALSE on failure.Usage: \n"; } ?>move_uploaded_file ( string filename, string destination)This function checks to ensure that the file designated by filename is a valid upload file(meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file isvalid, it will be moved to the filename given by destination.

    If filename is not a valid upload file, then no action will occur, and move_uploaded_file()will return FALSE.If filename is a valid upload file, but cannot be moved for some reason, no action willoccur, and move_uploaded_file() will return FALSE. Additionally, a warning will beissued.

    116. What is the difference between Reply-to and Return-path in the headers of a

    mail function?

    Answer:

    Reply-to: Reply-to is where to delivery the reply of the mail.Return-path: Return path is when there is a mail delivery failure occurs then where todelivery the failure notification.

    117. Explain about Type Juggling in php?

    Answer:

    PHP does not require (or support) explicit type definition in variable declaration; avariable's type is determined by the context in which that variable is used. That is to say,if you assign a string value to variable $var, $var becomes a string. If you then assign aninteger value to $var, it becomes an integer.An example of PHP's automatic type conversion is the addition operator '+'. If any of theoperands is a float, then all operands are evaluated as floats, and the result will be a float.Otherwise, the operands will be interpreted as integers, and the result will also be aninteger. Note that this does NOT change the types of the operands themselves; the onlychange is in how the operands are evaluated.$foo = "0"; // $foo is string (ASCII 48)

    $foo += 2; // $foo is now an integer (2)$foo = $foo + 1.3; // $foo is now a float (3.3)$foo = 5 + "10 Little Piggies"; // $foo is integer (15)$foo = 5 + "10 Small Pigs"; // $foo is integer (15)

  • 8/22/2019 PHP Interview Question and Answers1

    34/36

    ?>If the last two examples above seem odd, see String conversion to numbers.If you wish to change the type of a variable, see settype().If you would like to test any of the examples in this section, you can use the var_dump()

    function.Note: The behavior of an automatic conversion to array is currently undefined.$a = "1"; // $a is a string$a[0] = "f"; // What about string offsets? What happens??>Since PHP (for historical reasons) supports indexing into strings via offsets using thesame syntax as array indexing, the example above leads to a problem: should $a becomean array with its first element being "f", or should "f" become the first character of thestring $a?The current versions of PHP interpret the second assignment as a string offsetidentification, so $a becomes "f", the result of this automatic conversion however should

    be considered undefined. PHP 4 introduced the new curly bracket syntax to accesscharacters in string, use this syntax instead of the one presented above:$a = "abc"; // $a is a string$a{1} = "f"; // $a is now "afc"?>

    118. How can I get the only name of the current executing file?

    $curfilename = __FILE__; //current file name with full path$pieces = explode("\\", $curfilename);$onlyfilenamewithext = $pieces[count($pieces)-1]; //current file name with extensiononly$temp = explode(".",$onlyfilenamewithext);$onlyfilename = $temp[0]; //current file name without extensionecho $onlyfilename;?>

    119. How can I embed a java programme in php file and what changes

    have to be done in php.ini file?

    There are two possible ways to bridge PHP and Java: you can either integrate PHP into aJava Servlet environment, which is the more stable and efficient solution, or integrateJava support into PHP. The former is provided by a SAPI module that interfaces with theServlet server, the latter by this Java extension.The Java extension provides a simple and effective means for creating and invokingmethods on Java objects from PHP. The JVM is created using JNI, and everything runsin-process.Example Code:getProperty('java.version') . ''; echo 'Java vendor=' . $system->getProperty('java.vendor') . ''; echo 'OS=' . $system->getProperty('os.name') . ' ' . $system->getProperty('os.version') . 'on ' . $system->getProperty('os.arch') . '

  • 8/22/2019 PHP Interview Question and Answers1

    35/36

    '; // java.util.Date example $formatter = new Java('java.text.SimpleDateFormat', "EEEE,MMMM dd, yyyy 'at' h:mm:ss a zzzz"); echo $formatter->format(newJava('java.util.Date')); ?>The behaviour of these functions is affected by settings in php.ini.Table 1. Java configuration options

    NameDefaultChangeablejava.class.pathNULLPHP_INI_ALLName Default Changeablejava.homeNULLPHP_INI_ALLjava.library.path

    NULLPHP_INI_ALLjava.libraryJAVALIBPHP_INI_ALL

    120. How can I find what type of images that the php version supports?

    Answer:

    Using Imagetypes() function we can knowUsage:

    121. The table tbl_sites contains the following data.

    -----------------------------------------------------Userid sitename country------------------------------------------------------1 sureshbabu indian2 phpprogrammer andhra3 php.net usa4 phptalk.com germany5 mysql.com usa6 sureshbabu canada7 phpbuddy.com pakistan8. phptalk.com austria9. phpfreaks.com sourthafrica10. phpsupport.net russia11. sureshbabu australia12. sureshbabu nepal13. phptalk.com italyWrite a select query that will displayed the duplicated site nameand how many times it is duplicated?

  • 8/22/2019 PHP Interview Question and Answers1

    36/36

    Answer: SELECT sitename,COUNT(sitename) AS NumOccurrencesFROM tbl_sitesGROUP BY sitemailHAVING ( COUNT(sitemail) > 1 )

    OrSELECT sitenameFROM tbl_sitesGROUP BY sitenameHAVING ( COUNT(sitename) = 1 )

    122. How can we send mail using JavaScript?Answer:

    No. You can't send mail using Javascript. But you can execute a client side email client tosend the email using mailto: code.Using clientside email client

    function myfunction(form){tdata=document.myform.tbox1.value;location="mailto:[email protected]?subject="+tdata+"/MYFORM";return true; }