Pages

Friday, August 26, 2011

PHP Interview Questions


Last few days I have been working to compile a question and answer set for PHP-MySQL interview questions. There are roughly 150 questions and i will be adding more as days to come. These questions and answers are compiled from different online resources. I am planning to make it a PDF version so that people download it and go through it offline. I hope i will be able to finish it soon.
NB: If you want to add any question, please add it to the comments section. I want to make it a big repository.
Here is the first set of 80 Questions and answer.
Q:1
What are the differences between Get and post methods in form submitting.
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 minor
stylistic 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 searches have no visible side-effects and make ideal applications of query
forms.

–>If the service associated with the processing of a form has side effects (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 form
data set, encoded using the application/x-www-form-urlencoded content type. The user agent then traverses the link to this URI. In this scenario, form data are restricted to ASCII codes.
–> If the method is “post” –, the user agent conducts an HTTP post transaction using the value of the action attribute and a message created according to the content type specified by the enctype attribute.
Quote from CGI FAQ
Firstly, the the HTTP protocol specifies
differing usages for the two methods. GET requests should always be idempotent on the server. This means that whereas one GET request might (rarely) change some state on the Server, two or more identical requests will have no further effect.
This is a theoretical point which is also good advice in practice. If a user hits “reload” on his/her browser, an
identical request will be sent to the server, potentially resulting in two identical database or guestbook entries, counter increments, etc. Browsers may reload a GET URL automatically, particularly if cacheing is disabled (as is
usually the case with CGI output), but will typically prompt the user before re-submitting a POST request. This means you’re 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 you’re using a form. There is a further practical constraint 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 don’t want the status to be 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 longer supported 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 the
Zend engine under the hood. 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 in order 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. You can even built a timer function where you can automatically submit the form after xx seconds once the loading is done (can be seen in online
test sites).



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

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



Q:5
What is the difference between mysql_fetch_object and
mysql_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 that you can only access the data by the field names, and not by their
offsets (numbers are illegal property names).



Q:6
What is the difference between $message and $$message?
A:6
It is a classic example of PHP’s variable variables. take the following 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 like this${$message} => $mizanSometimes it is convenient to be able to have variable variable
names. 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://info@abc.com’
using regular expression of PHP?

A:7
preg_match(“/^http:\/\/.+@(.+)$/”,’http://info@abc.com’,$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 of
mysql_create_db(“Database Name”)



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

A:9
The include() statement includes and evaluates the specified file.The documentation below also applies torequire(). The two constructs are identical in every way except how they handle failure. include() produces a
Warning while
require() results
in a Fatal Error. In other words, use
require() if you want a missing file to halt processing of the page.
include()
does not behave this way, the script will continue regardless.
The include_once() statement includes and evaluates the specified 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 be included 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 evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
require_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, 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 of
table 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 create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM 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 the default 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 Line Interface. Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, “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.



Q:14
Suppose your Zend engine supports the mode <? ?> Then how can u
configure your PHP Zend engine to support <?PHP ?> mode ?

A:14
In php.ini file:
set
short_open_tag=on
to 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 paypal integration 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 (<BR />) before all newlines in a string string nl2br (string); Returns string with ” inserted before all newlines. For example: echo nl2br(“god bless\n you”) will output “god bless <br /> you” to your browser.


Q:17
Draw the architecture of Zend engine?
A:17
The Zend Engine is the internal compiler and runtime engine used by PHP4. Developed by Zeev Suraski and Andi Gutmans, the Zend Engine is an abbreviation of their names. In the early days of PHP4, it worked as follows:
The PHP script was loaded by the Zend Engine and compiled into Zend opcode. Opcodes, short for operation codes, are low level binary instructions. Then the opcode was executed and the HTML generated sent
to the client. The opcode was flushed from memory after execution.Today, there are a multitude of products and techniques to help you speed up this process. In the following diagram, we show the how modern
PHP scripts work; all the shaded boxes are optional.

PHP Scripts are loaded into 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.1
MySQL: 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 and
operating systems?

A:19
All of those are open source resource. Security of Linux is very very more than windows. Apache is a better server that IIS both in functionality 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 table
using 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, and compression and uncompression:
encryption
decryption
AES_ENCRYT()
AES_DECRYPT()
ENCODE()
DECODE()
DES_ENCRYPT()
DES_DECRYPT()
ENCRYPT()
Not available
MD5()
Not available
OLD_PASSWORD()
Not available
PASSWORD()
Not available
SHA() or SHA1()
Not available
Not available
UNCOMPRESSED_LENGTH()


Q:22
What are the features and advantages of object-oriented
programming?
A:22
One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be
better at modeling the real world than is procedural programming. It
allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system


Q:23
What are the differences between procedure-oriented languages and
object-oriented languages?
A:23
Traditional programming has the following characteristics:Functions are written sequentially, so that a change in programming can affect any code that follows it. If a function is used multiple times in a system (i.e., a piece of code that 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 of code must be found, modified, and tested.
Code (sequences of computer instructions) and data (information on which the 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 data
in 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 cause problems 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 is an abstraction of a set of real-world things (for example, an object may be created around “date”) The object would contain all information and functionality 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 about a particular thing should reside in only one place in a system.
The information within an object is encapsulated (or hidden) from the rest 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 today’s date is and will send a request to the date object) These requests are called messages 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 different classes. Such functions can be declared either as member functions of one 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 that is admitting them. Such functions can use all attributes of the class
which names them as a friend, as if they were themselves members of that class.
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 member
function 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 parent classes (and to the class that defines the item).Private: Private limits visibility only to the class that defines the 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 a method 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 not be serialized.
volatile:
a variable that might be concurrently modified by multiple threads should be declared volatile. Variables declared to be volatile will not be optimized by the compiler because their value can change at any 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 – for example, accessing a variable that has not yet been defined. By default, 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 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 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 of haystack
string from the first occurrence of
needle to the end ofhaystack.If needle is not found,
returns
FALSE.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
This function is case-sensitive. For case-insensitive searches, usestristr().


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 can
search Google for that. the best one is available at
http://asp2php.naken.cc./


Q:30
What is the functionality of the function htmlentities?
A:30
Convert all applicable characters to HTML entities
This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents 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?
A:32
By using date_default_timezone_get and
date_default_timezone_set function on PHP 5.1.0
<?php
// Discover what 8am in Tokyo relates to on the East Coast of the US

// Set the default timezone to Tokyo time:
date_default_timezone_set('Asia/Tokyo');

// Now generate the timestamp for that particular timezone, on Jan 1st, 2000
$stamp = mktime(8, 0, 0, 1, 1, 2000);

// Now set the timezone back to US/Eastern
date_default_timezone_set('US/Eastern');

// Output the date in a standard format (RFC1123), this will print:
// Fri, 31 Dec 1999 18:00:00 EST
echo '<p>', date(DATE_RFC1123, $stamp) ,'</p>';?>


Q:33
What is meant by urlencode and urldocode?
A:33
URLencode returns a string in which all non-alphanumeric characters
except
-_. 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 form is 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 an
image using PHP image functions?
A:36
To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To 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.


Q:38
What is the maximum size of a file that can be uploaded using PHP
and how can we change this?
A:38
By default the maximum size is 2MB. and we can change the following
setup 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 restore
it. ?
A:40
To backup: BACKUP TABLE tbl_name[,tbl_name…] TO
‘/path/to/backup/directory’
RESTORE TABLE tbl_name[,tbl_name…] FROM ‘/path/to/backup/directory’mysqldump: Dumping Table Structure and DataUtility to dump a database or a collection of database for backup or for transferring the data to another SQL server (not necessarily a MySQL server). The dump will contain SQL statements to create the table and/or
populate the table.
-t, –no-create-info
Don’t write table creation information (the CREATE TABLE statement).
-d, –no-data
Don’t write any row information for the table. This is very useful if
you 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 of
a session?
A:43
session_unregister — Unregister a global variable from the current
session
session_unset — Free all session variables


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 navigation
between 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 that this 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 of
images that PHP supports?
A:49
Though i am not sure if this is wrong or not, With the exif
extension you are able to work with image meta data.


Q:50
How can I know that a variable is a number or not using a
JavaScript?
A:50
bool is_numeric ( mixed var)
Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(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 for
mysql.
A:51
Case Studio
Smart Draw


Q:52
How can I retrieve values from one database server and store them
in other database server using PHP?
A:52
we can always fetch from one database and rewrite to another. here
is 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 point the 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 will remain 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
Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter


Q:54
How can I make a script that can be bi-language (supports
English, German)?
A:54
You can maintain two separate language file for each of the
language. 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.


Q:55
What are the difference between abstract class and interface?
A:55
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.


Q:56
How can we send mail using JavaScript?
A:56
JavaScript does not have any networking capabilities as it is designed to work on client site. As a result we can not send mails using JavaScript. But we can call the client side mail protocol mailto via JavaScript to prompt for an email to send. this requires the client to 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 the MySQL 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 and stored in the server. Once this has been done, clients don’t 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 be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having
libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the 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 of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer 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 read through the entire table to find the relevant rows. The larger the table, 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 the middle 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 reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.


Q:59
What is the maximum length of a table name, database name, and
fieldname in MySQL?
A:59
The following table describes the maximum length for each type of
identifier.
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 can
take 64 values


Q:61
What are the other commands to know the structure of table using
MySQL 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) .frm
2) .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 the
file 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 number
of files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers of
files in a directory can place a practical limit on the number of tables
in a database. If the time required to open a file in the directory
increases significantly as the number of files increases, database
performance 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 usually
determined by operating system constraints on file sizes, not by MySQL
internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace
that can be created from several files. This allows a table to exceed
the 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 documentation
specific 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 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 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 be
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.We can grant rights on all databse by using *.* or some specific
database by database.* or a specific table by database.table_name
username@hotsname can be either username@localhost, username@hostname
and username@%
where hostname is any valid hostname and % represents any name, the *.*
any condition
password 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 above
a) 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


Q:66
Explain Normalization concept?
A:66
The normalization process involves getting our data to conform to
three progressive normal forms, and a higher level of normalization
cannot be achieved until the previous levels have been achieved (there
are actually five normal forms, but the last two are mainly academic and
will not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of redundant data
from horizontal rows. We want to ensure that there is no duplication of
data 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 a
horizontal 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 already
be in First Normal Form.Third Normal Form
I have a confession to make; I do not often use Third Normal Form. In
Third Normal Form we are looking for data in our tables that is not
fully dependant on the primary key, but dependant on another value in
the 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 Style
Sheets?
A:70
External Style SheetsAdvantagesCan control styles for multiple documents at once. Classes can be
created for use on multiple HTML element types in many documents.
Selector and grouping methods can be used to apply styles under complex
contextsDisadvantagesAn extra download is required to import style information for each
document The rendering of the document may be delayed until the external
style sheet is loaded Becomes slightly unwieldy for small quantities of
style definitionsEmbedded Style Sheets
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 other
style 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 be
used 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 and
Unique key?
A:72
Primary Key: A column in a table whose values uniquely identify the
rows in the table. A primary key value cannot be NULL.
Unique Key: Unique Keys are used to uniquely identify each row in the
table. 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 more
than one unique for a table.



Q:73
The 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

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) and
insert 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 next
row 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), support
cross 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 columns
it 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, if
you 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 r
storing a value of n-m bytes
Set varchar to occupy n bytes and it will take only the required space
and will not use the n bytes
eg. name char(15) will waste 10 bytes if we store ‘mizan’, if each char
takes a byte
eg. name varchar(15) will just use 5 bytes if we store ‘mizan’, if each
char 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-character
hexadecimal 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 now
will 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 data from a text file. but you have to make sure thata) data is delimited
b) columns and data matched correctly


