Chapter 2 PHP
Chapter 2 PHP
Over the past few years, PHP and server-side Java have
gained momentum, while ASP has lost its share.
Introduction to PHP…
PHP is a server-side scripting language, which means that the
scripts are executed on the server, the computer where the
Web site is located.
This is different than JavaScript, another popular language for
dynamic Web sites.
JavaScript is executed by the browser, on the user’s computer.
Thus, JavaScript is a client-side language.
PHP files are executed through the web server only, not directly
http://127.0.0.1/test.php
Writing PHP
You add PHP code to your web page by using tags, similar to
other tags in the HTML file.
The PHP code section is enclosed in PHP tags with the following
form:
<?php
PHP statements
?>
For example, you can add the following PHP section to your HTML
file.
<?php
echo “This line brought to you by PHP”;
?>
Web pages that contains PHP should be saved with .php
extension.
You can also add several PHP sections to a Web page.
Writing PHP…
There are actually four different styles of PHP tags we can use.
Short style
<?
echo “<p>Order processed. </p>”;
?>
This style of tag is the simplest and follows the style of an
SGML.
To use this tag, you either need to enable short tags in your
config file (short_open_tag = On), or compile PHP with short
tags enabled.
XML style
<?php
echo “<p>Order processed. </p>”;
?>
This style of tag can be used with XML documents.
Most commonly used tag in literatures
Writing PHP…
SCRIPT style
<SCRIPT LANGUAGE=”php”>
echo “<p>Order processed. </p>”;
</SCRIPT>
This style of tag is the longest and will be familiar if you’ve
used JavaScript.
ASP style
<%
echo “<p>Order processed. </p>”;
%>
This style of tag is the same as used in Active Server Pages
(ASP).
It can be used if you have enabled the asp_tags configuration
setting.
Writing PHP…
Example: your first hello world PHP script
<html>
<head><title>Hello World Script</title></head>
<body>
<?php
echo “<p>Hello World!</p>”
?>
</body>
</html>
We use the action attribute to specify the PHP to execute when the
web page is submitted.
<form name=”formname” method=”submitingmethod”
action=”phpfile.php”>
form elements
</form>
Example:
$testvar = 3 + 4;
echo “The value is $testvar”; //output: The value is 7
$testvar = “three”;
echo “The value is $testvar”; //output: The value is
three
1.2 Working with
Variables…
Displaying variable values
You can display the value stored in a variable with print statement.
Sunday”.
Removing Variables
You can uncreate the variable by using this statement:
unset($age);
You can test for a negative, as well, by using not operator (!)
in front of the expression.
For example, the following statement returns TRUE if the
variable does not exist at all:
!isset($varname)
1.2 Working with
Variables…
<?php
$a = "test";
$b = "anothertest";
echo isset($a); // TRUE
echo isset($a, $b); //TRUE
unset ($a);
echo isset($a, $b); //FALSE
$foo = NULL;
print isset($foo); // FALSE
$var = 0;
if (empty($var)) // evaluates TRUE
echo '$var is either 0 or not set at all';
?>
1.2 Working with
Variables…
Type Casting
We often work with multiple data types at once.
task in programming.
Type conversion or typecasting refers to changing an
Implicit and
Explicit
$foo = 321.456;
settype($foo, "string");
print("<br>String: $foo"); //output: String: 321.456
Constants should not be given names that are keywords for PHP.
Keywords are words that have meaning for PHP, such as echo,
and they can’t be used as constants because PHP treats them
as the PHP feature of the same name.
1.2 Working with
Variables…
Displaying constants
You can determine the value of a constant by using print as
follows:
print(INTEREST);
$num = 33;
(boolean) $num;
echo $num;
Output: 33
echo gettype("4");
Output: String
1.3 Using Operators
PHP supports many operators.
Mathematical Operators
Arithmetic operators are straightforward—they
However, if the ++ is after the $a, we are using the postfix increment
operator.
This has a different effect.
$a=4;
echo $a++;
In this case, first, the value of $a is returned and printed, and second, it is
incremented.
The value that is printed is 4.
However, the value of $a after this statement is executed is 5.
1.3 Using Operators…
Operator description example meaning
Output:
They are equal
1.3 Using Operators…
Logical Operators
The logical operators are used to combine the
operator description
xor Is true if either (but not both) of its arguments are true
! Is true if its single argument (to the right) is false and false if its argument is true
>> Shift right Shift the bits of $a $b steps to the right (each step means
divide by two)
1.3 Using Operators…
<?php
echo 12 ^ 9; // Outputs '5'
echo "1" ^ "9"; // Outputs the Backspace (ascii 8)
// ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8
1.4.1 if Statements
We can use an if statement to make a decision.
true or false.
If the condition is true, the associated block of code will be
executed.
Conditions in if statements must be surrounded by brackets ().
Example:
for ($i = 1; $i <= 3; $i++) {
echo “$i. Hello World!<br>”;
}
The following is the output from these statements:
1. Hello World!
2. Hello World!
You can nest for loops inside of for loops.
Suppose you want to print out the times tables from 1 to 9.
1x1=1
...
1x9=9
2x1=2
...
2 x 9 = 18
…
9x1=9
…
9 x 9 = 81
syntax:
while (condition)
{
statement
}
amount of time.
This is very stressful on your Web server, and renders the Web page in
1.5 Using Loops…
Example: infinite loop
$i = 1;
while($i < 10)
{
print(“i is $i”);
}
output:
i is 1
i is 1
...
The variable $i is not incremented in the body of the
while loop.
As a result, the value of $i is always 1 making the while
1.5 Using Loops…
Breaking out of a loop
Sometimes you want your script to break out of a loop.
PHP provides two statements for this purpose:
break: breaks completely out of a loop and continues
with the script statements after the loop.
continue: stops current iteration and goes back to
condition check. If condition check is true, it will go
to the next iteration.
The break and continue statements are usually used in
conditional statements. In particular, break is used
most often in switch statements.
1.5 Using Loops…
Example: break statement
$counter = 0;
while ( $counter < 5 ) {
$counter++;
if ( $counter == 3 ) {
echo “break\n”;
break;
}
echo “Last line in loop: counter=$counter\n”;
}
echo “First line after loop\n\n”;
Creating Arrays
There are different ways to create an array in a PHP script:
by assigning a value into one (and thereby implicitly creating it),
by using the array() construct, or
by calling a function that happens to return an array as its value.
Associative Arrays
In the products array, we allowed PHP to give each item the default
index.
PHP also supports associative arrays.
ways.
One is by using loop together with array index.
output:
Tires
Oil
Spark Plugs
battery
Jar
1.6 Arrays…
Using foreach to walk through an array
You can use foreach to walk through an array one value at a
Multidimensional Arrays
Arrays do not have to be a simple list of keys and values—
easy.
The following code results in the array being sorted into
The following code creates an associative array and then sorts the
array into ascending price order.
$prices = array( “Tires”=>100, “Oil”=>10, “Spark Plugs”=>4 );
asort($prices);
$prices = array( “Tires”=>100, “Oil”=>10, “Spark Plugs”=>4 );
ksort($prices);
1.6 Arrays…
Example:
$capitals[1] = “Sacramento”;
$capitals[2] = “Austin”;
$capitals[3] = “Salem”;
rsort($arrayname) Sorts by value in reverse order; assigns new numbers as the keys.
natsort($arrayname) Sorts mixed string/number values in natural order. For example, given an
array with values day1, day5, day11, day2, it sorts into the following order:
day1, day2, day5, day11. The previous sort functions sort the array into this
order: day1, day11, day2, day5.
1.6 Arrays…
Determining Size of Array
You can find out the size of your array by using either the count
$n = count($arrayname);
$n = sizeof($arrayname);
After either of these statements, $n will contain the number of
Built-in Arrays
PHP has several built-in arrays that you can use when writing PHP
scripts.
Different types of information are stored in different arrays.
$_REQUEST Contains all the variables together that are in $_POST, $_GET, and $_SESSION.
$_ENV Contains information provided by your operating system, such as the operating system
name, the system drive, and the path to your temp directory. This info varies depending
on your operating system
$HTTP_ENV_VARS Same as $_ENV.
1.6 Arrays…
The $_SERVER and $_ENV arrays contain different
information, depending on the server and
operating system you’re using.
You can see what information is in the arrays for
your particular server and operating system by
using the following statements:
foreach($_SERVER as $key =>$value)
echo “Key=$key, Value=$value\n”;
1.6 Arrays…
The output includes such lines as the following:
Key=HTTP_HOST, Value=127.0.0.1
Key=HTTP_ACCEPT, Value=text/html,application/xhtml+xml,
application/xml;q=0.9,*/*;q=0.8
Key=HTTP_ACCEPT_LANGUAGE, Value=en-us,en;q=0.5
Key=HTTP_ACCEPT_ENCODING, Value=gzip, deflate
Key=HTTP_ACCEPT_CHARSET, Value=ISO-8859-1,utf-8;q=0.7,*;q=0.7
Key=HTTP_CONNECTION, Value=keep-alive
Key=WINDIR, Value=C:\Windows
Key=SERVER_SIGNATURE, Value=
Key=SERVER_SOFTWARE, Value=Apache/2.2.17 (Win32) PHP/5.3.6
Key=SERVER_ADDR, Value=127.0.0.1
Key=SERVER_PORT, Value=80
Key=REMOTE_ADDR, Value=127.0.0.1
Key=DOCUMENT_ROOT, Value=C:/Program Files (x86)/VertrigoServ/www
Key=SERVER_ADMIN, [email protected]
Key=SCRIPT_FILENAME, Value=C:/Program Files
(x86)/VertrigoServ/www/environment.php
Key=REMOTE_PORT, Value=2005
Key=GATEWAY_INTERFACE, Value=CGI/1.1
Key=SERVER_PROTOCOL, Value=HTTP/1.1
Key=REQUEST_METHOD, Value=GET
Key=QUERY_STRING, Value=
1.6 Arrays…
The PHP_SELF element shows the file that
contains the script that is currently
running.
You can see the information in the $_ENV
array by using the phpinfo() statement
with a 16 to specify the environmental
variables, as follows:
phpinfo(16);
1.7 Functions in PHP
Applications often perform the same task at different points in the
script or in different scripts.
This is when functions come in handy.
A function is a group of PHP statements that perform a specific task.
You can use the function wherever you need to perform the task.
Defining Functions
You can create a function by putting the code into a function block.
Calling a function
The following line is the simplest possible call to a function:
functionName();
This calls a function called functionName that does not
require parameters.
This line of code ignores any value that might be returned by
this function.
1.7 Functions in PHP…
Most functions do require one or more parameters.
We pass parameters by placing the data or the name of a
variable holding the data inside parentheses after the
function name.
A call to a function with a parameter resembles the
following:
function_name(parameter);
other functions.
A variable’s scope controls where that variable is visible and
useable.
PHP has fairly simple rules:
Variables declared inside a function are in scope from the statement in
which they are declared to the closing brace at the end of the function.
This is called function scope. These variables are called local variables.
Variables declared outside of functions are in scope from the statement in
which they are declared to the end of the file, but not inside functions.
This is called global scope. These variables are called global variables.
Using require() and include() statements does not affect scope. If the
statement is used within a function, function scope applies. If it is not
inside a function, global scope applies.
The keyword global can be used to manually specify that a variable
defined or used within a function will have global scope.
1.7 Functions in PHP…
Example: local variable
<?php
function test()
{
$testvariable = "this is a test variable";
}
echo "test variable: $testvariable<br>";
?>
output:
inside the function, $var = contents
outside the function, $var = contents
1.8 Cookies and Sessions
1.8.1 Cookies
You can store information in cookies and then retrieve it.
setcookie(“variable”,”value”);
The variable is the variable name, but you do not include
mktime: This function returns a date and time in a format that the
computer can understand. You must provide the desired date and time
in the following order: hour, minute, second, month, day, and year. If
any value is not included, the current value is used.
It is safest to set the cookie with a date you are sure has
already expired:
setcookie("vegetable", "", time()-60);
You should also ensure that you pass setcookie() the same
path, domain, and secure parameters as you did when
originally setting the cookie.
1.8 Cookies and
Sessions…
1.8.2 Session
A session is the time that a user spends at your Web site.
Users may view many Web pages between the time they enter your site
After you create a session, the session variables are available for your
use on any other Web page. To make session information available, PHP
does the following:
PHP assigns a session ID number.
The number is a really long nonsense number that is unique for the user
and that no one could possibly guess. The session ID is stored in a PHP
system variable named PHPSESSID.
PHP stores the variables that you want saved for the session in a file on the
server.
The file is named with the session ID number.
It’s stored in a directory specified by session.save_path in the php.ini file.
PHP passes the session ID number to every page.
1.8 Cookies and
Sessions…
If the user has cookies turned on, PHP passes the
session ID by using cookies.
If the user has cookies turned off, PHP behavior
depends on whether trans-sid is turned on in
php.ini.
PHP gets the variables from the session file for
each new session page.
Whenever a user opens a new page that is part of
the session, PHP gets the variables from the file by
using the session ID number that was passed from
the previous page.
The variables are available in the $_SESSION array.
1.8 Cookies and
Sessions…
Opening and closing sessions
You should open a session at the beginning of each Web page.
session_start();
Because sessions use cookies, if the user has them turned on,
session_start is subject to the same limitation as cookies.
That is, to avoid an error, the session_start function must be
called before any output is sent.
This means that it is must be the first line code in your program.
1.8 Cookies and
Sessions…
You may want to restrict your site to users with a valid user ID and
password.
For restricted sessions that users log into, you often want users to
log out when they’re finished.
To close a session, use the following statement wherever to want
to close the session:
session_destroy();
If you want to stop storing any variable at any time, you can unset
the variable by using the following statement:
unset($_SESSION[‘varname’]);
1.8 Cookies and
Sessions…
The following two scripts show how to use sessions to pass information
from one page to the next.
<?php
/* Script name: sessionTest1.php
* Description: Starts a session. Saves a session variable.
*/
session_start();
$_SESSION[‘fullName’] = “David John Antony”;
?>
<html>
<head><title>Testing Sessions page 1</title></head>
<body>
<p>This is a test of the sessions feature.
<form action=”sessionTest2.php” method=”POST”>
<input type=”text” name=”form_var” value=”testing”>
<input type=”submit” value=”Go to Next Page”>
</form>
</body>
1.8 Cookies and
Sessions…
In this script, a session is started and one session variable called fullName is
stored.
A form is also displayed with one text field where the user can enter some text.
When the submit button from this form, labeled “Go to Next Page” is clicked, the
sessionTest2.php script runs.
<?php
/* Script name: sessionTest2.php
* Description: Gets a variable from an existing session.
*/
session_start();
?>
<html>
<head><title>Testing Sessions page 2</title></head>
<body>
<?php
$session_var = $_SESSION[‘fullName’];
$form_var = $_POST[‘form_var’];
echo “session_var = $session_var<br>\n”;
echo “form_var = $form_var<br>\n”;
?>
</body>
1.8 Cookies and
Sessions…
output:
session_var = “David John Antony”;
form_var = testing