Вы находитесь на странице: 1из 97

PHP the completed note

Web hardware and software Basics


Markup languages like HTML, XML are used for the designing of web pages. For the
presentation and appearance CSS is used.
Common Gateway Interface
CGI is the standard protocol that defines how the web server software can assign the generation
of web pages to a console application. Such applications are known as CGI scripts. They are
written in scripting languages. These scripts are executed by operating system and results are
given back to the web server. But now a day these scripts (PHP, ASP) run directly by the web
server itself or by the extension modules such as mod_pearl, mod_php etc. This is called direct
execution.
Both of these CGI and direct execution can be used to build complex multi page sites. But
direct execution results lower overhead due to the lack of calls to the external interpreter.
Ques: How a PHP script can execute using command line?
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.
Server side scripting and Client side Scripting
Server Scripting
It is the web server technology in which user's request is fulfilled by running a script and the
web server generate dynamic pages. It is used to provide the interactive website that interface to
the databases or data stores.
The primary advantage of server scripting is the ability to customize the response based on the
needs, access rights, or queries into databases. In this programmers can write their own server,
client and communication protocol that can be only be used with one another. In earlier days
server scripting was done by the combination of C, Perl and shell scripts using CGI. Eg: ASP/
ASP.Net, PHP, JAVA, Java Script, PERL, Ruby, Lasso, JSP, SMX, Python.
Client Scripting
Client side scripting is the class of computer programs on the web that are executed at the client
side by the user's web browser. These computer programs are written in Dynamic HTML so tat
the web pages to be scripted. ie. Change in content depending on user input, environmental
conditions and variables.
Client side scripts are two types. External Scripts and Embedded scripts.
The scripts can write within the HTML codes then it is called embedded scripts. Sometimes
scripts can write in a separate file and called when needed .This is called external scripts.
When client request, demanded files are sent to the client’s computer by the corresponding web
server. The user's web browser executes the script and displays the document, including visible
output from the script.
Client side may also contain instruction for browser to follow if the user interacts with
document eg: clicking button.
These instructions can be followed without the communication with server. The client side
scripts can see be seen by the users but can't change it.
Server Scripting Client Scripting
1. Done at the server side. Done at client side
2. Script executed by the web server of server. Executed by web browser of client.
3. Produced output can understand by web browser Output is the display of execution of script.
(DHTML). User can see source code.
4. User can't see source code unless author publishes They have great access to the information and
code. functions available on the user's browser.
5. They have greater access to the information and Client side scripts do not require any additional
functions available on the server. software on the server. But requires web
6. Server side scripts require language interpreter browser which understands the scripting
installed on server regardless of the client's web browser, language.
OS or System calls. Eg; Javascript, VB script.

7. Eg: PHP, ASP


Web server
Web server is a computer program that is responsible for accepting HTTP requests from clients
and serving them HTTP responses along with optional data contents.
HTML Basics
Hyper Text Markup Language is the first member of SGML (Standard Generalized Markup
Language). It is used to design layout of the documents and to specify Hyperlinks. HTML
contains tags and attributes. Tag is coded HTML command that defines how part of web page
should be displayed. Attribute is a special word used inside the tag to specify additional
information to tag. Eg: bgcolor, size.
Format of HTML:
<HTML>
<HEAD>
<TITLE></TITLE>
<META></META>
<SCRIPT></SCRIPT>
</HEAD>
<BODY> </BODY>
</HTML>
Tags and attributes
WAMP and LAMP
Ques: What are the reasons for selecting LAMP (Linux, Apache, MySQL, Php) instead of
combination of other software programs, servers and operating systems?
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 faster than ASP or any other scripting language.
Dream weaver

Macromedia Dream weaver 8 is a professional HTML editor for designing, coding, and
developing websites, web pages, and web applications. Whether you enjoy the control of hand-
coding HTML, or prefer to work in a visual editing environment, Dreamweaver provides you
with helpful tools to enhance your web creation experience.

This guide introduces you to using Macromedia Dreamweaver 8 if you’re unfamiliar with any
major aspect of it.The tutorials in this guide lead you through the process of creating a simple but
functional website.

Macromedia Dreamweaver 8 is a professional HTML editor for designing, coding, and


developing websites, web pages, and web applications. Whether you enjoy the control of hand-
coding HTML or prefer to work in a visual editing environment, Dreamweaver provides you
with helpful tools to enhance your web creation experience.

The visual editing features in Dreamweaver let you quickly create pages without writing a line of
code. You can view all your site elements or assets and drag them from an easy-to-use panel
directly into a document. You can streamline your development workflow by creating and editing
images in Macromedia Fireworks or another graphics application, then importing them directly
into Dreamweaver, or by adding Macromedia Flash objects.

Dreamweaver also provides a full-featured coding environment that includes code-editing tools
(such as code coloring and tag completion) and language reference material on Cascading Style
Sheets (CSS), JavaScript, and ColdFusion Markup Language (CFML), among others.
Macromedia Roundtrip HTML technology imports your hand-coded HTML documents without
reformatting the code; you can then reformat code with your preferred formatting style.

Dreamweaver also enables you to build dynamic database-backed web applications using server
technologies such as CFML, ASP.NET, ASP, JSP, and PHP.

Dreamweaver is fully customizable. You can create your own objects and commands, modify
keyboard shortcuts, and even write JavaScript code to extend Dreamweaver capabilities with
new behaviors, Property inspectors, and site reports.

Tomcat
PHP
The PHP Hypertext Preprocessor is a scripting language that allows web developers to create
dynamic content that interacts with databases. PHP is basically used for developing web based
software applications. PHP is faster than ASP or any other scripting language.
PHP History
Macro Tabini is the founder of PHP architecture. Earlier days PHP was Personal Home Page.
PHP developed by Rasmus Lerdorf. Lerdorf created PHP tools to perform tasks such as
displaying his resume and recording how much traffic his page receiving. Then he made a form
interpreter named PHP/FI by combining Common Gateway Interface Binaries (CGI).PHP/FI
can support C language, communicate with databases and can build Simple dynamic web pages.
Lerdorf published PHP in 1995 June 8. Release name was PHP2. It included PERL variables,
form handlings and HTML support.
In 1997 two Israeli developers Zeev Suraski and Andi Gutmans formed PHP3 and its name was
changed to Hypertext Preprocessor. In November 1997 PHP/FT2 is formed and in 1998 PHP3
officially launched.
Zeev and Andi make PHP core named PHP4 by creating Zend Engine I in 1999. Zend Engine is
an open source scripting engine. Zend Engine has licensed by PHP License since 2001. Zend is
combination of Zev and Andi. They also formed Zend Technologies at Rasmat Gan, Israel.
Released PHP4 on 2000 May 22 with Zend Engine II.
PHP5 is created with Zend Engine II and released on July 13, 2004. PHP 5 has the features that
• data object extensions.
• Late static building
PHP 6 created from PHP 5 by adding some advantages.
• register_globals, magic quotes and safe mode are removed. register_globals is a function
that defines whether or not register EGPCS(Environment,GET, POST, Cookie, Server) as
global variables. Magic quotes: is feature that prevents inexperienced developers from
writing code which is vulnerable to SQL injection attack. Safe mode: iS access utility to
troubleshoot.
• Supports uni-code, multibyte strings and ASCII characters.
• Run in both 32 bit and 64 bit environment
Version number Release Date  Features
1 June 8 1995  Personal Home Page
2 November 1 1997 Fastest tool for dynamic page creation.
3 June 6 1998 Zeev and Andi's PHP3
4.0 May 22 2000 Zend Engine.
4.1 December 2001 Super globels ($_GET, $_POST, $_SESSION) added.
4.2 April 2002  register_globels disabled.
4.3 December 2002 Command Line Interpreter added to CGI.
4.4 July 11 2005 Manpages for phpsize and php_config.
• 4.4.8 January 3 2008 Security enhancement and bug fix.
• 4.4.9 August 7 2008 More security enhancement.
5 July 13 2004 Zend Engine II
5.1 November 24 2005 Compiler variables in PHP Engine
5.2 November 2 2006 Enable filter extension by default.
• 5.2.11 September 16 2009 Bug and security fix
• 5.2.12 ­ ­
5.3 June 30 2009  Name space support
 Late Static binding
 Jump label
 Native Closures
 Native PHP archives
 Garbage collections
 Window Support
 Persistent connection with MySQL
  Ternary shortcuts

• 5.3.1 November 19 2009  php extension


Bug and security fixes.
6  Unicode Support
 Alternate PHP cache
 Removal of register_globals, magic quotes and safe mode.

PEAR
PEAR is short for "PHP Extension and Application Repository". PEAR is the next revolution in
PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and
distribution system for reusable PHP components. It eases installation by bringing an automated
wizard, and packing the strength and experience of PHP users into a nicely organized OOP
library. PEAR also provides a command-line interface that can be used to automatically install
"packages" . The purpose of PEAR is to provide:

• A structured library of open-sourced code for PHP users


• A system for code distribution and package maintenance
• A standard style for code written in PHP
• The PHP Foundation Classes (PFC),
• The PHP Extension Community Library (PECL)
• A web site, mailing lists and download mirrors to support the PHP/PEAR community