Q:79
How can we know the number of days between two given dates using
MySQL?
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 another element in the document tree.For example, you may wish to target a specific <em> element on the page, but not all <em> elements. A sample document could contain the following code: <body>
<
h1>Heading <em>here</em> </h1>
<
p>Lorem ipsum dolor <em>sit</em> amet.</p>
</
body> The document tree diagram (with the <em> element to be targeted) would be:If you use a type selector like the example below, you will select all <em> elements on the page:
em {color: blue; } However, if you use a descendant selector, you can refine the <em> elements that you select. The rule below will only select <em> elements that are descendants of <p> elements. If this rule is applied, the <em> element within the <h1> 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:
<body>
<
p>Lorem ipsum dolor <em>sit</em> amet.</p>
<
ul>
<
li>item 1</li>
<
li>item 2</li>
<
li><em>item 3</em></li>
</
ul>
</
body> The document tree (with a third-level <em> element highlighted) would be:
Using the following rule you can isolate any <em> element inside a <ul> element, without having to describe the <li> element. If this rule is applied, any <em> element within a <ul> element will be colored blue. However, the <em> element within the <p> 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 another element (parent). Child selectors will not select all descendants, only direct children.
For example, you may wish to target an <em> that is a direct child of a <div>, but not other <em> elements that are descendants of the <div>. A sample document could contain the following code:
<body>
<
h1>Heading <em>text</em></h1>
<
div>
This is some <
em>text</em>
<
p>This is a paragraph of <em>text</em></p>
</
div>
</
body>The document tree (highlighting the <em> that is a child of the <div>) would be:
Using the following rule you can target any <em> element that is a child of the <div>. Other <em> elements that are descendants but not direct children of the <div> 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, but are 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 use can 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 to demonstrate 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 object properties, 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 doesn’t have a keyword specific to class, so we must go back to basics and develop classes in a different way. This isn’t very difficult.
Class Properties
Let us examine a very small estate agent program.
<HTML>
<HEAD>
<TITLE>Estate Agent</TITLE>
<SCRIPT>
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+’<BR>’);
with (house2) document.write(‘House 2 has ‘+rooms+’ rooms, ‘+(garage?’a':’no’)+’ garage, and costs £’+price+’<BR>’);
</SCRIPT>
</HEAD>
</HTML>
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 the ternary 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. (See example)
<HTML>
<HEAD>
<TITLE>Estate Agent 2</TITLE>
<SCRIPT>
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+’<BR>’);
}
house1=new House(‘House 1′,4,100000,false);
house2=new House(‘Big House’,5,200000,true);
house1.view();
house2.view();
</SCRIPT>
</HEAD>
</HTML>
Much better!
Note how we must add another property, name, so that we can identify the house in 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, to get 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 using a unique name. In JavaScript, a namespace is really just an object that you’ve attached all further methods, properties and objects. But it is not always necessary to 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 is easy 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 of the 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 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 7 ways are1. Validate Input. Never trust your user and always filter input before taking 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 log file 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 many applications are still vulnerable. Consider the following SQL statement:
<?php
$sql = "INSERT
INTO users (reg_username,
reg_password,
reg_email)
VALUES ('{$_POST['reg_username']}',
'$reg_password',
'{$_POST['reg_email']}')";
?>
This query is constructed with $_POST, which should immediately look suspicious.
Assume that this query is creating a new account. The user provides a desired username and an email address. The registration application generates a temporary password and emails it to the user to verify the email address. Imagine that the user enters the following as a username:
bad_guy', 'mypass', ''), ('good_guy
This certainly doesn’t look like a valid username, but with no data filtering in place, the application can’t tell. If a valid email address is given (shiflett@php.net, for example), and 1234 is what the application generates for the password, the SQL statement becomes the following:
<?php

$sql = "INSERT
INTO users (reg_username,
reg_password,
reg_email)
VALUES ('bad_guy', 'mypass', ''),
('good_guy',
'1234',
'shiflett@php.net')"; ?>
Rather than the intended action of creating a single account (good_guy) with a valid email address, the application has been tricked into creating two accounts, and the user supplied every detail of the bad_guy account.
While this particular example might not seem so harmful, it should be clear that worse things could happen once an attacker can make modifications to your SQL statements.
For example, depending on the database you are using, it might be possible to send multiple queries to the database server in a single call. Thus, a user can potentially terminate the existing query with a semicolon and follow this with a query of the user’s choosing.
MySQL, until recently, does not allow multiple queries, so this particular risk is mitigated. Newer versions of MySQL allow multiple queries, but the corresponding PHP extension (ext/mysqli) requires that you use a separate function if you want to send multiple queries (mysqli_multi_query() instead of mysqli_query()). Only allowing a single query is safer, because it limits what an attacker can potentially do.
Protecting against SQL injection is easy:
  • Filter your data.This cannot be overstressed. With good data filtering in place, most security concerns are mitigated, and some are practically eliminated.
  • Quote your data.If your database allows it (MySQL does), put single quotes around all values in your SQL statements, regardless of the data type.
  • Escape your data.Sometimes valid data can unintentionally interfere with the format of the SQL statement itself. Use mysql_escape_string() or an escaping function native to your particular database. If there isn’t a specific one, addslashes() is a good last resort.
    Q:91 What is cross site Scripting?
A:91
To understand what Cross Site Scripting is, let’s see a usual situation, common to many sites. Let’s say we are taking some information passed in on a querystring (the string after the (?) character within a URL), with the purpose of displaying the content of a variable, for example, the visitor’s name:
http://www.yourdomain.com/welcomedir/welcomepage.php?name=John
As we can see in this simple querystring, we are passing the visitor’s name as a parameter in the URL, and then displaying it on our “welcomepage.php” page with the following PHP code:
<?php
echo ‘Welcome to our site ’ . stripslashes($_GET[‘name’]);
?>
The result of this snippet is shown below:
Welcome to our site John
This is pretty simple and straightforward. We’re displaying the content of the “name” variable, by using the $_GET superglobal PHP array, as we have done probably hundreds of times. Everything seems to be fine. Now, what’s wrong with this code? Nothing really. But let’s modify the querystring by replacing our visitor’s name 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=
<script language=
javascript>alert
(‘Hey, you are going to be hijacked!’);</script>

Do you remember the PHP code included in our “welcome.php” page? Yes, you’re correct. When we modify the querystring, the following code is executed:
<?php
echo ‘Welcome to our site ‘ .
<script language=javascript> alert(‘Hey, you are going
to be hijacked!’);</script>
?>
The output of this code is an alert JavaScript box telling you “Hey, you are going be hijacked!” after the “Welcome to our site” phrase.
Very ugly stuff, right? That’s a simple example of the Cross Site Scripting vulnerability. 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(), and in_array().     Q:93 Which sorting method is lowest time consumable?
A:93
HeapSort, Merge sort are the lowest time consumable sorting algorithm.    
Web Development PHP

100 PHP interview questions and answers are below

Questions : 1
Who is the father of PHP ?


Answers : 1
Rasmus Lerdorf is known as the father of PHP.






Questions : 2
What is the difference between $name and $$name?


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







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


Answer : 3
Java script submit() function is used for submit form without submit button
on click call document.formname.submit()







Questions : 4
In how many ways we can retrieve the data in the result set of
MySQL using PHP?



