0% found this document useful (0 votes)
4 views

PHP

The document provides an introduction to PHP, a server-side scripting language used for web development, detailing its capabilities, limitations of static HTML, and various programming concepts such as variables, constants, data types, and control structures. It explains how PHP can create dynamic and interactive websites and includes examples of syntax and operators. Additionally, it covers arrays, functions, and string manipulation, making it a comprehensive guide for PHP programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

PHP

The document provides an introduction to PHP, a server-side scripting language used for web development, detailing its capabilities, limitations of static HTML, and various programming concepts such as variables, constants, data types, and control structures. It explains how PHP can create dynamic and interactive websites and includes examples of syntax and operators. Additionally, it covers arrays, functions, and string manipulation, making it a comprehensive guide for PHP programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

PHP

CONTENTS

1. Introduction 121

2. Control Structures 126

3. Arrays 127

4. Functions 129

5. Forms 134
An ISO 9001 : 2000 Recognised Institution

INTRODUCTION TO PHP
PHP is the Web development language written by and for Web developers. It stands for Hypertext Preprocessor.
The product was originally named Personal Home Page Tools.
PHP is a server-side scripting language, which can be embedded in HTML for creating dynamic and interactive
websites. Other server-side programming languages are Microsoft’s Active Server Pages, Macromedia’s Cold
Fusion, and Sun’s Java Server Pages.

LIMITATIONS FOR STATIC HTML


• It makes control of design and layout difficult.
• It doesn’t scale up to a large number of pages.
• It’s not very interactive.
• It can’t cope with rapidly changing content or personalization.

SERVER-SIDE SCRIPTING
Server-side scripting products consist of two main parts: the scripting language and the scripting engine (which
may or may not be built into the Web server). The engine parses and interprets pages written in the language.
Often, the same company or team develops both parts for use only with each other—PHP3and ColdFusion are
both examples of this practice.
PHP perfectly serve most of the truly useful aspects of the Web, as such as the items in this list:
· Content sites (both production and display)
· Community features (forums, bulletin boards, and so on)
· E-mail (Web mail, mail forwarding, and sending mail from a Web application)
· Customer-support and technical-support systems
· Advertising networks
· Web-delivered business applications
· Directories and membership rolls
· Surveys, polls, and tests
· Filling out and submitting forms online
· Personalization technologies
· Catalog, brochure, and informational sites
· Any other application that needs to connect a backend server (database)

VARIABLES
The main way to store information in the middle of a PHP program is by using a variable. Variable names must be
composed of letters (uppercase or lowercase), digits (0–9), and underscore characters (_). Furthermore, the first
character after the $ may not be a number. Below are the most important things about variables in PHP
· All variables in PHP are denoted with a leading dollar sign ($).
· The value of a variable is the value of its most recent assignment.
· Variables are assigned with the = operator, with the variable on the left-hand side and the expression to
be evaluated on the right.
· Variables can, but do not need, to be declared before assignment.
· Variables used before they are assigned have default values.

PHP 121
An ISO 9001 : 2000 Recognised Institution

CONSTANTS
PHP offers constants, which have a single value throughout their lifetime. Constants do not have a $ before their
names, and by convention the names of constants usually are in uppercase letters. Constants can contain only
scalar values (numbers and string). Constants have global scope, so they are accessible everywhere in your
scripts after they have been defined—even inside functions.
define(PI, 3.14); to create constants.

DATA TYPES
PHP has a total of eight types: integers, doubles, Booleans, strings, arrays, objects, NULL, and resources.
Simple Types:
1. Integers are whole numbers, without a decimal point, like 495.
2. Doubles are floating-point numbers, like 3.14159 or 49.0.
3. Booleans have only two possible values: TRUE and FALSE.
4. NULL is a special type that only has one value: NULL.
5. Strings are sequences of characters, like ‘name’

Compound Types:
1. Arrays are named and indexed collections of other values.
2. Objects are instances of programmer-defined classes, which can package up both other kinds of values
and functions that are specific to the class.
3. Resources are special variables that hold references to resources external to PHP (such as database
connections).

INTERPRETING OTHER TYPES AS BOOLEANS