PHP features
• Performance: Scripts written in PHP executes faster than other Scripting languages.
Optimized memory manager and third party accelerators improves the performance and
response time.
• Portability: PHP is portable to MS Windows, UNIX and Mac OS ,OS/2.
• Ease of use: PHP syntax is clear and consistent.
• Open Source: PHP has GPL license and so it is freely available without any cost.
• Community Support: PHP developing is done through more than 100 of developers
among world.
• Third party application Support: PHP supports wide range of databases. It supports
MySQL,postgre SQL ,ORACLE, and Ms SQL Sever.
• Automatic Compilation: PHP is interpreted language that is a change made in source
code will test automatically.
PHP3 vs PHP4
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.
PHP 5.3 Features
Zend Engine Architecture
Variables and data types
PHP variables contain int, float, double string etc. It is loosely coupled that is the type will
implicitly change the type of variable as needed, depending on the operations being done in
value. PHP variables are identified by $ symbol followed by variable name. Name contains a-z,
A-Z and should start with a letter and then follows _, numbers etc. PHP supports pointers.
Ques: Would you initialize your strings with single quotes or double quotes?
Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a
better idea speed-wise to initialize a string with single quotes, unless you specifically need
variable substitution.
Variables
Variables are temporary storage containers. In PHP, a variable can contain any type of data,
such as, for example, strings, integers, floating-point numbers objects and arrays. PHP is loosely
typed, meaning that it will implicitly change the type of a variable as needed, depending on the
operation being performed on its value. PHP variables are identified by a dollar sign $, followed
by an identifier name. Variables must be named using only letters (a-z, A-Z), numbers and the
underscore character; their names must start with either a letter or an underscore.
Indirect Referencing of Variables
In PHP it is possible to create a variable whose name is contained in another variable.
Example:
<?php
$x="John";
$$x="sam";
echo $x;
echo "<br>";
echo $$x;
echo "<br>";
echo $John;
?>

Output
John
sam
sam
Ques: What is the difference between $message and $$message?
$message is a simple variable with a fixed name whereas $$message is a reference variable
whose name stored in $message. Ie if $message contains "var" $$message is the same as $var.
Example:
$a=”abc”;
$aa=”z”;
print($abc); // op is z
print($aa);// op is z
print($a); //op is abc
Data Types
1. PHP's scalar data types
Scalar data is data that only contains a single value. PHP features 6 scalar data types:
Type Description Example values
integer A whole number 7, -23
float A floating point number 7.68, -23.45
string A sequence of characters "Hello", "abc123@#$"
unicode A sequence of Unicode characters "Hello", "abc123@#$"
A sequence of binary (non-Unicode)
binary "Hello", "abc123@#$"
characters
boolean Either true or false true, false
2. PHP's compound data types
Compound data can contain multiple values. PHP has 2 compound data types:
Array: Can hold multiple values indexed by numbers or strings.
Object: Can hold multiple values (properties), and can also contain methods (functions) for
working on properties.
An array or object can contain multiple values, all accessed via one variable name. What's
more, those values can themselves be other arrays or objects. This allows you to create quite
complex collections of data.
3. PHP's special data types
As well as scalar and compound types, PHP has 2 special data types that don't fall into the other
categories:
resource :Used to access an external resource (for example, a file handle or database
connection) .
null :Can only contain the value null, which means "no value".
4. Loose typing in PHP
Some languages, such as Java, are strongly typed: once you've created a variable, you can't
change the type of data stored in it. PHP, in contrast, is loosely typed: you can change a
variable's data type at any time.
In the following PHP example, $x starts off by holding integer data (3). The next line appends
the string "hello" to the data using the concatenation operator, which changes $x's value to
"3hello" (a string data type). Finally, 5.67 is assigned to $x, changing its data type to a float:
$x = 3;
$x .= "hello";
$x = 5.67;
Hex and Octal digits: Hex is denoted by /X or /x and octal digits denoted by /0.
Eg: \023 and \x23 .The first one is octal 23, the second is hex 23.
5. Finding out the data type of a value
You can check a value's data type using one of the following PHP functions:
is_int( value )
Returns true if value is an integer, false otherwise
is_float( value )
Returns true if value is a float, false otherwise
is_string( value )
Returns true if value is a string, false otherwise
is_unicode( value )
Returns true if value is a Unicode string, false otherwise
is_binary( value )
Returns true if value is a binary string, false otherwise
is_bool( value )
Returns true if value is a Boolean, false otherwise
is_array( value )
Returns true if value is an array, false otherwise
is_object( value )
Returns true if value is an object, false otherwise
is_resource( value )
Returns true if value is a resource, false otherwise
is_null( value )
Returns true if value is null, false otherwise
is_unicode() and is_binary() are only available in PHP 6 and later.
For example, the following code displays 1 (true):
$x = 3.14;
echo is_float( $x );
6. Changing data types with settype()
As you've already seen, you can change a variable's data type simply by assigning a new value
of a different type to the variable. However, sometimes it's a good idea to explicitly set the type
of the data held by a variable. For example, if you're handing data entered by a visitor, or
passing data to another program, then it's good to ensure that the data is of the correct type.
PHP has a function called settype() that converts a variable's value from one data type to
another:
$x = 3.14;
settype( $x, "integer" );

In the above example, $x's data type is changed from float to integer (with the result that $x
ends up containing the value 3).
Be careful when changing data types, since you may end up losing information — for example,
when changing a float (3.14) to an integer (3).
7. Changing data types with casting
If you just want to change a value's type at the time you use the value, then you can use casting.
This merely changes the type of the value that is to be used; the original variable remains
untouched.
To cast a value, place the data type in parentheses before the value at the time you use it:

$x = 3.14;
echo (integer) $x;
The above code displays 3 (3.14 cast to an integer). However, note that $x still contains the
value 3.14 after the cast operation.
You can, if you prefer, use (int) instead of (integer), and (bool) instead of (boolean).

Operators
An operator is any symbol used to perform an operation on a value. Operators can be classified
into three based on the number of operands it is processing.They are
 Unary Operator (operates on only one operand)
 Binary Operator (operates on two operands)
 Ternary Operator (operates on three operands)

Unary Operator
Incrementing/Decrementing Operators

PHP supports specific operators for incrementing and decrementing numbers. These are a short
hand way of expressing the increase or decrease of a value by one:

Operan Description
Name Sample
d
++ Post-increment $var++; Returns $var, then increases it by 1.
++ Pre-increment ++$var; Increases $var by 1, then returns it.
-- Post-decrement $var--; Returns $var, then decreases it by 1.
-- Pre-decrement --$var; Decreases $var by 1, the returns it.

Samples:

$x = 1;

$x++; $x would have the value of 2


$x = 4;
print --$x; -- 4 would be outputted, and then $x would be decremented.

Binary Operator
The Assignment Operator(=)
The assignment operator allows you to assign a value to a variable. You can assign strings,
integers, even the results of functions:

$var = "Hi there";


$var = 1;
$var = myfunction();

The Concatenation Operator ( . )


This operator allows you to append one value to another. You can append strings, other
variables or even the results of functions:

$var = "test";
$var2 = "This is a ".$var;
print $var2; -- This would output "This is a test"

You can also use the Assignment Concatenation Operator to append a new value to the value
an existing variable:

$var = "this is a test";


$var .=" of the emergency broadcast system";
print $var; -- This would output "This is a test of the emergency broadcast system"

Arithmetic Operators
Arithmetic Operators in PHP are used to work with numbers. Addition subtraction, division and
multiplication are all supported:

Opera Description
Name Sample
nd
+ Addition $var + $var2 Adds the two values together
Subtracts the second value from the
- Subtraction $var - $var2
first.
Multiplies the two values by each
* Multiplication $var * $var2
other.
/ Division $var/$var2 Divides the first value by the second.
Returns the remainder of the first
% Modulus $var%$var2
value divided by the second.
Modulus operator is used to find the remainder after division

Comparison Operators
Comparison Operators allow you to test things like whether one number value is larger, smaller
or equal to another. Unlike expressions with Arithmetic Operators (which return a value), those
with Comparison Operators evaluate to either TRUE or FALSE and are frequently used in
conditional statements:

Operan Description
Name Sample
d
Is true if the first value is equivalent to
== Equal to $var == $var2
the second.
Is true if the first value is not equal to
!= Not equal to $var != $var2
the second.
Is true if the first value is less than the
< Less than $var < $var2
second.
Is true if the first value is greater than
> Greater than $var > $var2
the second.
Is true if the first value is less than or
<= Less than or equal $var <= $var2
equal to the second.
Greater than or Is true if the first value is greater than
>= $var >= $var2
equal or equal to the second.

The Equal and Not-Equal To operators are also used to evaluate whether non-numerical values
are equal to each other.
This script how you can use a conditional statement to test whether or not the entered password
is the same as the stored one:

<?php
$storedpassword = "mypassword";
$enteredpassword = "mypassword";

if ($storedpassword == $enteredpassword) {
print "The entered password was correct!";
}else {
print "The entered password was wrong!";
}

?>

In addition to the comparision operators listed above, PHP4 has added two new ones that not
only allow you see if two values are equal, but also check to see if they are of the same type.

Operan Description
Name Sample
d
Is true if the first value is equivalent to
=== Identical $var === $var2
the second and both are the same type.
Is true if the first value is not equal to
!== Not identical to $var !== $var2 the second or they are not the same
type
Logical Operators

<?php

$storedusername = "user";
$enteredusername = "user";

$storedpassword = "mypassword";
$enteredpassword = "mypassword";
if ($storedusername == $enteredusername AND $storedpassword == $enteredpassword)
{
print "The entered username and password were correct!";
} else {
print "The entered username and password were wrong!";
}

?>

The "AND" between the two separate conditions tells the script that both must be true for the
entire statement to be considered true. If both are true, then "The entered username and
password were correct!" would be printed.

PHP supports several different Logical Operators:

Operan Description
Name Sample
d
AND And $var AND $var2 Is true if both values are true.
OR Or $var OR $var2 Is true if either value is true.
XOR Xor $var XOR $var2 Is true if either value is true, but not both.
&& And $var && $var2 Is true if both values are true.
|| Or $var || $var2 Is true if either value is true.
Is true if the value is not true (ex. if the
! Not !$var
variable doesnt exist).
Operator Precedence
Take a look at the following:

