Web Chapter 5
Web Chapter 5
Solution
Using Server Side Programs
Common Gateway Interface (CGI)
printf("%s%c%c\n",
"Content-Type:text/html;”,13,10);
printf("<TITLE>Multiplication results</TITLE>\
n");
data = getenv("QUERY_STRING");
The fundamental architectural
issue with
CGI-BIN based systems is that
Each time a CGI script is executed, a
Setting Up PHP
install a web server
install PHP
install a database, such as MySQL
<html PHP file <html Output: resulting HTML
> >
<head <head
> >
<title> PHP <title> PHP Introduction
Introduction </title>
</
</title> head>
</ <body
head> >
<body This is HTML!
> <br />
This is HTML! This is PHP!
<br /> <br />
<? </
php body>
echo 'This is PHP! </
<br />'; html>
?
> A PHP script is executed on the
</ server, and
body> the plain HTML result is sent
</ back to the
html> brows
er
Basic PHP Syntax
A PHP script can be placed anywhere in the
document
A PHP script starts with <?php and ends with
?>:
PHP statements end with a semicolon (;)
Comments
// This is a single-line comment
# This is also a single-line comment
/* multi line comment*/
PHP is case sensitive (variables not PHP
keywords)
In PHP, a variable starts with the $ sign, followed by the
name of the
variable:
$txt = "Hello world!";
$x = 5;
$y = 10.5;
PHP has no command for declaring a variable. It is
created the moment you first assign a value to it
Variable name can only contain letter, number or
underscore and it cannot start with a number
PHP is a loosely-typed language
Do not need to declare the type of a variable
Type can change throughout the program
PHP has three different variable scopes:
Global
A variable declared outside a function has a GLOBAL
SCOPE and can only be accessed outside a function
The global Keyword
The global keyword is used to access a global variable from
within a function.
Local
A variable declared within a function has a LOCAL SCOPE
and can
only be accessed within that function
Static
When a function is completed/executed, all of its variables
are deleted. However, sometimes we want a local variable
<?php
$x = 5; // global
scope function
myTest() {
$y = 5; // local
scope
function myTest() {
global $x, $y; // refers to the above
variables
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
• PHP also stores all global variables in an array called
$GLOBALS[index]. The index holds the name of the variable.
This array is also accessible from within functions and can be
used to update global variables directly.
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
Variables can store data of different types.
PHP supports the following data types:
String : can be any text inside quotes. You can use single or
double quotes:
Integer : $x=10;
Float (also called double): $x=10.01;
Boolean $x=true;
Array : $cars = array("Volvo","BMW","Toyota");
Object: are instances of programmer-defined classes
NULL: A variable of data type NULL is a variable that
has no value assigned to it. $x=null;
var_dump() function can be used to identify the data
type and value of a variable
Usage : var_dump($x);
A constant is an identifier for a simple value. The
value cannot be changed during the script.
A valid constant name starts with a letter or
underscore (no $ sign before the constant name).
Unlike variables, constants are automatically global
across the entire
script.
To create a constant, use the define() function.
Syntax
test_get.php
The date() function formats a timestamp to a more
readable
date and time.
Syntax
date(format,timestamp)
format Required. Specifies the format of the timestamp
d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
l (lowercase 'L') - Represents the day of the week
timestamp Optional.
Specifies a timestamp: which is a sequence of characters, denoting
the date and/or
time at which a certain event occurred.
PHP Include & Require Statements
are used to insert the content of one PHP file into
another PHP file (before the server executes it)
Syntax
include 'filename'; or require 'filename';
fclose(pointerToOpenedFile):
is used to close an open file
feof(pointerToOpenedFile):
r Read only. File pointer at the start of the file
r+ Read/Write. File pointer at the start of the file
w Write only. Overwrites the file
w+ Read/Write. Overwrites the file
a Append. File pointer at the end of the file.
If the file doesn't exist, fopen() will try to create the file
a+ Read/Append. File pointer at the end of the file.
x Create and open for write only.
File pointer at the beginning of the file.
If the file already exists, the fopen() call will fail and generate an error. If
the file does not
exist, try to create it
x+ Create and open for read/write.
File pointer at the beginning of the file.
If the file already exists, the fopen() call will fail and generate an error. If
the file does not exist, try to create it
readfile(filename):
reads a file and writes it to the output
buffer
fread(param1, param2): reads from an
open file
param1: contains the name of the file to read
from
param2: specifies the maximum number of
bytes to read
fgets(pointerToOpenedFile)
is used to read a single line from a file
fwrite(param1, param2) function is
used to write to a file.
param1: contains the name of the file to write
to and
param2: is the string to be written
File locking mechanisms
With many users accessing your scripts at the
same time,
your files could quickly become corrupt.
flock() function
locks a file and won’t allow other processes
to write or read the file while the current
process is running.
Syntax :
flock(pointerToOpenedFile,
lockingMode)
flock($fp1, 1); //shared lock – allows read,
doesn’t allow
write
flock($fp2, 2); //exclusive lock – doesn’t
<?php
$file = fopen("test.txt","w+");
// exclusive lock
if (flock($file,LOCK_EX)){
fwrite($file,"Write something");
// release lock
flock($file,LOCK_UN);
}
else {
echo "Error locking
file!";
}
fclose($file);
?>
PHP has a lot of built in functions
that you can use with file
processing. Some of them are
“file_exists()”, “is_file()”, “is_dir()”,
“is_readable()”,
“is_writeable()”, “is_executable()”;
Syntax
setcookie(name, value, expire, path, domain,
secure);
Only the name parameter is required. All other parameters
are optional.
The setcookie() function must appear BEFORE the <html>
tag.
3c7foj34c3jj973hjkop2fc937e3443.
identification string.
</body>
) and </html>
session_destro
Cookies Sessions
Where is data stored? Locally on client Remotely on server
Expiration? Variable – determined Session is destroyed
when cookie is set when the browser
is closed
Redirect browser to
another page
<?php
header("Location: http://www.w3schools.com/");
?>
<html> <body> ...... </body> </html>
The default error handling in PHP is
very simple. An error message with
filename, line number and a message
describing the error is sent to the
browser.
Error handling methods:
Simple "die()" statements
Error reporting
The die() function prints a
message and exits the current
script
Syntax
die(message)
<?php if(!
file_exists("welcome.txt")) {
die("File not found");
} else {
$file=fopen("welcome.txt","r
");
}
?>
Proper exception code should include:
Try - A function using an exception should be
in a "try" block. If the exception does not
trigger, the code will continue as normal.
However if the exception triggers, an
exception is "thrown"
Throw - This is how you trigger an
exception. Each "throw" must have at
least one "catch"
Catch - A "catch" block retrieves an exception
<?php
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or
below");
}
return true;
}
try {
checkNum(2);
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>