Chapter 4
Chapter 4
PHP
What is php?
PHP, usually installed as a module inside the web server, is a popular server
side scripting language in which applications are written to communicate with
MySQL (or other database systems) on the back end and browsers on the front
end.
When a browser calls a PHP document, the Server reads the PHP document,
runs the PHP code and returns the resulting HTML code to the browser. The
PHP script is executed on the server, and the plain HTML result is sent back to
the browser.
PHP is available on millions of web domains and powers famous sites such as
Facebook, Yahoo!, YouTube, and Wikipedia
Features of php
PHP supports cookies and sessions
PHP supports many databases (MySQL, Oracle, Sybase, etc.).
PHP files can contain text, image, HTML tags and scripts
PHP files are returned to the browser as plain HTML
PHP runs on different platforms (Windows, Linux, Unix, etc.)
PHP is compatible with almost all servers used today (Apache,
IIS, etc.)
PHP is FREE to download from the official PHP resource:
www.php.net
PHP is easy to learn and runs efficiently on the server side
Setting up php with apache
When we install Wamp server, all the required software to run
php, such as, Apache,PHP and MySQL are installed in Windows
OS
Basic php syntax
Php comments
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
echo "Comments are ignored";
?>
</body>
</html>
Predefined and user variables
Predefined variables: PHP provides a large number of predefined variables. The
following variables are predefined in php .
They are called super global variables. They are always available in all scopes.
User defined variables:
Rules for defining user defined PHP variables are,
Variables in PHP starts with a $ sign, followed by the name of the variable
The variable name must begin with a letter or the underscore character
A variable name can only contain alpha-numeric characters and underscores (A-
z, 0-9, and _ )
A variable name should not contain spaces
Variable names are case sensitive (y and Y are two different variables)
In PHP, a variable does not need to be declared before adding a value to it.
PHP automatically converts the variable to the correct data type, depending on
its value
Variable types in php:
The basic data types in PHP are
Retrieve data from html forms
User input should be validated on the browser whenever possible (by client
scripts).
Browser validation is faster and reduces the server load.
You should consider server validation if the user input will be inserted into a
database.
A good way to validate a form on the server is to post the form to itself, instead
of jumping to a different page.
The user will then get the error messages on the same page.
This makes it easier to discover the error
home.php
<form method="POST" action="home.php">
<input type="hidden" name= "posted" value="true">
Please enter your name:
<input type="text" name="fullname">
<input type="submit" value="Send">
</form>
<?php
if(isset($_POST['posted']))
echo "Hello ".$_POST['fullname'];
?>
1.php
<?php
echo '<a href="2.php?
a=10&b=20">Click to goto page 2</a>';
?>
2.php
<?php
echo "a=$_GET[a]<br>";
echo "b=$_GET[b]";
?>
Using numbers and strings in php
<?php
echo "Hello World";
?>
<?php
$name = "Anand";echo "Hello, $name";
?>
<?php
$name = 'Anand';echo 'Hello, $name';
?>
<?php
$weight=100; echo 'The total weight is ' . $weight. 'kg';
?>
Control structures:
PHP supports control structures such as if,if-else,if-elseif-elseif-…-else,switch
statements
<?php
$a=5;$b=3;
if ($a > $b)
echo "a is bigger than b";
?>
<?php
$a=3;$b=5;
if ($a > $b) { echo "a is bigger than b";}
else { echo "a is NOT bigger than b";}
?>
<?php
$a=3;$b=5;
if ($a > $b) { echo "a is bigger than b";}
elseif ($a == $b) {echo "a is equal to b";}
else { echo "a is smaller than b";}
?>
<?php
$i=5;
switch ($i) {
case 0: echo "i equals 0";
case 1: echo "i equals 1";
case 2: echo "i equals 2";
default:echo "i is not equal to 0,1,or 2";
}
?>
Conditional and loop statements:
In PHP, we have the following looping statements:
while- loops through a block of code while a specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as
a specified condition is true
for - loops through a block of code a specified number of times
foreach- loops through a block of code for each element in an array
<?php
$a=array("Red","Blue","Green","Yellow");
$i=0;
while($i<count($a))
{echo "<br>".$a[$i];
++$i;
}
?>
<?php
$a=array("Red","Blue","Green","Yellow");
$i=0;
do {echo "<br>".$a[$i];
++$i;
} while($i<count($a));
?>
<?php
$a=array("Red","Blue","Green","Yellow");
for($i=0;$i<count($a);++$i)
echo "<br>".$a[$i];
?>
<?php
$a=array("Red","Blue","Green","Yellow");
foreach($a as $v)
echo "<br>".$v;
?>
<?php
$b=2.55;
$a=array("Red",12,true,3.44,$b);
foreach($a as $v) //see note below
echo "<br>".$v;
?>
<?php
$a["Lisa"] = "28";
$a["Jack"] = "16";
$a["Ryan"] = "35";
$a["Rachel"] = "46";
$a["Grace"] = "34";
foreach( $a as $k => $v) //see note below
{echo "Name: $k, Age: $v <br />";}
?>
Note: The statement “foreach($a as $k=>$v)” should be read as “For each $a as
$k of $v”. It means, for each element of the associative array $a, I want to refer
to the key as $k and the value as $v.
Similarly the statement “foreach($a as $v) “ should be read as “For each $a as
$v”. It means, for each element of the array $a, I want to refer it as $v.
Introducing References
References:
References in PHP are a means to access the
same variable content by different names. They
are not like C pointers; for instance, you cannot
perform pointer arithmetic using them, they are
not actual memory addresses.
There are three basic operations performed
using references: assigning by reference, passing
by reference, and returning by reference.
By default, variables are always assigned by value.
That is to say, when you assign an expression to a
variable, the entire value of the original
expression is copied into the destination variable.
This means, for instance, that after assigning one
variable's value to another, changing one of those
variables will have no effect on the other
PHP also offers another way to assign values to variables: assign by reference.
This means that the new variable simply references (in other words, "becomes an
alias for" or "points to") the original variable. Changes to the new variable affect
the original, and vice versa.
To assign by reference, simply prepend an ampersand (&) to the beginning of the
variable which is being assigned (the source variable). For instance, the
following code snippet outputs 'My name is axmed' twice
<?php
$foo = ‘axmed'; // Assign the value ‘axmed' to $foo
$bar = &$foo; // Reference $foo via $bar.
$bar = "My name is”. $bar; // Alter $bar...
echo $bar;
echo $foo; // $foo is altered too.
?>
This does not mean that variable content will be destroyed. For example, the
below code, won't unset $b, just $a.
<?php
$a = 1;
$b =& $a;
echo "a=".$a."<br>"."b=".$b."<br>";
unset($a);
echo "a=".$a."<br>"."b=".$b."<br>";
?>
References and arrays
In PHP, there are three kinds of arrays:
– Numeric array - An array with a numeric index
– Multidimensional array - An array containing one or more arrays
– Associative array - An array where each ID key is associated with a value
Numeric arrays
<?php
//Numeric Array
$colors=array("Red","Blue","Green","Yellow");
$fruits[0]="Apple";
$fruits[1]="Mango";
$fruits[2]="Grape";
echo "<br>".$colors[1];
echo "<br>".$fruits[1];
?>
Multidimensional Array
<?php
$items['books'][0]="book0";
$items['books'][1]="book1";
$items['bags'][0]="bag0";
$items['pens'][0]="pen0";
$items['pens'][1]="pen1";
$items['pens'][2]="pen2";
echo $items['pens'][1];
?>
Associative Array
<?php
$ages = array(‘Xasen'=>32, ‘m.amin'=>42, 'Raxma'=>34);
echo "<br>".$ages[‘M.amin'];
?>
References are applicable to arrays also
<?php
$a=array("zero","one","two");
$b=$a; //array $a is copied into array $b
$b[3]="three";
print_r($a);
echo"<br>";
print_r($b);
?>
<?php
$a=array("zero","one","two");
$b=&$a; //both $a,$b represent same array
$b[3]="three";
print_r($a);
echo"<br>";
print_r($b);
?>
Functions
default parameter
<?php
function add_tax_rate($amount, $rate=10)
{ $total = $amount * (1 + ($rate / 100));
return($total); }
echo add_tax_rate(10);
echo "<br>".add_tax_rate(10, 9);
?>
call by value
<?php
function increment($value, $amount = 1) {
$value = $value +$amount;
}
$a = 10;
echo $a.'<br />';
increment($a);
echo $a.'<br />';
?>
call by reference
<?php
function increment(&$value, $amount = 1) {
$value = $value +$amount;
}
$a = 10;
echo $a.'<br />';
increment($a);
echo $a.'<br />';
?>
Functions : returning Reference
When you use a function to return a reference, you need follow these rules:
To declare a function that returns a reference, the function name must be
prefixed with '&' in the function definition statement.
If a function is declared to return a reference, it should use the 'return'
statement to return a variable.
To call a function that returns a reference, the function name must be prefixed
with '&' in the function call operation.
The returning reference from a function should be assigned to another variable.
using a function to return a reference
<?php
function &f($a) {
$a+=10;
return($a);
}
$a=5;
$b=&f($a);
echo $b;
?>