$x = 9 + 1 * 10
Because we read left to right, you might assume that $x equals 100 (Nine plus one, times 10,
equals 100); however, because of operator precedence, you would be wrong. The multiplication
operator has higher precedence than the addition operator, so that calculation would be
performed first: One times 10, plus nine, equals 19.

The same rules of precedence apply to Operators in PHP. Take a look at the below chart to get
an idea of how various operators rank. Operators listed in the same row have equal precedence.
Highest Precedence */%
+-.
< <= > >=
&&
||
And
Xor
Lowest precedence or

You can also force precedence by using parentheses:

$x = (9 + 1) * 10

Since the first part of the above equation is surrounded, it would be calculated first, and $x
would equal 100.
Ternary Operator
The ternary operator is a shorthand (albeit very hard to read) way of doing if statements.
<?php
$agestr = ($age < 16) ? 'child' : 'adult';
echo $agestr ;
?>
8.

Constants
Via define() directive, like define ("MYCONSTANT", 100);

Octal and hex numbers


PHP Interpreter treats numbers beginning with 0 as octal. \023 and \x23. The first one is octal
23, the second is hex 23.
<?php $str = ‘Hello,
there.\nHow are you?\nThanks for visiting fyicenter’; print $str; ?>
Because inside the single quotes the \n character is not interpreted as newline, just as a sequence
of two characters - \ and n.
echo vs print
echo is the most primitive of them, and just outputs the contents following the construct
to the screen. print is also a construct (so parentheses are optional when calling it), but it
returns TRUE on successful output and FALSE if it was unable to print out the string.
However, you can pass multiple parameters to echo, like:

<?php echo 'Welcome ', 'to', ' ', 'fyicenter!'; ?>


and it will output the string "Welcome to fyicenter!" print does not take multiple

parameters. It is also generally argued that echo is faster, but usually the speed advantage
is negligible, and might not be there for future versions of PHP. printf is a function, not a
construct, and allows such advantages as formatted output, but it’s the slowest way to
print out data out of echo, print and printf.

Operators
Control Structures and Control Loops
Control Structures allow a script to react differently depending on what has already occurred, or
based on user input, and allow the graceful handling of repetitive tasks.

In PHP, there are two primary types of Control Structures: Conditional Statements and Control
Loops.

Conditional Statements
Conditional Statements allow you to branch the path of execution in a script based on whether a
single, or multiple conditions, evaluate to true or false.
If Statements

If Statements always begin with "if", followed by a condition surrounded in parentheses. If the
condition evaluates to true, then the statement or statements immediately following the condition
will be executed.

<?php
$x=1;

if ($x == 1) print '$x is equal to 1';


?>

This example illustrates the simplest kind of If Statement. In this case, had the condition been
false, nothing would have occurred and you would have seen a blank browser window when the
script was run.

When you have more than one statement to be executed within a control structure, it's necessary
to surround them with brackets:

<?php
$x=1;

if ($x == 1) {
print '$x is equal to 1';
$x++;
print 'now $x is equal to 2';
}
?>
Keep in mind that the positioning of the elements does not affect the execution of the script. All
of the example arrangements below are perfectly valid not only for If Statements, but for every
form of control loop.

if ($x == 1) print '$x is equal to 1';

if ($x == 1)
print '$x is equal to 1';

if ($x == 1) { print '$x is equal to 1'; }

if ($x == 1) {
print '$x is equal to 1';
}

You can also include multiple conditions within parentheses. For the nested statements to
execute, all of the conditions must evaluate to true.

<?php
$x=1;

if ($x == 1 OR $x == 2) print '$x is equal to 1 (or maybe 2)';


?>

Else Statements

As the name implies, Else Statements allow you to do something else if the condition within an
If Statement evaluated to false:

<?php
$x=1;
if ($x == 2) {
print '$x is equal to 2';
} else {
print '$x is equal to 1';
}
?>

Else If Statements

Thus far, we have been able to respond to one condition, and do something if that condition is
not true. For evaluating multiple conditions you could use Else If Statements .
A combination of If and Else Statements, Else If Statements are evaluated sequentially if the
condition within the If Statement is false. When a condition within an Else If Statement evaluates
to true, the nested statements are parsed, the script stops executing the entire If/Else if/Else
Structure. The rest of the script proceeds to be parsed.

Take a look at the following example:

<?php
$x=1;

if ($x == 2) {
print '$x is equal to 2';
} else if ($x == 1) {
print '$x is equal to 1';
} else {
print '$x does not equal 2 or 1';
}
?>

The final else statement can be left off if you do not want anything to happen if none of the If or
Else If Statements are true:

<?php
$x=0;

if ($x == 2) {
print '$x is equal to 2';
} else if ($x == 1) {
print '$x is equal to 1';
}
?>

In this case, since neither the condition within the If or Else if Conditions are true, and no Else
Statement was provided, nothing would be outputted to the browser.

Switches

Switches are a good alternative to If/Else if/Else Statements in situations where you want to
check multiple values against a single variable or condition. This is the basic syntax:

<?php
$var = "yes";

switch ($var) {
case "yes":
print '$var is equal to yes';
break;

case "no":
print '$var is equal to no';
break;
}
?>

After running this code snippet, much of what is here will probably make sense to you. In the
first line of the switch statement, we have the identifier "switch" followed by a variable
surrounded by parenthesis. Each case includes a possible value for the variable.

Switches execute a little differently than If/Else if/Else statements. Once a case value matches
the value of the switch expression, every following statement is executed, including those
following other cases.

To prevent this from happening, a break statement is used. "Break;" ends the execution of the
switch statement, and lets the script continue execution; it can also be used in while or for loops.

Optionally, you may also include a special case called "default". This case works much like and
Else Statement, and will execute if all the other cases are found to be false. This case should be
the very last one you include.

<?php
$var = "yes";

switch ($var) {
case "maybe":
print '$var is equal to yes';
break;

case "no":
print '$var is equal to no';
break;
default:
print 'none of the other two cases were true, so this sentance will be printed
out instead.';
}
?>

Similar to the Break Statement is the Exit Statement. Exit is particularly useful in situations
where you run into what would be considered a "fatal error" (for example, if the user had entered
a password that was incorrect) or any other time you needed to end the execution of a script
before it naturally terminated.

<?php
$var = "yes";

switch ($var) {
case "yes":
print '$var is equal to yes';
exit;
case "no":
print '$var is equal to no';
break;
}

print "this will not be printed, because the script will have terminate before this
line is reached";
?>

Unlike break, exit may be used anywhere in your scripts, inside or outside of control structures.
Control Loops

Frequently in PHP there are instances where you need to perform repetitive tasks, such as
formatting data pulled from a database, sending out emails to a mailing list, or cycling through
the contents of an array. Control Loops allow you to perform these tasks almost effortlessly.

While Loops
The statements nested within the loop will execute as long as the condition within the
parentheses evaluates to true. Since the validity of the condition is checked before the loop is
executed, if the condition is false, then the statements within the loop will not be executed at all.

<?php
$x=1;

while ($x <=10) {


print "$x<br>";
$x++;
}
?>

When you run this snippet, you will see the numbers 1 through 10 printed on your screen.
Do...While Loops
Do...While Loops are similar to While Loops. The primary difference in how these work is that
the validity of the condition in a Do...While Loop is tested after the loop has itinerated once.

<?php
$x=11;

do {
print "$x<br>";
$x++;
} while ($x <=10);?>

In the example above, $x would be printed out one time, and then the execution of the loop
would end, because $x is greater than 10.
For Loops

For Loops take three expressions separated by semi-colons. The first expression is only executed
one time, when the loop initializes. The next expression is a condition that is checked each time
the loop itinerates. Once the condition is false, the loop will stop executing. The final expression
will be executed each time the loop iterates after the nested statements have been parsed.

<?php
for($x=1; $x<=10; $x++) {
print "$x<br>";
}
?>

Typically, it's best to use a For Loop in situations where you know how many elements you will
be cycling through.
The Foreach Loop
This new loop was introduced in PHP version 4. Its used exclusively for looping through
elements of an array, allowing you to easily print out or perform operations on elements within
an array.

<?php

$Array = array();
$Array[]="http://www.yahoo.com/";
$Array[]="http://www.internet.com";
$Array[]="http://www.google.com";
$Array[]="http://www.cnn.com/";
$Array[]="http://www.php.net/";
foreach($Array as $key => $value) {

print "$key: $value<br>";


}
?>

The loop advances an internal pointer through each row of the array, assigns the key and the
value to variables, and then prints out one or both of them until the end of the array is reached.

Array
Arrays

PHP arrays are extremely flexible.They allow numeric, auto-incremented keys, alphanumeric
keys or a mix of both, and are capable of storing practically any value, including other
arrays,with over seventy functions for manipulating them.All arrays are ordered collections of
items, called elements. Each element has a value, and is identified by a key that is unique to the
array it belongs to.Keys can be either integer numbers or strings of arbitrary length.
Arrays are created one of two ways. The first is by explicitly calling the array() construct, which
can be passed a series of values and, optionally, keys.

$a = array (10, 20, 30);


$a = array (’a’ => 10, ’b’ => 20, ’cee’ => 30);
$a = array (5 => 1, 3 => 2, 1 => 3,);
$a = array();

A second method of accessing arrays is bymeans of the array operator ([]):

eg:
<?php
$x[]=10;
$x[]=2;
echo $x[0]." ".$x[1]; //output will be 10 2
?>

