0 comments
What is meant by MIME?

Answer 1:

MIME is Multipurpose Internet Mail Extensions is an Internet standard for the format of e-mail. However browsers also uses MIME standard to transmit files. MIME has a header which is added to a beginning of the data. When browser sees such header it shows the data as it would be a file (for example image)


Some examples of MIME types:

audio/x-ms-wmp

image/png

aplication/x-shockwave-flash


Answer 2:

Multipurpose Internet Mail Extensions.

WWW's ability to recognize and handle files of different types is largely dependent on the use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard provides for a system of registration of file types with information about the applications needed to process them. This information is incorporated into Web server and browser software, and enables the automatic recognition and display of registered file types. …


How can we know that a session is started or not?

A session starts by session_start() function.

This session_start() is always declared in header portion. it always declares first. then we write session_register().


What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

Answer 1:

mysql_fetch_array() -> Fetch a result row as a combination of associative array and regular array.

mysql_fetch_object() -> Fetch a result row as an object.

mysql_fetch_row() -> Fetch a result set as a regular array().


Answer 2:

The difference between mysql_fetch_row() and mysql_fetch_array() is that the first returns the results in a numeric array ($row[0], $row[1], etc.), while the latter returns a the results an array containing both numeric and associative keys ($row['name'], $row['email'], etc.). mysql_fetch_object() returns an object ($row->name, $row->email, etc.).


If we login more than one browser windows at the same time with same user and after that we close one window, then is the session is exist to other windows or not? And if yes then why? If no then why?

Session depends on browser. If browser is closed then session is lost. The session data will be deleted after session time out. If connection is lost and you recreate connection, then session will continue in the browser.


What are the MySQL database files stored in system ?

Data is stored in name.myd

Table structure is stored in name.frm

Index is stored in name.myi


What is the difference between PHP4 and PHP5?

PHP4 cannot support oops concepts and Zend engine 1 is used.


PHP5 supports oops concepts and Zend engine 2 is used.

Error supporting is increased in PHP5.

XML and SQLLite will is increased in PHP5.


Can we use include(abc.PHP) two times in a PHP page makeit.PHP”?

Yes we can include that many times we want, but here are some things to make sure of:

(including abc.PHP, the file names are case-sensitive)

there shouldn't be any duplicate function names, means there should not be functions or classes or variables with the same name in abc.PHP and makeit.php


What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

mysql_fetch_array - Fetch a result row as an associative array and a numeric array.


mysql_fetch_object - Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows


mysql_fetch_row() - Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.


What is meant by nl2br()?

Anwser1:

nl2br() inserts a HTML tag
before all new line characters \n in a string.


How can we encrypt and decrypt a data presented in a table using MySQL?

You can use functions: AES_ENCRYPT() and AES_DECRYPT() like:


AES_ENCRYPT(str, key_str)

AES_DECRYPT(crypt_str, key_str)


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

For this purpose, you can first read the data from one server into session variables. Then connect to other server and simply insert the data into the database.


WHO IS THE FATHER OF PHP AND WHAT IS THE CURRENT VERSION OF PHP AND MYSQL?

Rasmus Lerdorf.

PHP 5.1. Beta

MySQL 5.0


IN HOW MANY WAYS WE CAN RETRIEVE DATA IN THE RESULT SET OF MYSQL USING PHP?

mysql_fetch_array - Fetch a result row as an associative array, a numeric array, or both

mysql_fetch_assoc - Fetch a result row as an associative array

mysql_fetch_object - Fetch a result row as an object

mysql_fetch_row —- Get a result row as an enumerated array

Magic Methods

0 comments
The function names __construct, __destruct , __call, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __set_state, __clone and __autoload are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

__sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.
The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.
The __sleep method should return the value to serialize (usually $this), otherwise NULL is serialized.
Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that the object may have.
The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

Example . Sleep and wakeup

class Connection {
protected $link;
private $server, $username, $password, $db;

public function __construct($server, $username, $password, $db)
{
$this->server = $server;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->connect();
}

private function connect()
{
$this->link = mysql_connect($this->server, $this->username, $this->password);
mysql_select_db($this->db, $this->link);
}

public function __sleep()
{
return array('server', 'username', 'password', 'db');
}

public function __wakeup()
{
$this->connect();
}
}
?>

__toString
The __toString method allows a class to decide how it will react when it is converted to a string.

Example. Simple example

// Declare a simple class
class TestClass
{
public $foo;

public function __construct($foo) {
$this->foo = $foo;
}

public function __toString() {
return $this->foo;
}
}