Here are the rules for determining the “truth” of any value not already of the Boolean type:
· If the value is a number, it is false if exactly equal to zero and true otherwise.
· If the value is a string, it is false if the string is empty (has zero characters) or is the string “0”, and is true
otherwise.
· Values of type NULL are always false.
· If the value is a compound type (an array or an object), it is false if it contains no other values, and it is
true otherwise. For an object, containing a value means having a member variable that has been assigned
a value.
NULL
A variable that has been assigned NULL has the following properties:
· It evaluates to FALSE in a Boolean context.
· It returns FALSE when tested with isset().
PHP will not print warnings if you pass the variable to functions and back again, whereas passing a variable that
has never been set will sometimes produce warnings.

PHP 122
An ISO 9001 : 2000 Recognised Institution

STRINGS
Strings are character sequences, as in the following:
$string_1 = “This is a string in double quotes.”;
$string_2 = ‘singly quoted string’;
Strings can be enclosed in either single or double quotation marks, with different behavior at read time. Singly
quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as
well as specially interpreting certain character sequences. The escape-sequence replacements:
· \n is replaced by the new line character
· \r is replaced by the carriage-return character
· \t is replaced by the tab character
· \$ is replaced by the dollar sign itself ($)
· \” is replaced by a single double-quote (“)
· \\ is replaced by a single backslash (\)

VARIABLE INTERPOLATION
Whenever an unescaped $ symbol appears in a doubly quoted string, PHP tries to interpret what follows as a
variable name and splices the current value of that variable into the string. Exactly what kind of substitution
occurs depends on how the variable is set:
· If the variable is currently set to a string value, that string is interpolated (or spliced) into the doubly
quoted string.
· If the variable is currently set to a non string value, the value is converted to a string, and then that string
value is interpolated.
· If the variable is not currently set, PHP interpolates nothing.
echo and print
The two most basic constructs for printing to output are echo and print. Their language status is somewhat
confusing, because they are basic constructs of the PHP language, rather than being functions. As a result, they
can be used either with parentheses or without them. (Function calls always have the name of the function first,
followed by a parenthesized list of the arguments to the function.). The simplest use of echo is to print a string as
argument.
The command print is very similar to echo, with two important differences:
· Unlike echo, print can accept only one argument.
· Unlike echo, print returns a value, which represents whether the print statement succeeded.
The value returned by print will be 1 if the printing was successful and 0 if unsuccessful .
Example:
<?php
$int_var = 2147;
print (“Integer Value “.$int_var.”<br>”);
$double_var = 2.147;
print (“double Value “.$double_var.”<br>”);

PHP 123
An ISO 9001 : 2000 Recognised Institution

$double_even = 2.0;
$tot = $double_even + 3 ;
print (“total = “.$tot.”<br>”);

$double_one = 2.565656;
$double_two = 3.788888;
$tot = $double_one + $double_two;
print($double_one.”+”.$double_two.”=”.$tot.”<br>”);
$double_three = 2.3e+16;
print($double_three);
$true_num=12.3;
$true_str =”name”;
$false_null=NULL;
$false_num=0;
$false_str=””;

$string_1 = “This is a string in double quotes. $tot”;


$string_2 = ‘This is a some what longer, singly quoted string $tot’;

print ($string_1.”<br>”);
print ($string_2.”<br>”);
?>

ARITHMETIC OPERATORS
Operator Behavior Examples
+ Sum of its two arguments. 4 + 9.5 evaluates to 13.5
– If there are two arguments, the right-hand argument 50 - 75 evaluates to -25
is subtracted from the left-hand argument. If there - 3.9 evaluates to -3.9
is just a right-hand argument, then the negative of
that argument is returned.
* Product of its two arguments. 3.14 * 2 evaluates to 6.28
/ Floating-point division of the left-hand argument by 5 / 2 evaluates to 2.5
the right-hand argument.
% Integer remainder from division of left-hand argument 101 % 50 evaluates to 1
by the absolute value of the right-hand argument. 999 % 3 evaluates to 0
43 % 94 evaluates to 43

PHP 124
An ISO 9001 : 2000 Recognised Institution