Answer : 4
We can do it by 4 Ways
1. mysql_fetch_row. , 2. mysql_fetch_array , 3. mysql_fetch_object
4. mysql_fetch_assoc







Questions : 5
What is the difference between mysql_fetch_object and
mysql_fetch_array?



Answers : 5
mysql_fetch_object() is similar tomysql_fetch_array(), with one difference -
an object is returned, instead of an array. Indirectly, that means that
you can only access the data by the field names, and not by their
offsets (numbers are illegal property names).







Questions : 6
What are the differences between Get and post methods.


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






Questions : 7
How can we extract string "pcds.co.in " from a string "http://info@pcds.co.in
using regular expression of PHP?



Answers : 7
preg_match("/^http:\/\/.+@(.+)$/","http://info@pcds.co.in",$matches);
echo $matches[1];







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


Answers : 8
We can create MySQL database with the use of
mysql_create_db("Database Name")







Questions : 9
What are the differences between require and include?


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







Questions : 10
 Can we use include ("xyz.PHP") two times in a PHP page "index.PHP"?


Answers : 10
  Yes we can use include("xyz.php") more than one time in any page. but it create a prob when xyz.php file contain some funtions declaration then error will come for already declared function in this file else not a prob like if you want to show same content two time in page then must incude it two time not a prob






Questions : 11
  What are the different tables(Engine) present in MySQL, which one is default?


Answers : 11
 Following tables (Storage Engine) we can create
1.
MyISAM(The default storage engine IN MYSQL 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 the file type. An .frm file stores the table format. The data file has an .MYD (MYData) extension. The index file has an .MYI (MYIndex) extension. )
2.
InnoDB(InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data.)
3.
Merge
4.
Heap (MEMORY)(The MEMORY storage engine creates tables with contents that are stored in memory. Formerly, these were known as HEAP tables. MEMORY is the preferred term, although HEAP remains supported for backward compatibility. )
5.
BDB (BerkeleyDB)(Sleepycat Software has provided MySQL with the Berkeley DB transactional storage engine. This storage engine typically is called BDB for short. BDB tables may have a greater chance of surviving crashes and are also capable of COMMIT and ROLLBACK operations on transactions)
6.
EXAMPLE
7.
FEDERATED (It is a storage engine that accesses data in tables of remote databases rather than in local tables. )
8.
ARCHIVE (The ARCHIVE storage engine is used for storing large amounts of data without indexes in a very small footprint. )
9.
CSV (The CSV storage engine stores data in text files using comma-separated values format.)
10.
BLACKHOLE (The BLACKHOLE storage engine acts as a "black hole" that accepts data but throws it away and does not store it. Retrievals always return an empty result)






Questions : 12
 What is use of header() function in php ?


Answers : 12
The header() function sends a raw HTTP header to a client.We can use herder()
function for redirection of pages. It is important to notice that header() must
be called before any actual output is seen..







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


Answers : 13
Just run the PHP CLI (Command Line Interface) program and
provide the PHP script file name as the command line argument.







Questions : 14
Suppose your Zend engine supports the mode <? ?> Then how can u
configure your PHP Zend engine to support <?PHP ?> mode ?



Answers : 14
In php.ini file:
set
short_open_tag=on
to make PHP support







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



Answers : 15
Nothing more we have to do only redirect to the payPal url after
submit all information needed by paypal like amount,adresss etc.







Questions : 16
What is meant by nl2br()?


Answers : 16
Inserts HTML line breaks (<BR />) before all newlines in a string.






Questions : 17
What is htaccess? Why do we use this and Where?


Answers : 17
.htaccess files are configuration files of Apache Server which provide
a way to make configuration changes on a per-directory basis. A file,
containing one or more configuration directives, is placed in a particular
document directory, and the directives apply to that directory, and all
subdirectories thereof.







Questions : 18
How we get IP address of client, previous reference page etc ?


Answers : 18
By using $_SERVER['REMOTE_ADDR'],$_SERVER['HTTP_REFERER'] etc.






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



Answers : 19
All of those are open source resource. Security of Linux is very
very more than windows. Apache is a better server that IIS both in
functionality and security. MySQL is world most popular open source
database. PHP is more faster that asp or any other scripting language.







Questions : 20
How can we encrypt and decrypt a data present in a MySQL table
using MySQL?



Answers : 20
AES_ENCRYPT () and AES_DECRYPT ()






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


Answers : 21
The functions in this section perform encryption and decryption, and
compression and uncompression:
encryption
decryption
AES_ENCRYT()
AES_DECRYPT()
ENCODE()
DECODE()
DES_ENCRYPT()
DES_DECRYPT()
ENCRYPT()
Not available
MD5()
Not available
OLD_PASSWORD()
Not available
PASSWORD()
Not available
SHA() or SHA1()
Not available
Not available
UNCOMPRESSED_LENGTH()






Questions : 22
What are the features and advantages of object-oriented
programming?


Answers : 22
One of the main advantages of OO programming is its ease of
modification; objects can easily be modified and added to a system there
by reducing maintenance costs. OO programming is also considered to be
better at modeling the real world than is procedural programming. It
allows for more complicated and flexible interactions. OO systems are
also easier for non-technical personnel to understand and easier for
them to participate in the maintenance and enhancement of a system
because it appeals to natural human cognition patterns.
For some systems, an OO approach can speed development time since many
objects are standard across systems and can be reused. Components that
manage dates, shipping, shopping carts, etc. can be purchased and easily
modified for a specific system






Questions : 23
What are the differences between procedure-oriented languages and
object-oriented languages?


Answers : 23
There are lot of difference between procedure language and object oriented like below
1>Procedure language easy for new developer but complex to understand whole software as compare to object oriented model
2>In Procedure language it is difficult to use design pattern mvc , Singleton pattern etc but in OOP you we able to develop design pattern
3>IN OOP language we able to ree use code like Inheritance ,polymorphism etc but this type of thing not available in procedure language on that our Fonda use COPY and PASTE .






Questions : 24
What is the use of friend function?


Answers : 24
Sometimes a function is best shared among a number of different
classes. Such functions can be declared either as member functions of
one 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 that
is admitting them. Such functions can use all attributes of the class
which names them as a friend, as if they were themselves members of that
class.
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 member
function of another class provides the match.






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


Answer : 25
Public: Public declared items can be accessed everywhere.Protected: Protected limits access to inherited and parent
classes (and to the class that defines the item).
Private: Private limits visibility only to the class that defines
the 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 a
method 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 not
be serialized.

volatile:
a variable that might be concurrently modified by multiple
threads should be declared volatile. Variables declared to be volatile
will not be optimized by the compiler because their value can change at
any time.






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


Answer : 26
Three are three types of errors: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, as you will
see, you can change this default behavior.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 behavior is to display them to the user
when they take place.






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


Answers : 27
strstr Returns part of string from the first occurrence of needle(sub string that we finding out ) to the end of string.
$email= 'sonialouder@gmail.com';
$domain = strstr($email, '@');
echo $domain; // prints @gmail.com
here @ is the needle
stristr is case-insensitive means able not able to diffrenciate between a and A






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


Answer : 28
There are lot of difference among these three version of php
1>Php3 is oldest version after that php4 came and current version is php5 (php5.3) where php6 have to come
2>Difference mean oldest version have less functionality as compare to new one like php5 have all OOPs concept now where as php3 was pure procedural language constructive like C
In PHP5 1. Implementation of exceptions and exception handling
2. Type hinting which allows you to force the type of a specific argument
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 :
9 An __clone method if you really want to duplicate an object






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


Answer : 29
there are lots of tools available for asp to PHP conversion. you can
search Google for that. the best one is available at
http://asp2php.naken.cc./






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


Answer : 30
Convert all applicable characters to HTML entities
This function is identical to htmlspecialchars() in all ways, except
with htmlentities(), all characters which have HTML character entity
equivalents are translated into these entities.






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


Answer : 31
$second = date("s");






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


Answer : 32
By using date_default_timezone_get and
date_default_timezone_set function on PHP 5.1.0
<?php
// Discover what 8am in Tokyo relates to on the East Coast of the US    

// Set the default timezone to Tokyo time:
date_default_timezone_set('Asia/Tokyo');    

// Now generate the timestamp for that particular timezone, on Jan 1st, 2000
$stamp = mktime(8, 0, 0, 1, 1, 2000);    

// Now set the timezone back to US/Eastern
date_default_timezone_set('US/Eastern');    

// Output the date in a standard format (RFC1123), this will print:
// Fri, 31 Dec 1999 18:00:00 EST
echo '<p>', date(DATE_RFC1123, $stamp) ,'</p>';?>






Questions : 33
What is meant by urlencode and urldocode?


Answer : 33
URLencode returns a string in which all non-alphanumeric characters
except
-_. 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 form
is encoded, that is the same way as in

application/x-www-form-urlencoded
media type.
urldecode decodes any %##
encoding in the given string.






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


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






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


Answer : 35
$_SESSION['name'] = "sonia";






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


Answer : 36
To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function t






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


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






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


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






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


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






Questions : 40
How can we take a backup of a MySQL table and how can we restore
it. ?


Answer : 40
To backup: BACKUP TABLE tbl_name[,tbl_name…] TO
'/path/to/backup/directory'
RESTORE TABLE tbl_name[,tbl_name…] FROM '/path/to/backup/directory'mysqldump: Dumping Table Structure and DataUtility to dump a database or a collection of database for backup or
for transferring the data to another SQL server (not necessarily a MySQL
server). The dump will contain SQL statements to create the table and/or
populate the table.
-t, –no-create-info
Don't write table creation information (the CREATE TABLE statement).
-d, –no-data
Don't write any row information for the table. This is very useful if
you just want to get a dump of the structure for a table!