$class = new TestClass('Hello');
echo $class;
?>

The above example will output:

Hello

It is worth noting that before PHP 5.2.0 the __toString method was only called when it was directly combined with echo() or print().

__set_state
This static method is called for classes exported by var_export() since PHP 5.1.0.

The only parameter of this method is an array containing exported properties in the form array('property' => value, ...).

Differences Between PHP 4 and 5

0 comments
Some of the questions in the interview test your understanding of how PHP 5 differs from previous versions. As such, it’s a good idea to be fully aware of at least the major changes that have occurred between the two versions. Almost all the information contained in this appendix has already been covered in the preceding chapters; therefore, we present it here mostly for the sake of convenience, and we do not dwell much on explanations—for more information on any particular topic, you can refer back to the appropriate section of this book, or to the PHP manual.
Language Features
• PHP 5 allows limited type hinting. This allows you to specify that the parameter to a function or class method can only be of a specific class (or one of its subclasses), or an array. However, you may not specify any other scalar types.

• The foreach construct now supports by-reference declaration of the value element.

• A number of new functions, particularly for string and arraymanipulation, has
also been added to the core platform.

Objects

• For all intents and purposes, all objects in PHP 5 are passed by reference.This
means that assigning an object to a variable will not create a copy of the former,
but simply creates another reference to it.

• Constants, aswell as staticmethods and properties, can nowbe definedwithin
the scope of a class.

• Class methods and properties now feature visibility, and can be declared as
public, private or protected. Classes and methods can also be declared as
final to prevent further inheritance.

• Since all objects are assigned by reference, you now need a specialized mechanism
to copy objects. This is provided by the clone construct and the __clone() magic method.
• PHP 5 features unified constructors and destructors—all constructors should
now be named __construct(), and the new __destruct() magic method has been added for object destruction.

• With the addition of interfaces and abstract classes, PHP developers now have
far greater control over how they implement their object-oriented code. Interfaces
can be used to define common APIs, while abstract classes provide models for class implementations that follow a specific blueprint.

• Class definitions can now be loaded on demand by using the __autoload()function.

MagicMethods

A multitude of new “magic” methods has been introduced in PHP 5:

• __get() and __set() are called when accessing or assigning an undefined object
property, while __call() is executed when calling a non-existent method of a class.

• __isset() is called when passing an undefined property to the isset()construct.

• __unset() is called when passing an undefined property to unset().

• __toString() is called when trying to directly echo or print() an object.

• __set_state() is inserted dynamically by var_export() to allow for reinitialization
on execution of var_export()’s output.

Selected New Extensions

• SimpleXML allows easy access to XML data using object and array notation.

• PHP 5 also introduces a DOMXML, DOMXSL and Sablotron replacement in the formof the libxml2-based DOM and XSL extensions.

• The PHP Data Objects (PDO) extension provides a unified database access extension
that allows access to many different types of database systems by using a common interface. PDO is not an abstraction layer—except for prepared queries, it does nothing to abstract the actual database code (SQL), itself.

• The hash extension is a new replacement for the GPLed libmhash; it was added
to the PHP core starting with version 5.1.2. It can produce hashes using many
algorithms, including the familiarMD5and SHA1, aswell as some more secure (albeit slower) algorithms, such as snefru.

• The Standard PHP Library (SPL) provides numerous interfaces that enhance
the way classes interact with the PHP language, including the new Iterator interfaces.

• The new Reflection extension allows for runtime introspection of executing
PHP code.

ErrorManagement

• Classes now support exceptions; the new set_exception_handler() function
allows you to define a script-wide exception handler.

• The E_STRICT error reporting level has been added to the language to emit notices
when legacy or deprecated code is encountered.

Source : Zend PHP 5 Certification Study Guide

Comparison Operators

0 comments
Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.

Table Comparison Operators












Example
Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.


If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers. These rules also apply to the switch statement.


var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true

switch ("a") {
case 0:
echo "0";
break;
case "a": // never reached because "a" is already matched with 0
echo "a";
break;
}
?>

source: php manual

xml_parse_into_struct() Function

1 comments
Definition
The xml_parse_into_struct() function parses XML data into an array.

This function parses the XML data into 2 arrays:

Value array - containing the data from the parsed XML
Index array - containing pointers to the location of the values in the Value array
This function returns 1 on success, or 0 on failure.

Syntax
xml_parse_into_struct(parser,xml,value_arr,index_arr)











Parameter
Description

parser Required.
Specifies XML parser to use

xml Required.
Specifies XML data to parse