COMPARISON OPERATORS
Operator Name Behavior
== Equal True if its arguments are equal to each other, false otherwise
!= Not equal False if its arguments are equal to each other, true otherwise
< Less than True if the left-hand argument is less than its righthand argument,
but false otherwise
> Greater than True if the left-hand argument is greater than its right-hand
argument, but false otherwise
<= Less than or equal to True if the left-hand argument is less than its righthand argument or
equal to it, but false otherwise
>= Greater than or equal to True if the left-hand argument is greater than its righthand
argument or equal to it, but false otherwise
=== Identical True if its arguments are equal to each other and ofthe same type,
but false otherwise

INCREMENTING OPERATORS
The increment operator (++) adds one to the variable it is attached to, and the decrement operator (—) subtracts
one from the variable. Each one comes in two flavors, postincrement (which is placed immediately after the
affected variable), and preincrement (which comes immediately before). Both flavors have the same side effect of
changing the variable’s value, but they have different values as expressions. The postincrement operator acts as
if it changes the variable’s value after the expression’s value is returned, whereas the preincrement operator acts
as though it makes the change first and then returns the variable’s new value.

LOGICAL OPERATORS
Logical operators combine other logical (ie Boolean) values to produce new Boolean values. The standard logical
operations (and, or, not, and exclusive-or) are supported by PHP
Operator Behavior
and Is true if and only if both of its arguments are true.
or Is true if either (or both) of its arguments are true.
! Is true if its single argument (to the right) is false and false if its argument is true.
xor Is true if either (but not both) of its arguments are true.
&& Same as and, but binds to its arguments more tightly.
|| Same as or but binds to its arguments more tightly.

THE TERNARY OPERATOR


Used for three expressions and use the truth value of the first expression to decide which of the other two
expressions to evaluate and return.
syntax : test-expression ? yes-expression : no-expression

PHP 125
An ISO 9001 : 2000 Recognised Institution

CONTROL STRUCTURES
BRANCHING STATEMENTS
if (condition)
statement-1
else
statement-2

if (condition)
statement-1
elseif(condition)
statement-2
else
statement-3

switch(expression)
{
case value-1:
statement-1
statement-2
...
[break;]
case value-2:
statement-3
...
[break;]
...
[default:
default-statement] }
The expression can be a variable or any other kind of expression, as long as it evaluates to a simple value (that
is, an integer, a double, or a string).

LOOPING STRUCTURES
WHILE
while (condition)
statement

DO WHILE
do statement
while (expression);

FOR STATEMENT
for (initial-expression;termination-check;loop-end-expression)
statement

PHP 126
An ISO 9001 : 2000 Recognised Institution

ARRAYS
An array is a collection of variables indexed and bundled together into a single, easily referenced super-variable
that offers an easy way to pass multiple values between lines of code, functions, and even pages.
PHP arrays are associative arrays. The associative part means that arrays store element values in association
with key values rather than in a strict linear index order.
CREATING ARRAYS
1. $my_array [1] = “Array Example”
2. $subjects = array(‘physics’,’chemistry’,’maths’);
$subjects1 = array( 0 =>’physics’,1=>’maths’,2=>’chemistry’);
3. $my_array = range(1,5);
equivalent to $my_array = array(1, 2, 3, 4, 5);
two dimentional array:
$courses = array(‘languages’ =>
array(‘c’ => ‘C language’,
‘c++’ => ‘C++ language’,
‘java’ => ‘Java Language’),
‘dtp’ =>
array(‘pagemaker’ => ‘for text editing’,
‘photoshop’ => ‘photo editing’
)
);
ITERATION
To print all values in an array
foreach($subjects as $name)
print “$name<br>”;
To print individal values
reset($subjects);
$current_item = current($subjects);
print($current_item);
while( $current_item = next($subjects))
print “iteration: $current_item “;
To print reverse order
end($subjects);
$current_item = current($subjects);
print($current_item);
while( $current_item = prev($subjects))
print “iteration: $current_item “;

PHP 127
An ISO 9001 : 2000 Recognised Institution

Using each
reset($subjects);
while( $values = each($subjects))
{
$current_key = $values[‘key’];
$current_item = $values[‘value’];
print “<br>$current_key:$current_item”;
}
Array_walk
function print_value_length($array_value)
{
print (“<br>the $array_value length : “.strlen($array_value));
}
print “<br>”;
array_walk($subjects,’print_value_length’);