Questions : 41
How can we optimize or increase the speed of a MySQL select
query?


Answer : 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.






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


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






Questions : 43
How can we destroy the session, how can we unset the variable of
a session?


Answer : 43
session_unregister — Unregister a global variable from the current
session
session_unset — Free all session variables






Questions : 44
How can we set and destroy the cookie n php?


Answer : 44
By using setcookie(name, value, expire, path, domain); function we can set the cookie in php ;
Set the cookies in past for destroy. like
setcookie("user", "sonia", time()+3600); for set the cookie
setcookie("user", "", time()-3600); for destroy or delete the cookies;






Questions : 45
How many ways we can pass the variable through the navigation
between the pages?


Answer : 45
  • GET/QueryString
  • POST






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


Answer : 46
eregi_replace() function is identical to ereg_replace() except that
this 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.






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


Answer : 47
Sort(), arsort(),
asort(), ksort(),
natsort(), natcasesort(),
rsort(), usort(),
array_multisort(), and
uksort().






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


Answer : 48
2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)






Questions : 49
what is session_set_save_handler in PHP?


Answer : 49
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.






Questions : 50
How can I know that a variable is a number or not using a
JavaScript?


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






Questions : 51
List out some tools through which we can draw E-R diagrams for
mysql.


Answer : 51
Case Studio
Smart Draw






Questions : 52
How can I retrieve values from one database server and store them
in other database server using PHP?


Answer : 52
we can always fetch from one database and rewrite to another. here
is 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 point the 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 will
remain live.
now the following query will execute successfully.
$res3 = mysql_query("query",$db1);






Questions : 53
List out the predefined classes in PHP?


Answer : 53
Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter






Questions : 54
How can I make a script that can be bi-language (supports
English, German)?


Answer : 54
You can maintain two separate language file for each of the
language. 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.






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


Answer : 55
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.






Questions : 56
How can we send mail using JavaScript?


Answer : 56
JavaScript does not have any networking capabilities as it is
designed to work on client site. As a result we can not send mails using
JavaScript. But we can call the client side mail protocol
mailto
via JavaScript to prompt for an email to send. this requires the client
to approve it.






Questions : 57
How can we repair a MySQL table?


Answer : 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 the
MySQL will do a repair of only the index tree if the extended is given
it will create index row by row






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


Answer : 58
A stored procedure is a set of SQL commands that can be compiled and
stored in the server. Once this has been done, clients don't 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 be
parsed only once, and less information needs to be sent between the
server and the client. You can also raise the conceptual level by having
libraries of functions in the server. However, stored procedures of
course do increase the load on the database server system, as more of
the 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 of
stored procedure, one that is invoked when a particular event occurs.
For example, you can install a stored procedure that is triggered each
time a record is deleted from a transaction table and that stored
procedure automatically deletes the corresponding customer from a
customer 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 read
through the entire table to find the relevant rows. The larger the
table, 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 the
middle 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 reading
sequentially. If you need to access most of the rows, it is faster to
read sequentially, because this minimizes disk seeks.






Questions : 59
What is the maximum length of a table name, database name, and
fieldname in MySQL?


Answer : 59
The following table describes the maximum length for each type of
identifier.
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:






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


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






Questions : 61
What are the other commands to know the structure of table using
MySQL commands except explain command?


Answer : 61
describe Table-Name;






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


Answer : 62
The '.frm' file stores the table definition.
The data file has a '.MYD' (MYData) extension.
The index file has a '.MYI' (MYIndex) extension,






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


Answer : 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 the
file type.
The '.frm' file stores the table definition.
The data file has a '.MYD' (MYData) extension.
The index file has a '.MYI' (MYIndex) extension,






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


Answer : 64
If the operating system or filesystem places a limit on the number
of files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers of
files in a directory can place a practical limit on the number of tables
in a database. If the time required to open a file in the directory
increases significantly as the number of files increases, database
performance 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 usually
determined by operating system constraints on file sizes, not by MySQL
internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace
that can be created from several files. This allows a table to exceed
the 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 documentation
specific 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 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS+ 2TB






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


Answer : 65
The generic syntax for grant is as following
> GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY
[password]
now rights can be
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.We can grant rights on all databse by using *.* or some specific
database by database.* or a specific table by database.table_name
username@hotsname can be either username@localhost, username@hostname
and username@%
where hostname is any valid hostname and % represents any name, the *.*
any condition
password 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 above
a) 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






Questions : 66
Explain Normalization concept?


Answer : 66
The normalization process involves getting our data to conform to
three progressive normal forms, and a higher level of normalization
cannot be achieved until the previous levels have been achieved (there
are actually five normal forms, but the last two are mainly academic and
will not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of redundant data
from horizontal rows. We want to ensure that there is no duplication of
data 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 a
horizontal 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 already
be in First Normal Form.Third Normal Form
I have a confession to make; I do not often use Third Normal Form. In
Third Normal Form we are looking for data in our tables that is not
fully dependant on the primary key, but dependant on another value in
the table






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


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






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


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






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


Answer : 69
SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use
SELECT CURTIME();
CURRENT_TIME() = CURTIME()






Questions : 70
What are the advantages and disadvantages of Cascading Style
Sheets?


Answer : 70
External Style SheetsAdvantagesCan control styles for multiple documents at once. Classes can be
created for use on multiple HTML element types in many documents.
Selector and grouping methods can be used to apply styles under complex
contextsDisadvantagesAn extra download is required to import style information for each
document The rendering of the document may be delayed until the external
style sheet is loaded Becomes slightly unwieldy for small quantities of
style definitionsEmbedded Style Sheets
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 other
style 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 be
used to create complex element addressing scenarios






Questions : 71
What type of inheritance that PHP supports?


Answer : 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'.






Questions : 72
What is the difference between Primary Key and
Unique key?


Answer : 72
Primary Key: A column in a table whose values uniquely identify the
rows in the table. A primary key value cannot be NULL.
Unique Key: Unique Keys are used to uniquely identify each row in the
table. 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 more
than one unique for a table.







Question : 73
what is garbage collection? default time ? refresh time?


Answer : 73
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. Garbage 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






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


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






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


Answer : 75
ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns
it 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, if
you want to count all items in group, sum all values or view average






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


Answer : 76
Set char to occupy n bytes and it will take n bytes even if u r
storing a value of n-m bytes
Set varchar to occupy n bytes and it will take only the required space
and will not use the n bytes
eg. name char(15) will waste 10 bytes if we store 'romharshan', if each char
takes a byte
eg. name varchar(15) will just use 5 bytes if we store 'romharshan', if each
char takes a byte. rest 10 bytes will be free.






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


Answer : 77
Calculate the md5 hash of a string. The hash is a 32-character
hexadecimal 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 now
will be totally different for the same string I am using.






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


Answer : 78
you can use LOAD DATA INFILE file_name; syntax to load data
from a text file. but you have to make sure thata) data is delimited
b) columns and data matched correctly






Questions : 79
How can we know the number of days between two given dates using
MySQL?


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






Questions : 80
How can we know the number of days between two given dates using PHP?


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






Questions : 81
How we load all classes that placed in different directory in one PHP File , means how to do auto load classes


Answer : 81

by using spl_autoload_register('autoloader::funtion');
Like below
class autoloader
{
public static function moduleautoloader($class)
{
$path = $_SERVER['DOCUMENT_ROOT'] . "/modules/{$class}.php";
if (is_readable($path)) require $path;
}
public static function daoautoloader($class)
{
$path = $_SERVER['DOCUMENT_ROOT'] . "/dataobjects/{$class}.php";
if (is_readable($path)) require $path;
}
public static function includesautoloader($class)
{
$path = $_SERVER['DOCUMENT_ROOT'] . "/includes/{$class}.php";
if (is_readable($path)) require $path;
}
}
spl_autoload_register('autoloader::includesautoloader');
spl_autoload_register('autoloader::daoautoloader');
spl_autoload_register('autoloader::moduleautoloader');






Questions : 82
How many types of Inheritances used in PHP and how we achieve it


Answer : 82
As far PHP concern it only support single Inheritance in scripting.
we can also use interface to achieve multiple inheritance.






Questions : 83
PHP how to know user has read the email?


Answers : 83
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;
}






Questions : 84
What are default session time and path?


Answers : 84
default session time in PHP is 1440 seconds or 24 minutes
Default session save path id temporary folder /tmp






Questions : 85
how to track user logged out or not? when user is idle ?


Answers : 85
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.






Questions : 86
how to track no of user logged in ?


Answers : 86
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.






Questions : 87
in PHP for pdf which library used?


Answers : 87
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.






Questions : 88
for image work which library?


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






Questions : 89
what is design pattern? singleton pattern?


Answers : 89
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.






Questions : 90
what are magic methods?


Answers : 90
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()






Questions : 91
what is magic quotes?


Answers : 91
Magic Quotes is a process that automagically escapes ncoming 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.






Questions : 92
what is cross site scripting? SQL injection?


Answers : 92
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






Questions : 93
what is URL rewriting?


Answers : 93
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.






Questions : 94
what is the major php security hole? how to avoid?


Answers : 94
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.






Questions : 95
whether PHP supports Microsoft SQL server ?


Answers : 95
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.






Questions : 96
what is MVC? why its been used?


Answers : 96
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






