Chapter 5 Cgi & PHP
Chapter 5 Cgi & PHP
PHP
Session Controls
How to generate a dynamic content to web pages or web
applications?
Solution
Using Server Side Programs
Common Gateway Interface (CGI)
#include <stdio.h>
printf("%s%c%c\n", "Content-Type:text/html;”,13,10);
printf("<TITLE>Multiplication results</TITLE>\n");
printf("<H3>Multiplication results</H3>\n");
data = getenv("QUERY_STRING");
return 0; }
The fundamental architectural issue with
CGI-BIN based systems is that
Each time a CGI script is executed, a new
process is started. For busy Web sites, this can
slow down the server noticeably
Server-side scripting is often used to provide a
customized interface for visitors
Run on the server side
Source code is hidden from visitors
Can interact with database and other data sources like file
Examples
PHP, JSP, ASP.net …
Setting Up PHP
install a web server
install PHP
install a database, such as MySQL
<html> PHP file <html> Output: resulting HTML
<head> <head>
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 NOT to be deleted
<?php
$x = 5; // global scope
function myTest() {
$y = 5; // local scope
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
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
ECHO PRINT
Returning values
function functionName(){ code to be executed; return $value; }
Superglobal variables
are built-in variables that are always available in all scopes,
can be accessed from any function, class or file without having to
do anything special
Some of the superglobal variables are:
$GLOBALS : is used to access global variables from anywhere in the PHP
script
$_SERVER: holds information about headers, paths, and script locations.
$_REQUEST: is used to collect data after submitting an HTML form.
$_POST, $_GET, $_FILES, $_ENV, $_COOKIE, $_SESSION
$_SERVER holds information about headers, paths, and
script locations.
$_POST is used to collect form data after submitting
an HTML form with method="post”
$_GET used to collect form data after submitting an
HTML form with method="get“
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.
Default is the current date and time
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):
checks if the "end-of-file" (EOF) has been reached
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
fgets(pointerToOpenedFile)
is used to read a single line from a file
fgetc(pointerToOpenedFile)
is used to read a single character 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
$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.
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
HTTP request message:
Accept-Encoding: gzip
From Browser to Server
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
Modify a Cookie Value
To modify a cookie, just set (again) the cookie using the
setcookie() function
Delete a Cookie
To delete a cookie, use the setcookie() function with an
expiration date in the past
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
Two main disadvantages of cookies
Limited in size by browser
Stored client-side " users / malicious people can change
Two main disadvantages of cookies
Limited in size by browser
Stored client-side users / malicious people can change
This data will be available to all pages on the site during that
visit.
3c7foj34c3jj973hjkop2fc937e3443.
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"