The current() function returns the stored value that the current pointer points to.
The next() function first advances that pointer and then returns the current value pointed to.
The reset() function gives us a way to “rewind” that pointer to the beginning—it sets the pointer to the first key/
value pair and then returns the stored value.
prev(), which moves the pointer back by one, and end(), which jumps the pointer to the last entry in the list.
key() function—this acts just like current() except that it returns the key of a key/value pair, rather than the value.

PHP 128
An ISO 9001 : 2000 Recognised Institution

FUNCTIONS
The basic syntax for using (or calling) a function is:
function_name(expression_1, expression_2, ..., expression_n).
This includes the name of the function followed by a parenthesized and comma-separated list of input expressions
(which are called the arguments to the function). Functions can be called with zero or more arguments, depending
on their definitions. When PHP encounters a function call, it first evaluates each argument expression and then
uses these values as inputs to the function. After the function executes, the returned value (if any) is the result of
the entire function expression. Ex: sqrt(10);
STRING FUNCTIONS
1. strlen () find string length; ex: strlen($str);
2. strpos () finds the numerical position of a particular character in a string, if it exists.
Ex: strpos($str,’e’);
3. strcmp() It takes two strings as arguments and compares them byte by byte until it finds a difference. It
returns a negative number if the first string is less than the second and a positive number if the second string is
less. It returns 0 if they are identical.
Ex: strcmp($str1,$str2);
4. The strstr() function takes a string to search in and a string to look for (in that order). If it succeeds, it returns
the portion of the string that starts with (and includes) the first instance of the string it is looking for. If the string
is not found, a false value is returned
Ex: strstr($string_to_search, $string_to_find);
5. substr() function, which returns a new string that is a subsequence of the old one. As arguments, it takes a
string (that the substring will be selected from), an integer (the position at which the desired substring starts),and
an optional third integer argument that is the length of the desired substring. If no third argument is given, the
substring is assumed to continue until the end.

MATH FUNCTIONS
Function Behavior
floor() Takes a single argument (typically a double) and returns the largest integer that is less than or
equal to that argument.
ceil() Short for ceiling—takes a single argument (typically a double) and returns the smallest integer
that is greater than or equal to that argument.
round() Takes a single argument (typically a double) and returns the nearest integer.If the fractional part
is exactly 0.5, it returns the nearest even number.
abs() Short for absolute value—if the single numerical argument is negative, the corresponding positive
number is returned; if the argument is positive, the argument itself is returned.
min() Takes any number of numerical arguments (but at least one) and returns the smallest of the
arguments.
max() Takes any number of numerical arguments (but at least one) and returns the largest of the
arguments.

PHP 129
An ISO 9001 : 2000 Recognised Institution

DATE AND TIME FUNCTIONS


checkdate()
boolean checkdate (int month, int day, int year)
ex: echo checkdate(03, 29, 2004);

The Date() Function Format Parameters


Parameter Description Example
a ante meridiem and post meridiem am or pm
A ante meridiem and post meridiem AM or PM
d Day of the month, with leading zero 01 to 31
D Three-letter text representation of day Mon through Sun
F Complete text representation of month January through December
G 12-hour format of hour, sans zeros 1 through 12
G 24-hour format, sans zeros 1 through 24
h 12-hour format of hour, with zeros 01 through 24
H 24-hour format, with zeros 01 through 24
i Minutes, with zeros 01 through 60
I Daylight saving time 0 if no, 1 if yes
j Day of month, sans zeros 1 through 31
l Text representation of day Monday through Sunday
L Leap year 0 if no, 1 if yes
m Numeric representation of month,with zeros 01 through 12
M Three-letter text representation of month Jan through Dec
n Numeric representation of month, sans zeros 1 through 12
O Difference to Greenwich Mean Time (GMT) –0500
r Date formatted according to RFC 2822 Tue, 19 Apr 2005 22:37:00 –0500
s Seconds, with zeros 01 through 59
S Ordinal suffix of day st, nd, rd, th
t Number of days in month 28 through 31
T Timezone setting of executing machine PST, MST, CST, EST, etc.
U Seconds since Unix epoch
w Numeric representation of weekday 0 for Sunday through 6 for Saturday
W ISO-8601 week number of year 1 through 53
Y Four-digit representation of year 1901 through 2038 (Unix);1970 through
2038 (Windows)
z The day of year 0 through 365
Z Timezone offset in seconds –43200 through 43200