Questions : 97
what is framework? how it works? what is advantage?


Answers : 97
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






Questions : 98
what is CURL?


Answers : 98
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.






Questions : 99
what is PDO ?


Answers : 99
The PDO ( PHP Data Objects ) extension defines a lightweight, consistent interface for accessing databases in PHP. if you are using the PDO API, you could switch the database server you used, from say PgSQL to MySQL, and only need to make minor changes to your PHP code.
While PDO has its advantages, such as a clean, simple, portable API but its main disadvantage is that it doesn't allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL's support for Multiple Statements.
Just need to use below code for connect mysql using PDO
try {
$dbh = new PDO("mysql:host=$hostname;dbname=databasename", $username, $password);
$sql = "SELECT * FROM employee";
foreach ($dbh->query($sql) as $row)
{
print $row['employee_name'] .' - '. $row['employee_age'] ;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}






Questions : 100
What is PHP's mysqli Extension?


Answers : 100
The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later.
The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:
=>Object-oriented interface
=>Support for Prepared Statements
=>Support for Multiple Statements
=>Support for Transactions
=>Enhanced debugging capabilities
=>Embedded server support



Difference between echo and print?
void echo ( string $arg1 [, string $...] )
Outputs all parameters.
echo() is not actually
a function (it is a language construct), so you are not required to use parentheses with it. echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo(), the parameters must not be enclosed within parentheses.

echo() also has a shortcut syntax, where you can immediately follow
the opening tag with an equals sign. This short syntax only works with the short_open_tag configuration setting enabled.
I have foo.

print --- out put a string
print behaves like a function and you can return values and echo can't
Prin can be used as a part of more
complex operations
What is the use of ob_start in php?

ob_start — Turn on output buffering
According to PHP manual*
Description
bool ob_start ( [callback $output_callback [, int $chunk_size [, bool $erase]]] )
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.
Warning
Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.
Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.

How to reverse an array values using recursive method in php ?

$array=array(1,2,3,4,5,6);
rec($array,5);
echo $f1= substr($f,0,-1);
function rec($arr,$index)
{
global $f;
if($index==-1)
return;
$f.=$arr[$index].',';
$index--;
rec($arr,$index);

}

?>

//Output: 6,5,4,3,2,1

How to reverse a string in php with out using any built in functions?


function w3RevStr($str) {
$revStr = "";
$w=0;
while($c=$str[$w]){
$revStr = $c.$revStr;
$w=$w+1;
}
return $revStr;
}
echo w3RevStr("www.w3answers.com");
?>

How many HTTP headers will send to a web page(client side) from server when you use sessions (session_start()) in php ?.

There are three HTTP headers included in the response:
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

what are the advantages of storing sessions in database?
If you store a session in a database you have several advantages:
@ Improving the security because on many
hosting packages (shared host)
PHP uses the same path for storing sessions for all the users,
somewhere that is not in your folders.
@ You can track who is online etc.
@ For application that are running on multiple servers, you can store
all the session data in one database.
The real beauty of this
approach is that you don't have to modify your code or the way you use sessions in any way. $_SESSION still exists and behaves the same way, PHP still takes care of generating and propagating the session identifier, and changes made to session configuration directives still apply. All you have to do is call this one function.

You must call session_set_save_handler() prior to calling session_start(), but you can define the functions themselves anywhere.

The function is called session_set_save_handler(), and it takes six arguments,

1. Opening the session data store
2. Closing the session data store
3. Reading session data
4. Writing session data
5. Destroying all session data
6. Cleaning out old session data

How to get the contents of a web page using php?

you can achieve this using curl in php

see the example below.
function curl_get_con_url($url, $user_agent = '', $referer = '') {
// create a new CURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);

/* This lines will make sure that you can save the web page into a variable */
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_REFERER, $referer);

// grab URL
$page_content = curl_exec($ch);

if (curl_errno($ch)) {
$page_content = false;
}
// close CURL resource, and free up system resources
curl_close($ch);
return $page_content;
}
$referads_pc = curl_get_con_url('www.referads.com');

what are the security tips you should know before developing php/mysql web pages ?


1. Do not trust user input.
2. Validate user input on the server side.
3. Do not use user input directly in your MySQL queries.
4. Don't put integers in quotes In your MySQL queries.
5. Always escape the output using php built in functions.
6. When uploading files, validate the file mime type using php.
7. If you are using 3rd party code libraries, be sure to keep them up to date.
8. Give your database users just enough permissions.
9. Do not allow hosts other than localhost to connect to your database.
10. Your library file extensions should be PHP.
11. Have register globals off or define your
variables first
12. Keep PHP itself up to date (use latest version php5 or above)

what are the database space-saving functions available in php ?

Use ip2long() and long2ip() to store the IP adresses as Integers instead of storing them as strings, which will reduce the space from 15 bytes to 4 bytes. This will also increase search speed and make it easy to see if a ip falls within a specified range.
# Use gzcompress() and gzuncompress() to reduce the strings before you store them in a database. The gzcompress can compress plain-text up to 90%. The only reason why you shouldn’t use it is when you need full-text indexing capabilities.

what you should know about cookies before start using in php?

There are a few things you should be aware of:
1. Since cookies are used to record information about your activities on a particular domain, they can only be read by
the domain that created them
2. A single domain cannot set more than twenty cookies, and each cookie is limited to a maximum size of 4 KB
3. A cookie usually possesses six attributes, of which only the first is mandatory. Here they are:
* name: the name of
the cookie
* value: the value of the cookie
* expires: the date and time at which the cookie expires
* path: the top-level directory on the domain from which cookie data can be accessed
* domain: the domain for which the cookie is valid
* secure: a Boolean flag indicating whether the cookie should be transmitted only over a secure HTTP connection

It's important to remember that, since cookies are stored on the user's hard drive, you as the developer have very little control over them. If a user decides to turn off cookie support in his or her browser, your cookies will simply not be saved. Therefore, avoid writing code that depends heavily on cookies; and have a backup plan ready in case cookie data cannot be retrieved from the client.

Two types of cookies

1) temporary and
2) persistent cookies

Given a line of text $string, how would you write a regular expression to strip all the HTML tags from it?


$stringOfText = "This is a test";

$expression = "/<(.*?)>(.*?)<\/(.*?)>/";

echo preg_replace($expression, "\\2", $stringOfText);

what are the ways to check image mime types in php?

There are a few inbuilt options you can use however, for example getimagesize() can
return the mimetype, as does some of the new fileinfo functions. The mime type in getimagesize is stored in 'mime', and can be accessed as shown below.
$parts = getimagesize($filename);
echo $parts['mime'];

?>
or
$parts = getimagesize($filename);
$allowedMimes = array('image/jpg', 'image/png', 'image/gif');

if(in_array($parts['mime'], $allowedMimes))
echo 'Valid Mimetype!';
?>

other way

$filename = 'maliciousScript.jpg.php'; // filename to check
$parts = explode('.', $filename); // common (but wrong) method used
echo $parts[1];
echo strrchr($filename, '.'); // correct method
?>
echo system('file -ib '. $filename);
?>

how to opening excel files in windows nad linux using php ?

if you're using PHP on Windows, you can use the inbuilt COM library
$excel = new COM("excel.application");
$excel->Workbooks->Open("filename.xls");
On Linux machines, is PHPExcelReader( download from sourceforgr.net), and it seems to work very efficiently and easily with only a few lines of code.

$data = new Spreadsheet_Excel_Reader();
$data->read("filename.xls");

And you can access the data with a simple loop:

for($i=1; $i <= $data->sheets[0]['numRows']; $i++)
{
echo 'Row '. $i .', Column a:' $data->sheets[0]['cells'][$i][1] . '';
echo 'Row '. $i .', Column b:' $data->sheets[0]['cells'][$i][2] . '';
}

How many ways your web server can utilize PHP to generate web pages?

Mainly there are three ways
***************************
The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist.

The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When a request comes in from a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be served by a different child process than the first time. When opening a persistent connection, every following page requesting SQL services can reuse the same established connection to the SQL server.

The last method is to use PHP as a plug-in for a multithreaded web server. Currently PHP 4 has support for ISAPI, WSAPI, and NSAPI (on Windows), which all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack (iPlanet), Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. The behavior is essentially the same as for the multiprocess model described before. Note that SAPI support is not available in PHP 3.

What is meant by Persistent Database Connections?

Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).
Note
*****
People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same link, they do not give you an ability to build up a transaction efficiently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.

Its extremely simple and efficient. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.

List out some session functions in php?

session_save_path -- Get and/or set the current session save path
session_is_registered -- Find out whether a global variable is registered in a session
session_unset -- Free all session variables
session_cache_expire -- Return current cache expire
session_cache_limiter -- Get and/or set the current cache limiter
session_commit -- Alias of session_write_close()
session_decode -- Decodes session data from a string
session_destroy -- Destroys all data registered to a session
session_write_close -- Write session data and end session
session_encode -- Encodes the current session data as a string
session_get_cookie_params -- Get the session cookie parameters
session_id -- Get and/or set the current session id
session_module_name -- Get and/or set the current session module
session_name -- Get and/or set the current session name
session_regenerate_id -- Update the current session id with a newly generated one
session_register -- Register one or more global variables with the current session
session_set_cookie_params -- Set the session cookie parameters
session_set_save_handler -- Sets user-level session storage functions(Like storing to Databases like MySQl,Oracle etc)
session_start -- Initialize session data
session_unregister -- Unregister a global variable from the current session

What is the process that takes place when you upload a file in php?