PHP provides two functions that can be used to outputa variable’s value recursively: print_r()
and var_dump(). They differ in a few key points:
• While both functions recursively print out the contents of composite value,
only var_dump() outputs the data types of each value
• Only var_dump() is capable of outputting the value of more than one variable
at the same time
• Only print_r can return its output as a string, as opposed to writing it to the
script’s standard output

eg:
<?php
$x[]=10;
$x[]=2;
print_r($x); //output will be Array ( [0] => 10 [1] => 2 )
?

<?php
$x[]=10;
$x[]=2;
var_dump($x); //output will be array(2) { [0]=> int(10) [1]=> int(2) }
?>

<?php
$x[]=10;
$x[]=2;
$y=array('c','d');
var_dump($x,$y);

?>

output will be array(2) { [0]=> int(10) [1]=> int(2) } array(2) { [0]=> string(1) "c" [1]=>
string(1) "d" }

Enumerative vs. Associative


Arrays can be roughly divided in two categories: enumerative and associative. Enumerative
arrays are indexed using only numerical indexes, while associative arrays allow the association
of an arbitrary key to every element.

Multi-dimensional Arrays
To create multi-dimensional arrays, we simply assign an array as the value for an array element.

Array Functions

in_array() to determine whether an element with a given value exists in an array


unset() to delete an element from the array
array_flip() inverts the value of each element of an array with its key
array_reverse() inverts the order of the array’s elements
sort() sorts an array based on its values.But effectively destroys all the keys in
the array and renumbers
its elements starting from zero
asort() sorts an array maintain key association

Functions

Defining a function
To create a new function, we simply use the keyword function, followed by an identifier, a pair
of parentheses and braces:
function name() { }
PHP function names are not case-sensitive. As with all identifiers in PHP, the name must consist
only of letters (a-z), numbers and the underscore character, and must not start with a number. To
make your function do something, simply place the code to be execute between the braces, then
call it.

function display()
{
echo "Hello World!";
}

display(); // Displays "Hello World!"

Returning Values
We can specify the return value of your function by using the return keyword:

function hello()
{
return "Hello World"; // No output is shown
}

$txt = hello(); // Assigns the return value "Hello World" to $txt


echo hello(); // Displays "Hello World"

return also allows you to interrupt the execution of a function and exit it even if you don’t want
to return a value:
<?php
$x=0;
function notfive($x)
{
if ($x== 5) {
return; // Nothing else in the function will be processed
}
echo "$x";
}

notfive(5); //no output

notfive(2); //o/p will be 2


?>
Functions can also be declared so that they return by reference; this allows you to return a
variable as the result of the function, instead of a copy (returning a copy is the default for every
data type except objects). Typically, this is used for things like resources (like database
connections).We must return a variable—you cannot return an expression by reference, or use
an empty return statement to force a NULL return value:

eg:
function &query($sql)
{
$result = mysql_query($sql);
return $result;
}
Any variable defined within a function is no longer available after the function has finished
executing. This allows the use of names which may be in use elsewhere without having to
worry about conflicts.

Passing Arguments
Arguments allow you to inject an arbitrary number of values into a function in order to
influence its behaviour.

Eg:
<?php
function add($x,$y)
{
$z=$x+$y;
return $x;
}

echo add(2,3);
?>

Variable-length Argument Lists


The ability to create a function that accepts a variable number of arguments, depending on the
circumstance.PHP provides three built-in functions to handle variable-length argument lists:
func_num_args(), func_get_arg() and func_get_args().

Eg:
<?php
function hello()
{
if (func_num_args() > 0) {
$arg = func_get_arg(0); // The first argument is at position 0
echo "Hello $arg";
} else {
echo "Hello World";
}
}
hello("Reader"); // Displays "Hello Reader"
hello(); // Displays "Hello World"
?>

You can use variable-length argument lists even if you do specify arguments in the function
header. However, this won’t affect the way the variable-length argument list functions behave—
for example, func_num_args() will still return the total number of arguments passed to your
function, both declared and anonymous.

<?php
function countAll($arg1)
{
if (func_num_args() == 0) {
die("You need to specify at least one argument");
} else {
$args = func_get_args(); // Returns an array of arguments
// Remove the defined argument from the beginning
array_shift($args);
$count = strlen ($arg1);
foreach ($args as $arg) {
$count += strlen($arg);
}
}
return $count;
}
echo countAll("foo", "bar", "baz"); // Displays ’9’

?>

Passing Arguments by Reference


Function arguments can also be passed by reference, as opposed to the traditional by-value
method, by prefixing them with the by-reference operator &. This allows your function to affect
external variables.

Example
<?php
function pass_by_reference(&$param) {
array_push($param, 4, 5);
}

$ar = array(1,2,3);

pass_by_reference($ar);

foreach ($ar as $elem) {


print "<br>$elem";
}
?>
The code above prints 1, 2, 3, 4, 5. This is because the array is passed as reference, meaning that
the function (pass_by_reference) doesn't manipulate a copy of the variable passed, but the
actual variable itself.

Passing Arguments by Value


Here the function manipulates a copy of the variable passed,not the actual variable itself.

Example
<?php
function pass_by_value($param) {
array_push($param, 4, 5);
}

$ar = array(1,2,3);
pass_by_value($ar);

foreach ($ar as $elem) {


print "<br>$elem";
}
?>

Different types of sorting


Sorting functions in PHP:

asort()
arsort()
ksort()
krsort()
uksort()
sort()
natsort()
rsort()

Parameter Passing
pass by value vs pass by reference
FORMS
Form: is the area that containing form variables
<form name=”f1” method=” ” action=' '> </form>
Attributes of form tag:
method: contains the HTTP methods for form processing. HTTP includes two methods to
achieve different goals. They are GET and POST.
GET vs POST
GET POST
1. The GET is used when the result of a request does  1. POST is used when the result of a request has 
not make any persistent changes. persistent side effect such as adding a row to database
2. It uses the collected data to find the resource. 2. POST creates the resource needed.
3.  Small amount of limited size data can pass  3. Large amount of data can be passed through URL.
through URL Maximum 1024 characters.
4. The name and value used in the form will display  4. The name and value used in form is passed through
on the address bar proceeded by URL. So it is not  invisible STD I/P. So user can't see the passed 
secure. information. So it is secure.
5. Used to pass small amount of less sensitive data. 5. Used to pass large amount of sensitive data.
6. GET call moves within the page Eg: exp  6. POST call moves from one page to another.
pagination, url calling etc.
Action: when the form is submitted content is sent to another file. The name of that file is
specified using action.
Different types of forms
Text Field: <input type=”text” name=”txtfld” size=25/>
Text area: <textarea name="textarea"></txtarea>
Password: <input type=”password” name=”psswdfld” size=25/>
Hidden Field: <input type="hidden" name="hiddenField" />
Check box: <input type="checkbox" name="chk" id="che" value="1" />
Radio Button: <input type="radio" name="radiobuttonname" value=”1”/>
Radio Button group: <input type="radio" name="male" value="1" /> <input type="radio"
name="female" value="0" />
List: <select name="select"> <option>abc</option> <option>def</option> </select>
Submit Button: <input name="Submitbutt" type="submit" id="Submitbutt"
value="Submit" />
If you don't want to use the Submit button to submit a form, you can use normal hyper links to
submit a form. But you need to use some JavaScript code in the URL of the link. For
example:<a href="javascript: document.myform.submit();">Submit Me</a> or In the Java
Script code, we can call the document.form.submit() function to submit the form. For example:
<input type=button value="Save" onClick="document.form.submit()">
Reset button: <input name="resetbutt" type="reset" id="resetbutt" value="Reset" />
Button: <input name="backbutton" type="button" id="backbutton" value="Button" />
Field Set: <fieldset> <legend> Introuduction </legend> </fieldset>
File operations
Uploading files
Once the Web server received the uploaded file, it will call the PHP script specified in the form
action attribute to process them. This receiving PHP script can get the uploaded file information
through the predefined array called $_FILES. Uploaded file information is organized in
$_FILES as a two-dimensional array as:
$_FILES[$fieldName]['name'] - The Original file name on the browser system.
$_FILES[$fieldName]['type'] - The file type determined by the browser.
$_FILES[$fieldName]['size'] - The Number of bytes of the file content.
$_FILES[$fieldName]['tmp_name'] - The temporary filename of the file in which the
uploaded file was stored on the server.
$_FILES[$fieldName]['error'] - The error code associated with this file upload.
The $fieldName is the name used in the <INPUT TYPE=FILE, NAME=fieldName>.

How to store the uploaded file to the final location?

move_uploaded_file ( string filename, string destination)