PHP 130
An ISO 9001 : 2000 Recognised Institution

Example:
echo checkdate(02,29,1999);
print “Today is “.date(“F d, Y”);
print “Today is “.date(“l”);
$weekday = date(“l”);$daynumber = date(“dS”);$monthyear = date(“F Y”);
printf(“Today is %s the %s day of %s”, $weekday, $daynumber, $monthyear);
print “The time is “.date(“Oh:i:s”);
print “The time is “.date(“h:i:sa”);
$strdate = getdate();
print_r ($strdate);
print time();
print date(“F d, Y h:i:s”, time());
$time = gettimeofday();
$GMToffset = $time[‘minuteswest’] / 60;
echo “Server location is $GMToffset hours west of GMT.”;

Function definitions have the following form:


function function-name ($argument-1, $argument-2, ..)
{
statement-1;
statement-2;
...
}
That is, function definitions have four parts:
1.The special word function
2.The name that you want to give your function
3.The function’s parameter list—dollar-sign variables separated by commas
4.The function body—a brace-enclosed set of statements
Just as with variable names, the name of the function must be made up of letters, numbers, and underscores,
and it must not start with a number. Unlike variable names, function names are converted to lowercase before
they are stored internally by PHP, so a function is the same regardless of capitalization.
The short version of what happens when a user-defined function is called is:
1. PHP looks up the function by its name (you will get an error if the function has not yet been defined).
2. PHP substitutes the values of the calling arguments (or the actual parameters) into the variables in the
definition’s parameter list (or the formal parameters).
3. The statements in the body of the function are executed. If any of the executed statements are return statements,
the function stops and returns the given value. Otherwise, the function completes after the last statement is
executed, without returning a value.

PHP 131
An ISO 9001 : 2000 Recognised Institution

function declaration
function generate_footer() {
echo “<p>Copyright &copy; 2009 Apec</p>”;
}
function calling
<?php
generate_footer();
?>
PASSING ARGUMENTS BY VALUE
function salestax($price,$tax) {
$total = $price + ($price * $tax);
print “Total cost: $total”;
}
salestax(2.5,3,3);

PASSING ARGUMENTS BY REFERENCE