There are two basic things covered here.
The form that will be used to post the file data to and the actual program that does the uploading. Further we will discuss the method that PHP itself suggests for uploading files.

Process 1 HTML PART
*******************
Top of Form


Upload a file:

Bottom of Form


Note the enctype is set to "multipart/form-data".
This is crucial to the working of the application. If it is not specified here then the program will not work.

Next you'll notice that MAX_FILE_SIZE precedes the file input field. The MAX_FILE_SIZE for this demonstration is limited to 30000 bytes, or about 29K, but can easily be modified for larger files.

Finally you have the input sections. The first is set to create an input box that allows the user to choose his file and the second is the button that actually submits the file for upload. In the next section you'll notice that the name of the input element for type="file" will be used to determine the name to pull from the $_FILES array.

Form Method must be POST

Process 2 PHP PART
******************
$imgdir = '/imgdir/';
$uploadfile = $imgdir. basename($_FILES['smefile']['name']);
if (move_uploaded_file($_FILES[ 'smefile']['tmp_name'], $uploadfile)) {
echo "File successfully uploaded";
} else {
echo "Upload failed";
}
?>

Will persistent connection work in the CGI version of php ? mysql_connect() vs mysql_pconnect()
Persistent database connections work only in the module installation of PHP.
If you ask for a persistent connection in the CGI version,
you will simply get a regular connection.

if you become convinced that the sheer overhead of opening new database connections is killing your performance, you might want to investigate opening persistent connections.Unlike regular database connections, these connections are not automatically killed when your page exits (or even when mysql_close() is called) but are saved in a pool for future use. The first time one of your
scripts opens such a connection, it is opened in the same resource-intensive way as with a regular database connection. The next script that executes,however, might get that very same connection in response to its request, which saves the cost of reopening a fresh connection. (The previous connection will be reused only if the
parameters of the new request are identical.)

Other than offering a particular kind of increased efficiency, persistent
database connections do not provide any functionality beyond that of regular database connections.

What are the 'function problems' you have met in php?

1)Call to undefined function we_w3answers()
*****************************************
PHP is trying to call the function we_w3answers(), which has not been
because you misspelled the name of a function (built-in or user-defined)
simply omitted the function definition. If you use include/require
functions, make sure that you are loading the appropriate files.

2)Call to undefined function array()
***********************************
This problem has a cause that is similar to the cause of the previous problem, although it still baffled us completely the first time we ran into it. It can arise when you have code like the following:

$my_w3answers= array();
$my_w3answers(5) = “the fifth”;

3)Cannot redeclare my_function()
*******************************
This is a simple one—somewhere in your code you have two definitions of my_function(), which PHP will not stand for.

Make sure that you are not using include to pull in the same file of function definitions more than once. Use include_once or require_once to avoid

4)Wrong parameter count
***********************

Explain Parse Errors ? what are the most common causes of parse errors ?

The most common category of error arises from mistyped or syntactically incorrect PHP code, which confuses the PHP parsing engine.
1)The missing semicolon
***********************
If each PHP instruction is not duly finished off with a semicolon,
a parse error will result. In this sample fragment, the first line lacks a semicolon and, therefore, the variable assignment is never completed.
What we have here is
$Problem = “a silly misunderstanding”
echo $Problem;
?>

2)No dollar signs
*******************
Another very common problem is that a dollar sign prepending a variable name is missing.If the dollar sign is missing during the initial variable assignment, like so:
What we have here is
Problem = “a big ball of earwax”;
echo $Problem;
?>.
A parse error message will result. However, if instead the dollar sign is missing from a later
output of the variable, like this:
What we have here is
$Problem = “a big ball of earwax”;
print(“Problem”);
?>

3)Mode issues
**************
A parse error will result if you fail to close off a PHP block properly, as in:
What we have here is
$Problem = “an awful kerfuffle”;
echo $Problem;
4)Unescaped quotes
********************
5)Unterminated strings
**********************
What Are PHP Arrays?
PHP arrays are associative arrays with a little extra machinery thrown in.
The associative part means that arrays store element values in association with key values rather than in a strict linear index order. (If you have seen arrays in other programming languages, they are likely to have been vector arrays rather than associative arrays.) If you store an element in an array, in association with a key,all you need to retrieve it later from that array is the key value. For example, storage is as simple as this:
$state_location[‘San Mateo’] = ‘California’;

which stores the element ‘California’ in the array variable $state_location, in association with the lookup key ‘San Mateo’. After this has been stored,you can look up the stored value by using the key, like so:

$state = $state_location[‘San Mateo’]; // equals ‘California’

If all you want arrays for is to store key/value pairs, the preceding information is all you need to know. Similarly, if you want to associate a numerical ordering with a bunch of values,all you have to do is use integers as your key values, as in:

$my_array[1] = “The first thing”;
$my_array[2] = “The second thing”;

Are php strings immutable ?

PHP strings can be changed, but the most common practice seems to be to treat strings as immutable. Strings can be changed by treating them as character arrays and assigning directly into them, like this:
$my_string = “abcdefg”;
$my_string[5] = “X”;
print($my_string . “
”);
which will give the browser output:
abcdeXg
?>
what is Memcache?
Memcache is a technology which caches objects in memory where your web application can get to them really fast. It is used by sites such as Digg.com, Facebook.com and NowPublic.com and is widely recognized as an essential ingredient in scaling any LAMP application to handle enormous traffic.

How do I prevent Web browsers caching a page in php?

header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Pragma: no-cache');
?>

what is the php solution to dynamic caching ?

PHP offers an extremely simple solution to dynamic caching in the form of output buffering.

what are the most common caching policy approaches ?

1)Time triggered caching (expiry timestamp).
2)Content change triggered caching (sensitive content has changed, so cache must be updated).
3)Manually triggered caching (manually inform the application that information is outdated, and force a new cache creation).

How to capture content from the output buffer ? or Give me an example for Output caching in php?

ob_start(); // start an output buffer

echo ‘This text is from the w3answers buffer*******
’; // output that will be stored in the buffer

$w3buffer = ob_get_contents(); // store buffer content in $w3buffer variable
ob_end_clean(); // stop and clean the output buffer
echo ‘This is not from the w3answers buffer!!!!!!!! ’;
echo $w3buffer;
?>
O/p
*****
This is not from the w3answers buffer!!!!!!!!
This text is from the w3answers buffer*******

What is the difference between $message and $$message?

$message is a simple variable whereas $$message is a variable's variable,which means
value of the variable. Example:
$user = 'bob'
is equivalent to

$message = 'user';
$$message = 'bob';

why should we use Object oriented concepts in php ?

1. Object oriented PHP code is much more reusable because by its' very nature, it is modular.
2. Object oriented PHP is easier to update. Again, because PHP code is organised into objects.
3. Object oriented PHP makes team programming much easier to manage.
4. Object oriented PHP makes larger projects much easier to manage.
5. Object oriented PHP makes creating code libraries much easier.
6. Knowing Object oriented PHP will make working with many opensource PHP libraries much easier. For example: projects like PEAR and the Zend Framework are built using Object oriented PHP.
7. Object oriented PHP programmers typically make more money and will be able to work on more projects.
8. Since object oriented concepts are the same in all Object oriented languages, once you learn Object oriented programing in PHP, you will also have a good understanding of several other languages including:
a. Ruby
b. Java
c. C#
d. Actionscript
…among several other languages.

which is faster mysql_unbuffered_query or mysql_query ?

when we do the select queries that retrieve large data sets from MySQL, mysql_unbuffered_query in PHP is likely to give better performance than mysql_query.
PHP manual says,
it “sends a SQL query query to MySQL, without fetching and buffering the result rows automatically”.

How can we extract string "w3answers.com" from a string

mailto:info@w3answers.com using regular expression of PHP ?

$w3 = "mailto:info@w3answers.com";
preg_match('|.*@([^?]*)|', $w3, $w3output);
echo $w3output[1];
?>

Which function in PHP gives us absolute path of a file on the server?