value_arr Required.
Specifies the target array for the XML data

index_arr Optional.
Specifies the target array for index data


Note: The xml_parse_into_struct() function returns 1 for success and 0 for failure. This is not the same as TRUE and FALSE.

Example
XML File

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

PHP Code

//invalid xml file
$xmlfile = 'test.xml';
$xmlparser = xml_parser_create();// open a file and read data
$fp = fopen($xmlfile, 'r');
$xmldata = fread($fp, 4096);xml_parse_into_struct($xmlparser,$xmldata,$values);xml_parser_free($xmlparser);
print_r($values);
?>

The output of the code above will be:

Array
(
[0] => Array
(
[tag] => NOTE
[type] => open
[level] => 1
[value] =>
)
[1] => Array
(
[tag] => TO
[type] => complete
[level] => 2
[value] => Tove
)
[2] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[3] => Array
(
[tag] => FROM
[type] => complete
[level] => 2
[value] => Jani
)
[4] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[5] => Array
(
[tag] => HEADING
[type] => complete
[level] => 2
[value] => Reminder
)
[6] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[7] => Array
(
[tag] => BODY
[type] => complete
[level] => 2
[value] => Don't forget me this weekend!
)
[8] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[9] => Array
(
[tag] => NOTE
[type] => close
[level] => 1
)
)

SOURCE:w3schools.com
0 comments

What are the functions for IMAP?


imap_body - Read the message body

imap_check - Check current mailbox

imap_delete - Mark a message for deletion from current mailbox

imap_mail - Send an email message


 


What are encryption functions in PHP?


CRYPT()

MD5()


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


htmlspecialchars() - Convert some special characters to HTML entities (Only the most widely used)

htmlentities() - Convert ALL special characters to HTML entities


What is the functionality of the function htmlentities?


htmlentities() - 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.


How can we get the properties (size, type, width, height) of an image using php image functions?


To know the image size use getimagesize() function

To know the image width use imagesx() function

To know the image height use imagesy() function


How can we increase the execution time of a php script?


By the use of void set_time_limit(int seconds)

Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.



When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.


HOW CAN WE TAKE A BACKUP OF A MYSQL TABLE AND HOW CAN WE RESTORE IT?


Answer 1:

Create a full backup of your database: shell> mysqldump tab=/path/to/some/dir opt db_name

Or: shell> mysqlhotcopy db_name /path/to/some/dir



The full backup file is just a set of SQL statements, so restoring it is very easy:



shell> mysql "."Executed";





Answer 2:

To backup: BACKUP TABLE tbl_name TO /path/to/backup/directory

' To restore: RESTORE TABLE tbl_name FROM /path/to/backup/directory





mysqldump: Dumping Table Structure and Data



Utility 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!


How to set cookies?


setcookie('variable','value','time')

;

variable - name of the cookie variable

value - value of the cookie variable

time - expiry time

Example: setcookie('Test',$i,time()+3600);



Test - cookie variable name

$i - value of the variable 'Test'

time()+3600 - denotes that the cookie will expire after an one hour


How to reset/destroy a cookie


Reset a cookie by specifying expire time in the past:

Example: setcookie('Test',$i,time()-3600); // already expired time



Reset a cookie by specifying its name only

Example: setcookie('Test');


WHAT TYPES OF IMAGES THAT PHP SUPPORTS?


Using imagetypes() function to find out what types of images are supported in your PHP engine.

imagetypes() - Returns the image types supported.

This function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM.


CHECK IF A VARIABLE IS AN INTEGER IN JAVASCRIPT


var myValue =9.8;

if(parseInt(myValue)== myValue)

alert('Integer');

else

alert('Not an integer');


Tools used for drawing ER diagrams.


Case Studio

Smart Draw


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


Answer 1:

bool is_numeric( mixed var)

Returns TRUE if var is a number or a numeric string, FALSE otherwise.



Answer 2:

Definition and Usage

The isNaN() function is used to check if a value is not a number.



Syntax

isNaN(number)



Parameter Description

number Required. The value to be tested


How can we submit from without a submit button?


Trigger the JavaScript code on any event ( like onSelect of drop down list box, onfocus, etc ) document.myform.submit(); This will submit the form.


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


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

Classes & Objects In php5

0 comments
class
Every class definition begins with the keyword class, followed by a class name, which can be any name that isn't a reserved word in PHP. Followed by a pair of curly braces, which contains the definition of the classes members and methods. A pseudo-variable, $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but can be another object, if the method is called statically from the context of a secondary object). This is illustrated in the following examples: Example $this variable in object-oriented language