This function checks to ensure that the file designated by filename is a valid upload file
(meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it
will be moved to the filename given by destination. If filename is not a valid upload file, then
no action will occur, and move_uploaded_file() will return FALSE. If filename is a valid upload
file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will
return FALSE. Additionally, a warning will be issued.
Directory Operations
DATE and Time functions
adddate()
This is used to perform operations on a value of datatype datetime
Syntax
adddate(expression,interval indays/month/year)
Examples
select adddate('2009-10-11',interval 2 year);
O/P : 2011-10-11
select adddate('2009-10-11',interval 3 month);
O/P : 2010-01-11
select adddate('2009-10-11',interval 3 day);
O/P : 2009-10-14
curdate()
This is used to get the current date
Syntax
curdate()
Examples
select curdate();
curtime()
This is used to get the current time in hh:mm:ss
Syntax
curtime()
Examples
select curtime();
O/P : 23:28:46
date()
This is used to extract date from a datetime value
Syntax
date('datetime value')
Example
select date('2007-12-23 22:10:12');
O/P : 2007-12-23
datediff()
This is used to find how many days are there to reach the first date from the second date
Syntax
datediff('expression1','expression2')
Example
select datediff('2009-10-17','2009-10-11');
O/P :6
date_sub()
This is used to substract specified value in days/month/year from the given date
Syntax
date_sub('expression1',interval in days/month/year )
Example
select date_sub('2009-10-17',interval 6 day);
O/P : 2009-10-11
For further reference check http://dev.mysql.com/doc/refman/5.1/en/date-and-time-
functions.html
The number of days between two given dates using PHP
Simple arithmetic:
$date1 = date('Y-m-d');
$date2 = '2006-07-01';
$days = (strtotime() - strtotime()) / (60 * 60 * 24);
echo "Number of days since '2006-07-01': $days";
SELECT CURDATE();
SELECT CURRENT_DATE();
SELECT CURTIME();
SELECT CURRENT_TIME();
How can we know the number of days between two given dates using MySQL?
Use DATEDIFF()
SELECT DATEDIFF(NOW(),'2006-07-01');
MYSQL
MySQL SET function can take zero or more values, but at the maximum it can take 64 values.

DESCRIBE table_name;

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

The MySQL provides a LOAD DATA INFILE command. You can load data from a file.
Great tool but you need to make sure that:

a) Data must be delimited

b) Data fields must match table columns correctly

ALTER TABLE table_name CHANGE old_colm_name new_colm_name


ALTER TABLE table_name CHANGE colm_name same_colm_name [new data type]
Databases
What is the maximum length of a table name, a database name, or a field name in
MySQL?

Database name: 64 characters

Table name: 64 characters

Column name: 64 characters

What is maximum size of a database in mysql?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 Limit

Linux 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

normalization
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 Form

The 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 Form

Where 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

VARCHAR vs CHAR vs TEXT


CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if you
enter less than n characters to that column. For example, "Hello!" will be stored as
"Hello! " in CHAR(10) column.
VARCHAR is a variable length data type. VARCHAR(n) will take only the required
storage for the actual number of characters entered to that column. For example, "Hello!"
will be stored as "Hello!" in VARCHAR(10) column.
Aggregate functions
GROUP BY vs ORDER BY
To sort a result, use an ORDER BY clause.
The most general way to satisfy a GROUP BY clause is to scan the whole table and
create a new temporary table where all rows from each group are consecutive, and then
use this temporary table to discover groups and apply aggregate functions (if any).

ORDER BY [col1],[col2],...[coln]; Tells 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]; Tells DBMS to group (aggregate) 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.
JOIN
DROP vs TRUNCATE
DROP TABLE table_name - This will delete the table and its data.
TRUNCATE TABLE table_name - This will delete the data of the table, but not the table
definition.
REPAIR
The syntex for repairing a mysql table is:

REPAIR TABLE tablename

REPAIR TABLE tablename QUICK

REPAIR TABLE tablename EXTENDED

This command will repair the table specified.


If QUICK is given, MySQL will do a repair of only the index tree.
If EXTENDED is given, it will create index row by row.

MYSQL engine architecture.


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))?

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. When you fire the above
create query MySQL will create a MyISAM table.

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,

PHPMyadmin
PHP interface to MYSQL
We can create MySQL database with the use of mysql_create_db($databaseName) to
create a database.
If you want to create a table, you can run the CREATE TABLE statement as shown in the
following sample script:

<?php

include "mysql_connection.php";

$sql = "CREATE TABLE fyi_links ("

. " id INTEGER NOT NULL"

. ", url VARCHAR(80) NOT NULL"

. ", notes VARCHAR(1024)"

. ", counts INTEGER"

. ", time TIMESTAMP DEFAULT sysdate()"

. ")";

if (mysql_query($sql, $con)) {

print("Table fyi_links created.\n");

} else {

print("Table creation failed.\n");

}
mysql_close($con);

?>

Remember that mysql_query() returns TRUE/FALSE on CREATE statements. If you run


this script, you will get something like this:
Table fyi_links created.

mysql_fetch methods
MySQL fetch object will collect first single matching record where mysql_fetch_array
will collect all matching records from the table in an array
.
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.).
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.

mysql_fetch_assoc - Fetch a result row as an associative array


SESSIONS
A session is a logical object created by the PHP engine to allow you to preserve data
across subsequent HTTP requests.

There is only one session object available to your PHP scripts at any time. Data saved to the
session by a script can be retrieved by the same script or another script when
requested from the same visitor.
Sessions are commonly used to store temporary data to allow multiple PHP pages to offer
a complete functional transaction for the same visitor.

unlink() is a function for file system handling. It will simply delete the file in context.

unset() is a function for variable management. It will make a variable undefined.

register the variables into a session?

session_register($session_var);

$_SESSION['var'] = 'value';

session_unregister() - Unregister a global variable from the current session

session_unset() - Free all session variables


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.
The session support can be turned on automatically at the site level, or manually in each
PHP page script:

Turning on session support automatically at the site level: Set session.auto_start =

1 in php.ini.

Turning on session support manually in each page script: Call session_start()

funtion.

COKKIES
Persistent Cookie
A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's
computer. By default, cookies are created as temporary cookies which stored only in the
browser's memory. When the browser is closed, temporary cookies will be erased. You should
decide when to use temporary cookies and when to use persistent cookies based on their
differences:

 Temporary cookies can not be used for tracking long-term information.

 Persistent cookies can be used for tracking long-term information.


 Temporary cookies are safer because no programs other than the browser can
access them.

 Persistent cookies are less secure because users can open cookie files see the
cookie values
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');

REDIRECTTION from one page to another


Here are the possible ways of php page redirection.

1. Using Java script:

'; echo 'window.location.href="'.$filename.'";'; echo ''; echo ''; echo ''; echo ''; } }

redirect('http://maosjb.com'); ?>

2. Using php function: header("Location:http://maosjb.com ");

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

What type of headers have to be added in the mail function to attach a file?

$boundary = '--' . md5( uniqid ( rand() ) );

$headers = "From: \"Me\"\n";

$headers .= "MIME-Version: 1.0\n";

$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"";

PHP. ini file


PHP INI Settings
Setting up the extensions
To set up the extensions point PHP to the directory that holds the extension libraries and you
need to uncomment the desired extensions.
Point PHP to the correct directory:
Set extension_dir in php.ini to "C:\PHP\ext" (extension_dir = "C:\PHP\ext")
Uncomment the ones you want to use.
It’s important to be sure that php_mysql.dll extension is uncommented (for PHP 5 or
newer).
Extensions
extension=php_gd2.dll
extension=php_mssql.dll
extension=php_mysql.dll
File Uploading
file_uploads = On ;If you want users to be able to upload files using PHP
scripts.
upload_tmp_dir = "C:\TEMP" ;Path must be in a folder writeable from all websites.
upload_max_filesize = 32M ;Max file size that can be uploaded.
Other Settings
short_open_tag
This is on by default, but using short tags (<?) is bad form. Turn it off and don’t utilize it. (Edit)
There are two reasons for this. First, and the more rare reason, is that it could create problems
with XML parsing. If you ever have the need to embed PHP in XML (as I did once), you may
run into this. This is rare, but possibe. Second, and more common, is that if you ever change
hosts, or start using a host that configures PHP for you, they may disable the short tags by
default. This could leave you scrambling for a fix for your code. Changing 20,000 <? into <?
php can take a long time (I’ve done it; it can be a pain).
register_globals
The register_globals setting controls how you access form, server, and environment variables.
By default this variable is set to Off, requiring you to use special arrays to access these
variables. Those familiar with older versions of PHP will be used to an environment in which
the register_globals variable is effectively On; with this setting, you can access form, server and
environment variables simply by name.
display_errors and display_startup_errors
These two settings control whether PHP should display errors in the browser or be silent. It is
recommended that you turn these two settings Off during production so that you don't
accidentally display sensitive information about your Web site. This is especially true for
dynamic Web sites that send user names and passwords to access a database.
special set of tags do in PHP. What does a special set of tags <?= and ?> do in PHP?
The output is displayed directly to the browser.
Errors in PHP
Here are three basic types of runtime errors in PHP:
1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script -
for example, accessing a variable that has not yet been defined. By default, such errors are not
displayed to the user at all - although you can change this default 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.
Internally, these variations are represented by twelve different error types
Encryption in PHP
urlencode() returns the URL encoded version of the given string. URL coding converts special
characters into % signs followed by two hex digits. For example:
urlencode("10.00%") will return "10%2E00%25". URL encoded strings are safe to be used as
part of URLs. urldecode() returns the URL decoded version of the given string.
Anwser 2:

string urlencode(str) - Returns the URL encoded version of the input string. String values to be
used in URL query string need to be URL encoded. In the URL encoded version: Alphanumeric
characters are maintained as is.Space characters are converted to "+" characters.
Other non-alphanumeric characters are converted "%" followed by two hex digits representing
the converted character.
string urldecode(str) - Returns the original string of the input URL encoded string.
For example:

$discount ="10.00%";

$url = "http://domain.com/submit.php?disc=".urlencode($discount);

echo $url;

You will get "http://domain.com/submit.php?disc=10%2E00%25".

Answer1

You can encrypt a password with the following Mysql>SET

PASSWORD=PASSWORD("Password");

Answer2

You can use the MySQL PASSWORD() function to encrypt username and password. For

example,

INSERT into user (password, ...) VALUES (PASSWORD($password”)), ...);

How To Protect Special Characters in Query String?

If you want to include special characters like spaces in the query string, you need to

protect them by applying the urlencode() translation function. The script below shows

how to use urlencode():


<?php

print("<html>");

print("<p>Please click the links below"

." to submit comments about FYICenter.com:</p>");