getcwd()
$p = getcwd();
echo $p;
?>
here I have stored my files under httdocs (using php5,i haven't checked under php4) so I get the output as C:\apache2triad\htdocs you may get your path information while runnings the above code. :)

what is the output here ?

session_start();
$_SESSION["var"] = NULL;
echo $var = "www.w3answers.com";
?>

The output :
www.w3answers.com and warning as below

Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively. in Unknown on line 0

what is the output ?

echo "www.w3answers.com";
if ((string)'-1') { print 'ouch'; } else { print 'echo'; }
?>

a. ouch
b. echo
c. none
d. Parse error

ANS: a

what output do you get here?

$here = "/home/httpd/html/test ";
list ($j1,$j2,$j3,$j4) = split('/',$here);
print "$j3";
?>

a. home
b. Array
c. test
d. httpd
ANS: httpd

Which of the following functions is most efficient for substituting fixed patterns in strings?

A. preg_replace()
B. str_replace()
C. str_ireplace()
D. substr_replace()

Answer B is correct.

The PHP efficiency mantra is “do no more work than necessary.”
Both str_ireplace() and preg_replace() have more expensive (and flexible)matching logic, so you should only use them when your problem requires it.substr_replace() requires you to know the offsets and lengths of the substringsyou want to replace, and is not sufficient to handle the task at hand.

Which of the following represents the proper way to set a session variable?

A. $_SESSION[‘foo’] = ‘bar’;
B. session_start();
C. session_set_save_handler (‘myopen’, ‘myclose’, ‘myread’,
‘mywrite’, ‘mydelete’, ‘mygarbage’);
D. $foo = $_SESSION[‘foo’];

Answer A is correct.

Answer B is incorrect because session_start() only activates PHP sessions for the current script. Answer C is incorrect because session_set_save_handler() allows you to override PHP’s default session
mechanism with your own custom functions. Answer D is incorrect; session data is being used as the value of a regular variable and is not being manipulated in any way.

How we can pass data from PHP to ASP,ASP.net?

PHP to ASP
Let's first look at how you can pass data from PHP to ASP using WDDX.
You create a WDDX packet by first serializing data into a WDDX packet and then presenting it.
WDDX can convert most variable types that applications use, such as strings, integers, and arrays. After a variable has been converted to a WDDX variable type, it is ready for another application to pick up.

PHP has WDDX support built in, so you don't need to modify your PHP.ini file to start using WDDX.
A PHP Script to Serialize WDDX

//define PHP data to send
$ValueToSend = "Andrew";

//convert PHP data to WDDX data
$wddxvar = wddx_serialize_value("$ValueToSend");

//output WDDX data
print("$wddxvar");

?>
You first set the data you want to serialize into a WDDX packet:
$ValueToSend = "Andrew";
You then serialize that data:

$wddxvar = wddx_serialize_value("$ValueToSend");

Finally, you present that data as
print("$wddxvar");

********************************
O/P=Andrew
********************************
Internet Explorer just shows the data within the WDDX packet. It doesn't show the surrounding XML structures. However, if you choose the view source option, you can see the WDDX packet's XML structures
#################################-END-
**************************************************
ASP Script to Deserialize WDDX Data
**************************************************
To receive the WDDX packet from the PHP script, you must load the packet into a variable within the receiving ASP script. None of the WDDX implementations (the WDDX COM component or PHP's WDDX functions) provides native ways of doing this. You must add this functionality using separate code. After you receive the WDDX packet, you can convert it into a data type native to the receiving application. This is called deserializing.

Using ASP, you can use a third-party COM component. A free COM component that allows such functionality is ASP Tear from http://www.alphasier-rapapa.com/IisDev/Components/ (also included with the WDDX SDK). However, you can use any COM component that has similar functionality.
<%
set aspget = Server.CreateObject("SOFTWING.AspTear")
set wddxob = Server.CreateObject("WDDX.Deserializer.1")

'get WDDX data
wddxdata = aspget.Retrieve("http://localhost/phpbook/Chapter5_Sessions/WDDX/PHP/
two_wddxserver.php", Request_POST, "", "", "")

'convert WDDX data to ASP data
wddxvar = wddxob.deserialize(wddxdata)

'output ASP data
response.write "Hello " & wddxvar

set wddxob = nothing
set aspget = nothing

%>

First, you must load the WDDX and ASP Tear COM objects into memory for use by ASP. Don't worry too much if you are not familiar with using COM objects
set aspget = Server.CreateObject("SOFTWING.AspTear")
set wddxob = Server.CreateObject("WDDX.Deserializer.1")
Next you use ASP Tear to obtain the WDDX packet produced by the PHP server and load it into a variable:

'get WDDX data
wddxdata = aspget.Retrieve("http://localhost/phpbook/Chapter5_Sessions/WDDX/PHP/
two_wddxserver.php", Request_POST, "", "", "")
You deserialize the WDDX packet into a native data type for ASP:

'convert WDDX data to ASP data
wddxvar = wddxob.deserialize(wddxdata)
You then output the value:

'output ASP data
response.write "Hello " & wddxvar
Finally, you unload the COM objects from memory:

set wddxob = nothing
set aspget = nothing
ASP to PHP
PHP can also receive WDDX packets. Here you will see a PHP script obtaining a WDDX packet from an ASP script.

*************************************************
An ASP Script to Serialize WDDX
*************************************************
<%
'define ASP data to send
ValueToSend = "Andrew"
set wddxob = Server.CreateObject("WDDX.Serializer.1")

'convert ASP data to WDDX data
wddxvar = wddxob.serialize(ValueToSend)

'output WDDX data
response.write wddxvar

set wddxob = nothing

%>
This is very much the same as the serializing PHP script. First, you define the value you want to serialize in WDDX:

'define ASP data to send
ValueToSend = "Andrew"
You then load the WDDX COM object into memory, ready for use by ASP:

set wddxob = Server.CreateObject("WDDX.Serializer.1")
You then serialize the value into a WDDX packet:

'convert ASP data to WDDX data
wddxvar = wddxob.serialize(ValueToSend)
You then display the WDDX packet:

'output WDDX data
response.write wddxvar
Finally, you unload the WDDX COM object from memory:

set wddxob = nothing
*******************************************************
A PHP Script to Deserialize WDDX Data
********************************************************
The deserialize PHP script needs to do the same as the deserialize ASP script: It must convert the WDDX packet back into a native variable type for our script (in this case, a native variable type for PHP):
//get WDDX data
$wddxdata = join ('', file
('http://localhost/phpbook/Chapter5_Sessions/WDDX/ASP/one_wddxserver.asp'));

//convert WDDX data to PHP data
$wddxvar = wddx_deserialize("$wddxdata");
//output PHP data
print("Hello " . $wddxvar);
?>
You can obtain the WDDX packet from the ASP script using the PHP join function. To use the function in this manner, you must make sure that HTTP transparency is enabled in the PHP.ini settings file (the allow_url_fopen setting is enabled). (Note that HTTP transparency is enabled by default.)

$wddxdata = join ('', file
('http://localhost/phpbook/Chapter5_Sessions/WDDX/ASP/one_wddxserver.asp'));
As before, you deserialize the WDDX packet into a native variable type:

$wddxvar = wddx_deserialize("$wddxdata");
You then display the WDDX packet:

print("Hello " . $wddxvar);

How can you block certain IP Addresses from accessing your site?

$banned = array("24.91.102.173", "64.21.162.113");
if (in_array($_SERVER['REMOTE_ADDR'], $banned)) {
echo "You have been banned.";
exit;
}
?>

What Storage Engines do you use in MySQL?

MySQL Engines
*****************************************

MyISAM
HEAP
MEMORY
MERGE
MRG_MYISAM
ISAM
MRG_ISAM
InnoDB
INNOBASE
BDB
BERKELEYDB
NDBCLUSTER
NDB
EXAMPLE
ARCHIVE
CSV

What is Apache?

The most widely available HTTP server on the Internet. It supports the PERL and PHP languages.

The Apache HTTP Server Project is a collaborative software development effort aimed at creating a robust, commercial-grade, featureful, and freely-available source code implementation of an HTTP (Web) server. The project is jointly managed by a group of volunteers located around the world, using the Internet and the Web to communicate, plan, and develop the server and its related documentation. This project is part of the Apache Software Foundation. In addition, hundreds of users have contributed ideas, code, and documentation to the project. This file is intended to briefly describe the history of the Apache HTTP Server and recognize the many contributors.

Installing PHP on your Computer?
You can download apache2triad from
http://sourceforge.net/projects/apache2triad/

Its a single setup file for
---------------------------
Apache2 , MySQL , PostgreSQL , OpenSSL , Xmail , SlimFTPd Software developing triad of : PHP , Perl and Python + Apache2TriadCP , PHPmyadmin , PHPPgAdmin , AWStats , UebiMiau , PHPXMail , PHPSFTPd. All latest stables , all manuals

Use this for your php installation in your pc!!!

What can PHP do?
Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

There are three main areas where PHP scripts are used.

Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a webserver and a web browser. You need to run the webserver, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming.

Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks.

Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution.

PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers PHP has a module, for the others supporting the CGI standard, PHP can work as a CGI processor.

So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming, or a mixture of them. Although not every standard OOP feature is implemented in PHP 4, many code libraries and large applications (including the PEAR library) are written only using OOP code. PHP 5 fixes the OOP related weaknesses of PHP 4, and introduces a complete object model.

With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.

One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple. The following databases are currently supported:

Adabas D InterBase PostgreSQL
dBase FrontBase SQLite
Empress mSQL Solid
FilePro (read-only) Direct MS-SQL Sybase
Hyperwave MySQL Velocis
IBM DB2 ODBC Unix dbm
Informix Oracle (OCI7 and OCI8)
Ingres Ovrimos

We also have a database abstraction extension (named PDO) allowing you to transparently use any database supported by that extension. Additionally PHP supports ODBC, the Open Database Connection standard, so you can connect to any other database supporting this world standard.

PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. Talking about interconnection, PHP has support for instantiation of Java objects and using them transparently as PHP objects. You can also use our CORBA extension to access remote objects.

PHP has extremely useful text processing features, from the POSIX Extended or Perl regular expressions to parsing XML documents. For parsing and accessing XML documents, PHP 4 supports the SAX and DOM standards, and you can also use the XSLT extension to transform XML documents. PHP 5 standardizes all the XML extensions on the solid base of libxml2 and extends the feature set adding SimpleXML and XMLReader support.

At last but not least, we have many other interesting extensions, the mnoGoSearch search engine functions, the IRC Gateway functions, many compression utilities (gzip, bz2, zip), calendar conversion, translation...

What is PHP?


PHP: Hypertext Preprocessor, an open source, server-side, HTML embedded scripting language used to create dynamic Web pages.

In an HTML document, PHP script (similar syntax to that of Perl or C ) is enclosed within special PHP tags. Because PHP is embedded within tags, the author can jump between HTML and PHP (similar to ASP and Cold Fusion) instead of having to rely on heavy amounts of code to output HTML. And, because PHP is executed on the server, the client cannot view the PHP code.

PHP can perform any task that any CGI program can do, but its strength lies in its compatibility with many types of databases. Also, PHP can talk across networks using IMAP, SNMP, NNTP, POP3, or HTTP.

PHP was created sometime in 1994 by Rasmus Lerdorf. During mid 1997, PHP development entered the hands of other contributors. Two of them, Zeev Suraski and Andi Gutmans, rewrote the parser from scratch to create PHP version 3 (PHP3).

PHP OOPS Interview Questions


what is Magic methods in php?

There are seven special methods, and they are as follows:

__construct( )
Called when instantiating an object

__destruct( )
Called when deleting an object

__get( )
Called when reading from a nonexistent property

__set( )
Called when writing to a nonexistent property

__call( )
Called when invoking a nonexistent method

__toString( )
Called when printing an object (for eg: converting an object to strings)

__clone( )
Called when cloning an object (copying object)

Explain Constructors and Destructors in php?
__construct( )
Called when instantiating an object

__destruct( )
Called when deleting an object

Constructors and destructors are functions that are called when a new instance of an object is created (constructors) and/or destroyed (destructors). Their primary purpose is to allow for a means to initialize and clean up after an object during its use.
Constructors can accept parameters, which are assigned to specific object fields at
creation time.

Constructors can call class methods or other functions.
constructors are intuitively useful for initializing class properties,

Class constructors can call on other constructors, including those from the class parent.

One classic example is a class to access a database back end, where a constructor could make the connection to the database while the destructor closes it.

PHP 4 Constructors
In PHP 4, only constructors were available and were created by defining a function whose name was the same as the class itself:
class w3Class {
function w3Class($param) {
echo "Created a new instance of w3Class!";
}
}
$w3instance = new w3Class;
?>

In PHP 5, this concept has been changed PHP 5 or (5>=) now uses a unified constructor function named __construct(). PHP 5 or (5>=) also uses a unified __destruct() method for its destructors.

PHP 5 Constructors and Destructors

class w3Class {
function __construct($p) {
echo "Created a new instance of w3Class!";
}
function __destruct() {
echo "Destroyed this instance of w3Class";
}
}
$w3instance = new w3Class("value");

?>

Define class in php?

A class is a blueprint of an object ,variables and functions (called methods),

PHP 4 Class Style:

Create first file as ‘PHP4Class.php’
class w3answersPHP4Class {
var $my_class;
function my_W3method($param) {
echo "hey, you are in my_W3method ($param)!!\n";
echo "The value of my w3class is: ";
echo "{$this->my_class }\n";
}
}
?>

“$this is a special variable within a class that represents the instance of the object itself. It is used to access both methods and properties internally within the object”.
To create an instance of the w3answersPHP4Class, the new statement is used:

Create Second file as ‘instance.php’
require_once ("PHP4Class.php ");
$w3instance = new w3answersPHP4Class();
$w3anotherinstance = new w3answersPHP4Class();
$w3instance->my_class = 100;
$w3anotherinstance->my_class = 200;
?>

When executed, the $my_class property of the $w3instance object will be set to 100, and the $w3anotherinstance’s $my_class property will be set to 200.

The output will be

Hey, you are in my_W3method(MyParam)!!
The value of my w3class is 100

PHP 5 Class style:
Create first file as ‘PHP5Class.php’
class w3answersPHP5Class {
public $my_class;
/*we can also make private $my_class; but it will lead you to error when you tryimg to acess the varaiable
like Fatal Error: Cannot access private property w3answersPHP5Class::my_class in .... */

public function my_W3method($param) {
echo "hey, you are in my_W3method ($param)!!\n";
echo "The value of my w3class is: ";
echo "{$this->my_class }\n";
}
}
?>

Create Second file as ‘instance.php’
include_once ("PHP5Class.php ");
$w3instance = new w3answersPHP5Class();
$w3anotherinstance = new w3answersPHP5Class();
$w3instance->my_class = 100;
$w3anotherinstance->my_class = 200;

?>

How php Implements Polymorphism ?

PHP supports polymorphism in the sense of allowing instance of subclasses to be used in place of parent instances.

How PHP Supports Encapsulation?

Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from out side interference and miss use .To implement this concept , PHP 5 supports public, private, and protected variables and member functions .



PHP XML Questions


What are the Technology to Use for Parsing the XML?

There are two types of XML parsers the we can use.
1. DOM (Document Object Module).
2. SAX (Simple API for XML).
DOM
The DOM (Document Object Model) extension allows to operate on XML documents through the DOM API with PHP 5. DOM is a standard defined by the W3C for accessing XML documents.
In PHP 4, DOM xml extension is not following the standard method names.
As per the new W3C compatibility, the old domxml-based scripts won't work anymore. The API is quite different in PHP 5. But if we used the "almost W3C compatible" method names available in PHP 4.3, We only need to change the loading and saving methods, and remove the underscore in the method names. Other adjustments here and there may be necessary, but the main logic can stay the same. Though we have not used earlier so these will not be a problem for us.
The easiest way to read a well-formed XML file is to use the DOM library . The DOM library reads the entire XML document into an object and represents it as a tree of nodes,

SAX
SAX stands for Simple API for XML. It's a callback-based interface for parsing XML documents. SAX support has been available since PHP 3 and hasn't changed a lot since then. For PHP 5 the API is unchanged, The only difference is that it's not based on the expat library anymore, but on the libxml2 library.
Rather than treating an XML document as a tree-like structure, SAX treats it as a series of events such as startDocument or endElement. To accomplish this, a SAX appllication consists of a parser that sends these events to "handlers," methods or functions designated to handle them.

What is XML?

XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C).
XML doesn't define what data is being stored or the structure of that data.
XML simply defines tags and attributes for those tags. A properly formed XML tag looks like this:
php xml

An XML book list example
Rasmus
zend
w3answers
w3labs


XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C).
XML doesn't define what data is being stored or the structure of that data.
XML simply defines tags and attributes for those tags. A properly formed XML tag looks like this:
php xml
An XML book list example
Rasmus
zend
w3answers
w3labs
Ajax Frameworks-php libraries
Sajax
‘Sajax is a tool to make programming websites using the Ajax framework — also known as XMLHTTPRequest or remote scripting — as easy as possible. Sajax makes it easy to call ASP, Cold Fusion, Io, Lua, Perl, PHP, Python or Ruby functions from your webpages via JavaScript without performing a browser refresh. The toolkit does 99% of the work for you so you have no excuse to not use it.’

PHP Class Library - Xajax

‘xajax is an open source PHP class library that allows you to easily create powerful, web-based, Ajax applications using HTML, CSS, JavaScript, and PHP. Applications developed with xajax can asynchronously call server-side PHP functions and update content without reloading the page.’

CPAINT - Ajax Toolkit - what is CPAINT?

‘CPAINT (Cross-Platform Asynchronous INterface Toolkit) is a multi-language toolkit that helps web developers design and implement AJAX web applications with ease and flexibility. It was originally born out of the author’s frustration and disappointment with other open-source AJAX toolkits. It is built on the same principles of AJAX, utilizing JavaScript and the XMLHTTP object on the client-side and the appropriate scripting language on the server-side to complete the full circle of data passing from client to server and back.’

Ajax HTML using PEAR - libraries

This is a PHP and JavaScript package available through the official PEAR website.

Should I use an HTTP GET or POST for my AJAX calls?

AJAX requests should use an HTTP GET request when retrieving data where the data will not change for a given request URL. An HTTP POST should be used when state is updated on the server. This is in line with HTTP idem potency recommendations and is highly recommended for a consistent web application architecture.
What API function provides the connection between the client and server?
XMLHttpRequest
what is ajax? when ajax was born?
"AJAX is an acronym for Asynchronous JavaScript and XML. If you think it doesn't say much, we agree. Simply put, AJAX can be read "empowered JavaScript", because it essentially offers a technique for client-side JavaScript to make background server calls(such as from PHP,ASP.NET,JSP,RUby etc) and retrieve additional data as needed, updating certain portions of the page without causing full page reloads".
The XMLHttpRequest object enables JavaScript to access the server asynchronously, so that the user can continue working, while functionality is performed in the background.

The name AJAX was born in 2005, in Jesse James Garret's article at http://www.adaptivepath.com/publications/essays/archives/ 000385.php,
and gained much popularity when used by Google in many of its applications.
PHP Fresher Job Questions
How can we get second of the current time using date function?

echo $second = date("s");
?>

How can we know the number of elements in an array using php?

Ans:
There are two ways:
1) sizeof($myarray) - This function is an alias of count()
2) count($array) - This function returns the number of elements in an array.
Note
if you just pass a simple variable instead of an array, count() will return 1.
What are the different functions in sorting an array?
Ans:
asort()
arsort()
ksort()
krsort()
uksort()
sort()
natsort()
rsort()

What would the following code print to the browser? Why?


$num = 10;
function multiply(){
$num = $num * 10;
}
multiply();
echo $num;
?>
Ans: 10 because,its a call by value.$num is static here.
change the above code as
$num = 10;
function multiply(){
global $num ;
$num = $num * 10;
}
multiply();
echo $num;

?>
ANS: 100

How can you get round the stateless nature of HTTP using PHP?

ANS: using Sessions in PHP
What function can you use to open a file for reading and writing?
1. fget();
2. file_open();
3. fopen();
4. open_file();

ANS:fopen();

What function would you use to redirect the browser to a new page?

1. redir()
2. header()
3. location()
4. redirect()

ANS:header()

No comments:

Post a Comment