<?php
$cost = 20.00;
$tax = 0.05;
function calculate_cost(&$cost, $tax)
{
// Modify the $cost variable
Default Argument Values

function salestax($price,$tax=.0575) {
$total = $price + ($price * $tax);
echo “Total cost: $total”;
}
$price = 15.47;
salestax($price);

Optional Arguments
function salestax($price,$tax=””) {
$total = $price + ($price * $tax);
echo “Total cost: $total”;
}
salestax(42.00);

PHP 132
An ISO 9001 : 2000 Recognised Institution

RETURNING VALUES FROM A FUNCTION


The return() statement returns any ensuing value back to the function caller, returning program control back to the
caller’s scope in the process.
function salestax($price,$tax=.0575)
{
$total = $price + ($price * $tax);
return $total;
}
$total_amt = salestax(42.00);

Returning Multiple Values


The list() construct offers a convenient means for retrieving values from an array, like so:
<?php
function user_details() {
$user[] = “apec”;
$user[] = “[email protected]”;
$user[] = “English”;
return $user;
}
list($name,$email,$language) = user_details();
echo “Name: $name, email: $email, preferred language: $language”;
?>

PHP 133
An ISO 9001 : 2000 Recognised Institution

FORMS
You already know most of what you need to make good forms to be handled by PHP and a database. There are
a few PHP-specific points:
1. Always, always, always use a NAME for every data entry element (INPUT, SELECT, TEXTAREA, and so on).
These NAME attributes will become PHP variable names—you will not be able to access your values if you do
not use a NAME attribute for each one.
2. A form field NAME does not need to be the same as the corresponding database field name, but it’s often a
good idea.
3. You can (and usually should) specify a VALUE rather than let HTML send the default value. Consider substituting
a numerical value for a text value if possible, because the database is much slower at matching strings than
integers.
4. The VALUE can be set to data you wish to display in the form.
5. We can pass multiple variables in an array.

GET Arguments
The GET method passes arguments from one page to the next as part of the Uniform Resource Indicator (you
may be more familiar with the term Uniform Resource Locator or URL) query string. When used for form handling,
GET appends the indicated variable name(s) and value(s) to the URL designated in the ACTION attribute with a
question mark separator and submits the whole thing to the processing agent (in this case a Web server).

POST Arguments
POST is the preferred method of form submission today, particularly in nonidempotent usages (those that will
result in permanent changes), such as adding information to a database. The form data set is included in the
body of the form when it is forwarded to the processing agent (in this case, PHP). No visible change to the URL
will result according to the different data submitted. The POST method has these advantages:
1. It is more secure than GET because user-entered information is never visible in the URL query string, in the
server logs, or (if precautions, such as always using the password HTML input type for passwords, are taken)
onscreen.
2. There is a much larger limit on the amount of data that can be passed (a couple of kilobytes rather than a
couple of hundred characters).
Example1:
<?php
function validate_name($name)
{
if(strlen(trim($name))= =0)
return 0;
else
return 1;
}
if (isset($_POST[‘submit’]))
{
if(validate_name($_POST[‘name’]))
print “Name is valid”;

PHP 134
An ISO 9001 : 2000 Recognised Institution

Example2:
<form name=”form1" method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’] ?> “>
Select Language:<br>
<input name=”languages[]” type=”checkbox” value=”C” checked>C<br>
<input name=”languages[]” type=”checkbox” value=”C++”>
C++<br>
<input name=”languages[]” type=”checkbox” value=”Java”>Java<br>
<input name=”submit” type=”submit” value=”submit”>
</form>
<?php
if (isset($_POST[‘submit’]))
{
print “Selected Languages are :<br>”;
foreach($_POST[‘languages’] as $language)
print $language;
}
?>

Example3: Data from database


<?php
function create_dropdown($ctrl,$options)
{
$dropdown = “<select name=\”$ctrl\”>”;
foreach($options as $value1=>$name1)
{
$dropdown = $dropdown . “<option value=\”$value1\”>$name1</option>”;
}
$dropdown = $dropdown .”</select>”;
return $dropdown;
}
mysql_connect(“localhost”,”root”,””) or die(“Could not able to connect”);
mysql_select_db(“test”) or die (“could not find database”);
$query = “select id,name from languages”;
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$value = $row[“id”];

PHP 135
An ISO 9001 : 2000 Recognised Institution

$name = $row[“name”];
$options[“$value”] = $name;
}
print “Select Language<br>”;
echo create_dropdown(“languages”,$options);
?>

Example 4:
<?php
function validate_name($name)
{
if(strlen(trim($name))==0)
{
$message = “Name should not empty”;
return $message;
}
}

if (isset($_POST[‘submit’]))
{
$name = $_POST[‘name’];
$password = $_POST[‘password’];
$email = $_POST[‘email’];

$message= validate_name($name);
if(strlen($message)==0)
{
mysql_connect(“localhost”,”root”,””) or die(“Connection failed”);
mysql_select_db(“test”) or die(“database not exists”);
$query = “insert into userdetails(name,password,email) values(‘$name’,’$password’,’$email’)”;
$result = mysql_query($query);
if(mysql_affected_rows()==1)
{
$note = “One record inserted”;
}
else

PHP 136
An ISO 9001 : 2000 Recognised Institution

{
error_log(mysql_error);

$note = “ error while storing “;


}
}
}

<form name=”form1" action=”<?php echo $_SERVER[‘PHP_SELF’] ?>” method=”post”>


Enter Name:<input name=”name” type=”text” size=”12"><font color=”red”> <?php print $message ?></font><br>
Enter password:<input name=”password” type=”password” size=”12"><br>
Enter email:<input name=”email” type=”text” size=”12"><br>
<input name=”submit” type=”submit” value=”submit”>
</form>
<p> <?php echo $note?></p>

PHP 137

You might also like