$comment = 'I want to say: "It\'s a good site! :->"';

$comment = urlencode($comment);

print("<p>"

."<a href=\"processing_forms.php?name=Guest&comment=$comment\">"

."It's an excellent site!</a></p>");

$comment = 'This visitor said: "It\'s an average site! :-("';

$comment = urlencode($comment);

print("<p>"

.'<a href="processing_forms.php?'.$comment.'">'

."It's an average site.</a></p>");

print("</html>");
?>

AES_ENCRYPT() and AES_DECRYPT()


AES_ENCRYPT(str, key_str)

AES_DECRYPT(crypt_str, key_str)

CRYPT()

MD5()

OOP concepts in PHP


Class
A class is user defined data type that contains attributes or data members; and methods which
work on the data members. To create a class, you need to use the keyword class followed by the
name of the class. The name of the class should be meaningful to exist within the system .The
body of the class is placed between two curly brackets within which you declare class data
members/variables and class methods.
class Customer
{
private $first_name, $last_name;
public function setData($first_name, $last_name)
{ $this->first_name = $first_name;
$this->last_name = $last_name;
}
public function printData()
{ echo $this->first_name . " : " . $this->last_name;
}
}
Definition of an Object
An object is a living instance of a class. This means that an object is created from the definition
of the class and is loaded in memory.
Creating Objects in PHP5 Class
To create an object of a PHP5 class we use the keyword new. Below is the syntax style of how
to create objects in PHP5:
$obj_name = new ClassName();
In the above syntax style, $obj_name is a variable in PHP. ‘new’ is the keyword which is
responsible for creating a new instance of ClassName.
class Customer
{
private $first_name, $last_name;
public function getData($first_name, $last_name)
{ $this->first_name = $first_name;
$this->last_name = $last_name;
}
public function printData()
{ echo $this->first_name . " : " . $this->last_name;
}
}
$c1 = new Customer();
$c2 = new Customer();
In the above example $c1 and $c2 are two objects of the Customer Class. Both these objects are
allocated different blocks in the memory. Look at the diagram below:
Therefore, an object is a living instance of a class. Each object / living instance has its own
memory space that can hold independent data values.
Definition of an class attribute
An attribute is also know as data members and is used to hold data of a class. The data that it
holds are specific to the nature of the class in which it has been defined. For example, a
Customer class would hold data related to a customer, an Order class would hold data related a
an order.
Defining an attribute is as easy as declaring a variable within the body of the class. At the time
of declaring a data member/variable within the body of the class, it is also possible to assign a
default value to the attribute or data member.
Attributes can either be public, private or protected - the default being public. These are called
Access Specifiers.
Access Specifiers
Access specifiers specify the level of access that the outside world (i.e. other class objects,
external functions and global level code) have on the class methods and class data members.
Access specifiers can either be public, private or protected. Access specifiers are used as a key
component of Encapsulation and Data Hiding. By using either of the access specifiers
mentioned above i.e. public, private or protected you can hide or show the internals of your
class to the outside world.
Private
A private access specifier is used to hide the data member or member function to the outside
world. This means that only the class that defines such data member and member functions have
access them. Look at the example below:
class Customer
{
private $name;
public function setName($name)
{ $this->name = $name;
}
public function getName()
{ return $this->name;
}
}
$c = new Customer();
$c->setName("Sunil Bhatia");
echo $c->name; //error, $name cannot be accessed from outside the class
//$name can only be accessed from within the class
echo $c->getName(); //this works, as the methods of the class have access
//to the private data members or methods
In the above example, echo $c->name will give you an error as $name in class Customer has
been declared private and hence only be accessed by its member functions internally. Therefore,
the following line echo $c->getName() will display the name.
Public
A public access specifier provides the least protection to the internal data members and member
functions. A public access specifier allows the outside world to access/modify the data members
directly unlike the private access specifier. Look at the example below:
class Customer
{
public $name;
public function setName($name)
{ $this->name = $name;
}
public function getName()
{ return $this->name;
}
}
$c = new Customer();
$c->setName("Sunil Bhatia");
echo $c->name; // this will work as it is public.
$c->name = "New Name" ; // this does not give an error.
In the above example, echo $c->name will work as it has been declared as public and hence can
be accessed by class member functions and the rest of the script.
Protected
A protected access specifier is mainly used with inheritance. A data member or member
function declared as protected will be accessed by its class and its base class but not from the
outside world (i.e. rest of the script). We can also say that a protected data member is public for
the class that declares it and it’s child class; but is private for the rest of the program (outside
world). Look at the example below:
class Customer
{ protected $name;
public function setName($name)
{ $this->name = $name;
}
public function getName()
{ return $this->name;
}
}
class DiscountCustomer extends Customer
{ private $discount;
public function setData($name, $discount)
{ $this->name = $name; //this is storing $name to the Customer
//class $name variable. This works
// as it is a protected variable
$this->discount = $discount;
}
}
$dc = new DiscountCustomer();
$dc->setData("Sunil Bhatia",10);
echo $dc->name; // this does not work as $name is protected and hence
// only available in Customer and DiscountCustomer class
In the above example, echo $dc->name will not work work $name has been defined as a
protected variable and hence it is only available in Customer and DiscountCustomer class.
Objects as Attributes
In addition to declaring attributes as intrinsic data types (int, string, etc), you can also declare
data members as objects of another class. This is called aggregation in Object Oriented Analysis
and Design (OOAD). Lets look at an example below:
class Customer
{
private $first_name, $last_name;
private $outstanding_amount = 0; //example of default value
public function getData($first_name, $last_name)
{ $this->first_name = $first_name;
$this->last_name = $last_name;
}
public function printData()
{ echo $this->first_name . " : " . $this->last_name;
}
}
class Order
{ private $order_id;
private $customer;
public setCust(Customer $c)
{ $this->customer = $c;
}
}
$c1 = new Customer();
$o1 = new Order();
$o1->setCust($c1); //storing $c1 object in $o1 order object
In the above example setCust() method accepts a Customer type of parameter which is stored
internally in the $customer data member.
The advantage of the above method is that it allows you to change the customer object
independently of the order object. Imagine having to add 3 - 4 new data members to the
Customer object. You only have to modify the Customer object without having the need to
modify the Order Object.
Definition of an class method
A class method/functions is the behavior/functionality of a class i.e. they provide the necessary
code for the class in which it is defined.
Methods act (perform operations) on the data members of the class and can be declared as
private or public. A class method is exactly similar to PHP functions, it’s just that class
functions are declared inside classes and accessed using the -> (arrow operator / dereferencing
operator).
Methods can also be declared as either public, protected or private.
class Customer
{ private $name;
public functionsetName($name)
{ $this->name = $name;
}
}
$c1 = new Customer();
$c1->setName("Sunil Bhatia");
In the above example setName() is the class method of the Customer class. The setName() class
method is responsible for accepting the name of the customer and storing it in the internal data
member i.e. $name.
The reason why you require methods is so that you can perform necessary validations on the
data passed. Let’s re-look at the above example with necessary validation code.
class Customer
{ private $name;
public function setName($name)
{ if(trim($name) != "")
{
$this->name = $name;
return true;
}
Else
{ return false;
}
}
}
$c1 = new Customer();
$c1->setName("Sunil Bhatia");
In the above example the setName() method accepts a customer’s name and validates to check
if $name is blank. If $name is blank the setName() function returns false; otherwise it stores the
$name in the $this->name of the class and returns true.
Need for a Constructor
It is needed as it provides an opportunity for doing necessary setup operations like initializing
class variables, opening database connections or socket connections, etc. In simple terms, it is
needed to setup the object before it can be used.
PHP5 Constructor
In PHP5 a constructor is defined by implementing the __construct() method. This naming style
has been introduced in PHP5. In PHP4, the name of the constructor was the same name as that
of the class. So, for example if you had a class Customer, you would have to implement a
function Customer().
PHP5 to be backward complaint also supports the PHP4 rule. When an object is created, PHP5
searches for __construct() first. If __construct() is not defined it then searches for a method with
the same that of the class. However, if you define both; PHP5 will first search for __construct()
method and execute it if available, otherwise it will execute the same class name function.
Constructor
class Customer
{ public function __construct() {
//code
}
}
Let’s look at a real example:
class Customer {
private $first_name;
private $last_name;
private $outstanding_amount;
public function __construct() {
$first_name = "";
$last_name = "";
$outstanding_amount = 0;
}
public function setData($first_name, $last_name, $outstanding_amount) {
$this->first_name = $first_name;
$this->last_name = $last_name;
$this->outstanding_amount = $outstanding_amount;
}
public function printData() {
echo "Name : " . $first_name . " " . $this->last_name . "\n";
echo "Outstanding Amount : " . $this->outstanding_amount . "\n";
}
}
$c1 = new Customer();
$c1->setData("Sunil","Bhatia",0);
In the above example on line number 26, we create a new object of the Customer class. the
‘new’ operator is responsible for creating the Customer class. At this point PHP5 searches the
Customer class to see if a constructor has been defined. Therefore, it calls the constructor
method i.e. __construct() defined starting from line no 7. The __construct() method sets the
$first_name and $last_name to blank and sets the $outstanding_amount to zero.
Parameterized Constructor or Argument Constructor
A parameterized or argument constructor is a constructor which accepts values in the form of
arguments in the constructor. Unlike other programming languages where overloaded argument
constructors is possible, in PHP5 you cannot overload constructors.
Example:
class Customer {
private $first_name;
private $last_name;
private $outstanding_amount;
public function __construct($first_name, $last_name, $outstanding_amount) {
$this->setData($first_name, $last_name, $outstanding_amount);
}
public function setData($first_name, $last_name, $outstanding_amount) {
$this->first_name = $first_name;
$this->last_name = $last_name;
$this->outstanding_amount = $outstanding_amount;
}
public function printData() {
echo "Name : " . $first_name . " " . $this->last_name . "\n";
echo "Outstanding Amount : " . $this->outstanding_amount . "\n";
}
}
$c1 = new Customer("Sunil","Bhatia",0);
In the above example on line number 24, we create a new object $c1 and pass values “Sunil”,
“Bhatia” and zero to the constructor defined on line number starting 7. The constructor now
takes 3 arguments and stores them in the internal private variable $first_name, $last_name and
$outstanding_amount respectively.
Inheritance
Inheritance is a mechanism where a new class is derived from the existing base class. The
derived class shares/inherit the functionality of the base class. To extend the class behavior
PHP5 have introduced a new keyword called “extends“.
<php
class parent1
{
protected $firstname = 11;
protected $lastname = 23;
}
class children extends parent1
{
function __construct()
{
echo $this->firstname;
echo $this->lastname;
}
}
$a = new children();
?>
1. Interfaces Abstract Classes
1. Abstract Classes
An abstract class is a class that is only partially implemented by the programmer. It may contain
one or more abstract methods. An abstract method is simply a function definition that serves to
tell the programmer that the method must be implemented in a child class.
To create an abstract class we use the code shown in Listing 1:
Listing 1: An Abstract PHP class
<?php
abstract class Weapon
{
private $SerialNumber;
abstract public function fire();
public function __construct($SerialNumber)
{
$this->SerialNumber = $SerialNumber;
}
public function getSerialNumber()
{
return $this->SerialNumber;
}
}
?>
The abstract class in Listing 1 contains some of the methods required for a weapon. The fire()
method however, cannot be implemented because each different weapons use different firing
different mechanisms. The method is therefore declared as abstract, meaning it will be
implemented in a more specific child class.
Because the class is abstract, an instance of it can never be created (remember, it is only a
partial implementation). Instead a child class must be created using inheritance and implement
the fire method in itself. Failure to do so will result in a fatal error. Listing 2 shows a child class
being created from the Abstract Weapon class.
Listing 2: Extending the Abstract Weapons class
<?php
class Gun extends Weapon
{
public function fire()
{
if($this->SafetyOff) {
return $this->CurrentBullet;
}
}
}
class Cannon extends Weapon
{
public function fire()
{
$this->NeedsLoading = true;
return $this->CurrentCanon;
}
?>
An instance of the Cannon and Gun classes can now be created because they now fully
implemented subclasses of weapon.
2. Interfaces
An interface is similar to an abstract class; indeed interfaces occupy the same namespace as
classes and abstract classes. For that reason, you cannot define an interface with the same name
as a class. An interface is a fully abstract class; none of its methods are implemented and instead
of a class sub-classing from it, it is said to implement that interface.
An interface will be used in the database abstraction layer you create. This ensures that every
time you create a class for a particular database, the same API is exposed. When using an
interface, you can then rely on the methods defined for the interface to be part of the class
because, if they are not, PHP will not parse it.
The MySql functions will be used as an example because they are the most commonly used
amongst PHP programmers. The most commonly used functions are:
 mysql_connect()
 mysql_error()
 mysql_errno()
 mysql_query()
 mysql_fetch_array()
 mysql_fetch_row()
 mysql_fetch_assoc()
 mysql_fetch_object()
 mysql_num_rows()
 mysql_close()
If all the database class APIs you create can expose the same methods with the same return
types then you can be sure that changing from one database to another, such as from MySql to
Postgre SQL, will be painless. As such, the interface in listing 3 can be determined for your
API.
Listing 3: An Abstracted Database Interface
interface DB
{
public function connect();
public function error();
public function errno();
public static function escape_string($string);
public function query($query);
public function fetch_array($result);
public function fetch_row($result);
public function fetch_assoc($result);
public function fetch_object($result);
public function num_rows($result);
public function close();
}

Any class implementing the interface must define each method that is declared in the interface,
and each method must have at least the parameters identified in their interface definitions. It
may have more parameters as long as they are optional, but it cannot have less
PolyMorphism
Definition: polymorphism describes multiple possible states for a single property .
<?php

class animal {
public $name;
protected function setName($name){
$this->name = $name;
}
public function speak(){
return "No Animal Selected!";
}
}
class dog extends animal {
public function __construct($name){
$this->setName($name);
}
public function speak(){
return "Woof Woof";
}
}
class cat extends animal {
public function __construct($name){
$this->setName($name);
}
public function speak(){
return "I'm In your class, overloading your methods"; // :)
}
}
class human extends animal {
public function __construct($name){
$this->setName($name);
}
public function speak(){
return "Hello, My Name is " . $this->name;
}
}
$animal = new animal(); // Animal
$dog = new dog('rover'); // Dog named Rover
$cat = new cat('garfield'); // Cat named Garfield
$human = new human('fred'); // Human named Fred
// Non-existent animal cannot speak
echo $animal->speak();
// Dog's bark
echo $dog->speak();
// Cat's do nefarious things
echo $cat->speak();
// Human's Introduce themselves
echo $human->speak();
Features and advantages of OBJECT ORIENTED PROGRAMMING?
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.
Abstract class vs interfaces
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.
polymorphism
Inheritance
What type of inheritance that php supports?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'.

access specifiers
scope resolution operator
include vs require vs include_once
Anwser 1:

require_once() and include_once() are both the functions to include and evaluate the
specified file only once. If the specified file is included previous to the present call
occurrence, it will not be done again.
But require() and include() will do it as many times they are asked to do.

Anwser 2:

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. The major difference between include() and require() is that in failure
include() produces a warning message whereas require() produces a fatal errors.

Anwser 3:

All three are used to an include file into the current page.
If the file is not present, require(), calls a fatal error, while in include() does not.
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. It des not call a fatal error if file not exists. require_once() does the same

as include_once(), but it calls a fatal error if file not exists.


Anwser 4:

File will not be included more than once. If we want to include a file once only and
further calling of the file will be ignored then we have to use the PHP function
include_once(). This will prevent problems with function redefinitions, variable value

reassignments, etc.
It’s how they handle failures. If the file is not found by require(), it will cause a fatal error
and halt the execution of the script. If the file is not found by include(), a warning will be
issued, but execution will continue.

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

AJAX
Javascript
No. There is no way to send emails directly using JavaScript.
But you can use JavaScript to execute a client side email program send the email using
the "mailto" code. Here is an example:

function myfunction(form)

tdata=document.myform.tbox1.value;

location="mailto:mailid@domain.com?subject=...";

return true;
}