class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this is not defined.\n";
}
}
}

class B
{
function bar()
{
A::foo();
}
}

$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>

The above example will output:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.



Example . Simple Class definition

class SimpleClass
{
// member declaration
public $var = 'a default value';

// method declaration
public function displayVar() {
echo $this->var;
}
}
?>


The default value must be a constant expression, not (for example) a variable, a class member or a function call. Example . Class members' default value

class SimpleClass
{
// invalid member declarations:
public $var1 = 'hello '.'world';
public $var2 = <<hello world
EOD;
public $var3 = 1+2;
public $var4 = self::myStaticMethod();
public $var5 = $myVar;

// valid member declarations:
public $var6 = myConstant;
public $var7 = self::classConstant;
public $var8 = array(true, false);


}
?>



Note: There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

new
To create an instance of a class, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

Example . Creating an instance

$instance = new SimpleClass();
?>


When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.

Example . Object Assignment

$assigned = $instance;
$reference =& $instance;

$instance->var = '$assigned will have this value';

$instance = null; // $instance and $reference become null

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>

The above example will output:

NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned will have this value"
}


extends
A class can inherit methods and members of another class by using the extends keyword in the declaration. It is not possible to extend multiple classes, a class can only inherit one base class.

The inherited methods and members can be overridden, unless the parent class has defined a method as final, by redeclaring them within the same name defined in the parent class. It is possible to access the overridden methods or members by referencing them with parent::

Example . Simple Class Inheritance

class ExtendClass extends SimpleClass
{
// Redefine the parent method
function displayVar()
{
echo "Extending class\n";
parent::displayVar();
}
}

$extended = new ExtendClass();
$extended->displayVar();
?>

The above example will output:

Extending class
a default value

foreach loop

0 comments
PHP 4 introduced a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:


foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.
As of PHP 5, it is possible to iterate objects too.

Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. Therefore, the array pointer is not modified as with the each() construct, and changes to the array element returned are not reflected in the original array. However, the internal pointer of the original array is advanced with the processing of the array. Assuming the foreach loop runs to completion, the array's internal pointer will be at the end of the array.

As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)?>


This is possible only if iterated array can be referenced (i.e. is variable).

Note: foreach does not support the ability to suppress error messages using '@'.
You may have noticed that the following are functionally identical:
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
echo "Value: $value
\n";
}

foreach ($arr as $value) {
echo "Value: $value
\n";
}
?>


The following are also functionally identical:

$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
echo "Key: $key; Value: $value
\n";
}

foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value
\n";
}
?>

Character Type Functions

0 comments
Introduction
The functions provided by this extension check whether a character or string falls into a certain character class according to the current locale
When called with an integer argument these functions behave exactly like their C counterparts from ctype.h. It means that if you pass an integer smaller than 256 it will use the ASCII value of it to see if it fits in the specified range (digits are in 0x30-0x39). If the number is between -128 and -1 inclusive then 256 will be added and the check will be done on that.
When called with a string argument they will check every character in the string and will only return TRUE if every character in the string matches the requested criteria. When called with an empty string the result will always be TRUE in PHP < 5.1 and FALSE since 5.1.
Passing anything else but a string or integer will return FALSE immediately.
It should be noted that ctype functions are always preferred over regular expressions, and even to some equivalent str_* and is_* functions. This is because of the fact that ctype uses a native C library and thus processes significantly faster.

Requirements
None besides functions from the standard C library which are always available.

Installation
Beginning with PHP 4.2.0 these functions are enabled by default. For older versions you have to configure and compile PHP with --enable-ctype. You can disable ctype support with --disable-ctype.
The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.

Note: Builtin support for ctype is available with PHP 4.3.0.

Runtime Configuration
This extension has no configuration directives defined in php.ini.

Resource Types
This extension has no resource types defined.

Predefined Constants
This extension has no constants defined.

functions
ctype_alnum -- Check for alphanumeric character(s)
ctype_alpha -- Check for alphabetic character(s)
ctype_cntrl -- Check for control character(s)
ctype_digit -- Check for numeric character(s)
ctype_graph -- Check for any printable character(s) except space
ctype_lower -- Check for lowercase character(s)
ctype_print -- Check for printable character(s)
ctype_punct -- Check for any printable character which is not whitespace or an alphanumeric character
ctype_space -- Check for whitespace character(s)
ctype_upper -- Check for uppercase character(s)
ctype_xdigit -- Check for character(s) representing a hexadecimal digit