CSS
What are the advantages and disadvantages of CASCADE STYLE SHEETS?

External Style Sheets

Advantages

Can 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 contexts

Disadvantages

An 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 definitions

Embedded 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

Disadvantage

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

XML
JOOMLA
CuteFTP
CMS
Functions
nI2br(string)
Anwser1:

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

echo nl2br("god bless \n you");

output:

god bless<br>
you

strstr(str,str);
string strstr ( string haystack, string needle ) returns part of haystack string from the first
occurrence of needle to the end of haystack. This function is case-sensitive.
strstr() returns part of a given string from the first occurrence of a given substring to the

end of the string. For example: strstr("user@example.com","@") will return

"@example.com".

stristr() is idential to strstr() except that it is case insensitive.

split
explode
preg_match(pattern,str)
We can use the preg_match() function with "/.*@(.*)$/" as

the regular expression pattern. For example:

preg_match("/.*@(.*)$/","http://info@abc.com",$data);

echo $data[1];

extract string "abc.com" from a string

"mailto:info@abc.com?subject=Feedback" using regular expression of PHP?

$text = "mailto:info@abc.com?subject=Feedback";

preg_match('|.*@([^?]*)|', $text, $output);


echo $output[1];
Note that the second index of $output, $output[1], gives the match, not the first one,

$output[0].

md5,crc32(),shat()
Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off, depending on the
data that you’re encrypting, you might have reasons to store a 32-bit value in the database
instead of the 160-bit value to save on space. Second, the more secure the crypto is, the
longer is the computation time to deliver the hash value. A high volume site might be
significantly slowed down, if frequent md5() generation is required.
The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits,

while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important
when avoiding collisions.

eregi_replace() function is identical to ereg_replace() except that it ignores case


distinction when matching alphabetic characters.

func_num_args() function returns the number of parameters passed in.


__sleep returns the array of all the variables than need to be saved, while __wakeup

retrieves them.

On large strings that need to be formatted according to some length specifications, use

wordwrap() or chunk_split().

$formatted = ucwords("FYICENTER IS COLLECTION OF INTERVIEW


QUESTIONS");

print $formatted;

What will be printed is FYICENTER IS COLLECTION OF INTERVIEW QUESTIONS.

ucwords() makes every first letter of every word capital, but it does not lower-case

anything else. To avoid this, and get a properly formatted string, it’s worth using

strtolower() first.

htmlspecialchars only takes care of <, >, single quote ‘, double quote " and ampersand.

htmlentities translates all occurrences of character sequences that have different meaning

in HTML.

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

widely used)

htmlentities() - Convert ALL special characters to HTML entities


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.

a) sizeof($array) - This function is an alias of count()


b) count($urarray) - This function returns the number of elements in an array.

Interestingly if you just pass a simple var instead of an array, count() will return 1.

Give the syntax of GRANT commands?

The generic syntax for GRANT is as following


GRANT [rights] on [database] TO [username@hostname] IDENTIFIED BY [password]

Now rights can be:

a) ALL privilages

b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.

We can grant rights on all databse by usingh *.* or some specific database by database.*
or a specific table by database.table_name.

Give the syntax of REVOKE commands?

The generic syntax for revoke is as following

REVOKE [rights] on [database] FROM [username@hostname]

Now rights can be:

a) ALL privilages

b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.


We can grant rights on all databse by usingh *.* or some specific database by database.*

or a specific table by database.table_name.

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!

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

Friend functions

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.

class mylinkage

private:

mylinkage * prev;

mylinkage * next;

protected:

friend void set_prev(mylinkage* L, mylinkage* N);

void set_next(mylinkage* L);

public:

mylinkage * succ();

mylinkage * pred();

mylinkage();

};
void mylinkage::set_next(mylinkage* L) { next = L; }

void set_prev(mylinkage * L, mylinkage * N ) { N->prev = L; }

Friends in other classes

It is possible to specify a member function of another class as a friend as follows:

class C

friend int B::f1();

};

class B

int f1();

};

It is also possible to specify all the functions in another class as friends, by specifying the
entire class as a friend.

class A

{
friend class B;

};

Friend functions allow binary operators to be defined which combine private data in a
pair of objects. This is particularly powerful when using the operator overloading features
of C++. We will return to it when we look at overloading.

What are the advantages of stored procedures, triggers, indexes?

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.

How can increase the performance of MySQL select query?


We can use LIMIT to stop MySql for further search in table after we have received our
required no. of records, also we can use LEFT JOIN or RIGHT JOIN instead of full join
in cases we have related data in two or more tables.

How can we change the name of a column of a table?

MySQL query to rename table: RENAME TABLE tbl_name TO new_tbl_name


or,

ALTER TABLE tableName CHANGE OldName newName.

How can increase the performance of MySQL select query?

We can use LIMIT to stop MySql for further search in table after we have received our
required no. of records, also we can use LEFT JOIN or RIGHT JOIN instead of full join
in cases we have related data in two or more tables.

How can we change the name of a column of a table?

MySQL query to rename table: RENAME TABLE tbl_name TO new_tbl_name

or,

ALTER TABLE tableName CHANGE OldName newName.

When you want to show some part of a text displayed on an HTML page in red font

color? What different possibilities are there to do this? What are the

advantages/disadvantages of these methods?


There are 2 ways to show some part of a text in red:

1. Using HTML tag <font color="red">

2. Using HTML tag <span style="color: red">

When viewing an HTML page in a Browser, the Browser often keeps this page in its
cache. What can be possible advantages/disadvantages of page caching? How can
you prevent caching of a certain page (please give several alternate solutions)?

When you use the metatag in the header section at the beginning of an HTML Web page,
the Web page may still be cached in the Temporary Internet Files folder.
A page that Internet Explorer is browsing is not cached until half of the 64 KB buffer is

filled. Usually, metatags are inserted in the header section of an HTML document, which
appears at the beginning of the document. When the HTML code is parsed, it is read from
top to bottom. When the metatag is read, Internet Explorer looks for the existence of the
page in cache at that exact moment. If it is there, it is removed. To properly prevent the
Web page from appearing in the cache, place another header section at the end of the
HTML document. For example:

What are the different ways to login to a remote server? Explain the means,

advantages and disadvantages?

There is at least 3 ways to logon to a remote server:

Use ssh or telnet if you concern with security

You can also use rlogin to logon to a remote server.


Please give a regular expression (preferably Perl/PREG style), which can be used to
identify the URL from within a HTML link tag.

Try this: /href="([^"]*)"/i

How can I use the COM components in php?

The COM class provides a framework to integrate (D)COM components into your PHP scripts.

string COM::COM( string module_name [, string server_name [, int codepage]]) - COM

class constructor.

Parameters:

module_name: name or class-id of the requested component.

server_name: name of the DCOM server from which the component should be fetched. If

NULL, localhost is assumed. To allow DCOM com, allow_dcom has to be set to TRUE

in php.ini.

codepage - specifies the codepage that is used to convert php-strings to unicode-strings

and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL,

CP_THREAD_ACP, CP_UTF7 and CP_UTF8.

Usage:
$word->Visible = 1; //open an empty document

$word->Documents->Add(); //do some weird stuff

$word->Selection->TypeText("This is a test…");

$word->Documents[1]->SaveAs("Useless test.doc"); //closing word

$word->Quit(); //free the object

$word->Release();

$word = null;

What changes I have to do in php.ini file for file uploading?

Make the following line uncomment like:

; Whether to allow HTTP file uploads.

file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not

; specified).

upload_tmp_dir = C:\apache2triad\temp

; Maximum allowed size for uploaded files.


upload_max_filesize = 2M

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

Cron is very simply a Linux module that allows you to run commands at predetermined
times or intervals. In Windows, it's called Scheduled Tasks. The name Cron is in fact
derived from the same word from which we get the word chronology, which means order
of time.

The easiest way to use crontab is via the crontab command.

# crontab

This command 'edits' the crontab. Upon employing this command, you will be able to
enter the commands that you wish to run. My version of
Linux uses the text editor vi. You can find information on using vi here.
The syntax of this file is very important – if you get it wrong, your crontab will not
function properly. The syntax of the file should be as follows:

minutes hours day_of_month month day_of_week command

All the variables, with the exception of the command itself, are numerical constants. In
addition to an asterisk (*), which is a wildcard that allows any value, the ranges permitted
for each field are as follows:

Minutes: 0-59

Hours: 0-23

Day_of_month: 1-31
Month: 1-12

Weekday: 0-6

We can also include multiple values for each entry, simply by separating each value with
a comma.
command can be any shell command and, as we will see momentarily, can also be used to
execute a Web document such as a PHP file.
So, if we want to run a script every Tuesday morning at 8:15 AM, our mycronjob file will
contain the following content on a single line:

15 8 * * 2 /path/to/scriptname

This all seems simple enough, right? Not so fast! If you try to run a PHP script in this
manner, nothing will happen (barring very special configurations that have PHP compiled
as an executable, as opposed to an Apache module). The reason is that, in order for PHP
to be parsed, it needs to be passed through Apache. In other words, the page needs to be
called via a browser or other means of retrieving
Web content. For our purposes, I'll assume that your server configuration includes wget,
as is the case with most default configurations. To test your configuration, log in to shell.
If you're using an RPM-based system (e.g. Redhat or Mandrake), type the following:

# wget help

If you are greeted with a wget package identification, it is installed in your system.
You could execute the PHP by invoking wget on the URL to the page, like so:

# wget http://www.example.com/file.php

Now, let's go back to the mailstock.php file we created in the first part of this article. We
saved it in our document root, so it should be accessible via the Internet. Remember that
we wanted it to run at 4PM Eastern time, and send you your precious closing bell report?

Since I'm located in the Eastern timezone, we can go ahead and set up our crontab to use
4:00, but if you live elsewhere, you might have to compensate for the time difference
when setting this value.

This is what my crontab will look like:


0 4 * * 1,2,3,4,5 wget http://www.example.com/mailstock.php

Steps for the payment gateway processing?

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

What is the difference between Reply-to and Return-path in the headers of a mail
function?

Reply-to: Reply-to is where to delivery the reply of the mail.

Return-path: Return path is when there is a mail delivery failure occurs then where to

delivery the failure notification.

Explain about Type Juggling in php?

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

$foo += 2; // $foo is now an integer (2)

$foo = $foo + 1.3; // $foo is now a float (3.3)

$foo = 5 + "10 Little Piggies"; // $foo is integer (15)

$foo = 5 + "10 Small Pigs"; // $foo is integer (15)

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

Note: The behavior of an automatic conversion to array is currently undefined.


Since PHP (for historical reasons) supports indexing into strings via offsets using the
same syntax as array indexing, the example above leads to a problem: should $a become
an array with its first element being "f", or should "f" become the first character of the
string $a? The current versions of PHP interpret the second assignment as a string offset
identification, so $a becomes "f", the result of this automatic conversion however should
be considered undefined. PHP 4 introduced the new curly bracket syntax to access
characters in string, use this syntax instead of the one presented above:

How can I embed a java programme in php file and what changes have to be done
in php.ini file?

There are two possible ways to bridge PHP and Java: you can either integrate PHP into a
Java Servlet environment, which is the more stable and efficient solution, or integrate
Java support into PHP. The former is provided by a SAPI module that interfaces with the
Servlet server, the latter by this Java extension.

The Java extension provides a simple and effective means for creating and invoking
methods on Java objects from PHP. The JVM is created using JNI, and everything runs
in-process.

Example Code:

getProperty('java.version') . ''; echo 'Java vendor=' . $system->getProperty('java.vendor') .

''; echo 'OS=' . $system->getProperty('os.name') . ' ' . $system->getProperty('os.version') .

' on ' . $system->getProperty('os.arch') . ' '; // java.util.Date example $formatter = new

Java('java.text.SimpleDateFormat', "EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz"); echo

$formatter->format(new Java('java.util.Date')); ?>

The behaviour of these functions is affected by settings in php.ini.

Table 1. Java configuration options

Name

Default
Changeable

java.class.path

NULL

PHP_INI_ALL

Name Default Changeable

java.home

NULL

PHP_INI_ALL

java.library.path

NULL

PHP_INI_ALL

java.library

JAVALIB

PHP_INI_ALL

How To Read the Entire File into a Single String?

If you have a file, and you want to read the entire file into a single string, you can use the
file_get_contents() function. It opens the specified file, reads all characters in the file, and
returns them in a single string. Here is a PHP script example on how to

file_get_contents():

<?php

$file = file_get_contents("/windows/system32/drivers/etc/services");

print("Size of the file: ".strlen($file)."\n");

?>

This script will print:

Size of the file: 7116

Вам также может понравиться