CHAPTER FIVE
Server Side Programs
Apache Web server Configuration
Common Gateway Interface(CGI)
PHP
Compiled By: Seble N.
Apache Web Server Configuration
The Common Gateway Interface (CGI)
Introduction to Server Side Scripts
PHP
Session Controls
How to generate a dynamic content to web pages or web
applications?
Solution
Using Server Side Programs
Common Gateway Interface (CGI)
Using any programming languages
Server Side Script Languages
php , asp, jsp …
In order to deliver dynamic content we need to extend the abilities of the
web server so that it can do more than merely send static web pages in
response to client requests. The common gateway interface (CGI) provides
a mechanism to do this
Common Gateway Interface
is a standard environment for web servers to interface with executable
programs installed on a server that generate web pages dynamically . Such
programs are known as CGI scripts or simply CGIs
A CGI script can be written in any language that allows it to be executed
(e.g., C/C++, Fortran, PERL, TCL, Visual Basic, AppleScript, Python, and
Unix shells), but by far, the most common language for CGI scripting is
PERL, followed by C/C++.
1. When serving static web pages the server is normally asked for a
file that has a .htm or .html extension. If we wish to serve a
dynamic page the extension would be different, for example .cgi,
.pl, or .php, .jsp, .asp
2. If a request comes in with one of these extensions the web server
knows to pass the request to the CGI which then interprets it
correctly and executes the script in the particular scripting
language
3. Once the script has finished executing the CGI then passes the
output back to the web server to be delivered as a response to
the client request
Output of cgi programs could be an html document,
image, file …
Most servers expect CGI programs to reside in a special
directory, usually called cgi-bin, and/or to have a certain
file extension like .cgi, so that the server knows to execute
the program rather than simply serving the CGI program
as a raw data
CGI programs communicate with the server using
STDIN/STDOUT and environment variables
What do we need to create a CGI program?
A programming language
A web server configured for CGI
A web server machine that can execute a program written
using the programming language you used
Write your cgi program in some text editor
Save the executable program with an extension of .cgi in the
directory cgi-bin which tells the web server to execute the
.cgi program instead before sending it to the client
CGI uses environment variables to send
your program its parameters.
For GET submissions, cgi programs read users
form input from the environment variable
QUERY_STRING. For POST submissions, from
STDIN.
The first output of a cgi program should be the
content type of the response file like
“Content-type: text/html”
On the next line display blank line, to
STDOUT
Then start writing your instructions
Everything that should be included in the response
HTML page should be printed to STDOUT
#include <stdio.h>
void main() {
cout<<"Content-type: text/html\n\n" ;
/**Print the HTML response page to STDOUT. **/
cout<<"<html>\n" ;
cout<<"<head><title>CGI Output</title></head>\n" ;
cout<<"<body>\n" ;
cout<<"<h1>Hello, world.</h1>\n" ;
cout<<"</body>\n" ;
cout<<"</html>\n" ;
exit(0) ;
}
<form action="http://www.cs.tut.fi/cgi-bin/mult.cgi">
Multiplicand 1: <input type=“text” name="m">
Multiplicand 2: <input type=“text” name="n">
<input type="submit" value="Multiply!“> </form>
#include <stdio.h>
#include <stdlib.h> mult.cgi
int main(void) {
char *data; long m,n;
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");
printf("<P>The product of %ld and %ld is %ld.",m,n,m*n);
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 …
Programs written in the above languages don’t require to
spawn a new process every time a page is requested
What is PHP?
PHP is an acronym for "PHP: Hypertext Preprocessor"
PHP is a widely-used, open source scripting language
PHP is free to download and use
What is a PHP File?
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to
the browser as plain HTML
PHP files have extension ".php"
What Can PHP Do?
PHP can generate dynamic page content
PHP can create, open, read, write and delete files on the server
PHP can process form data
PHP can send and receive cookies
PHP can add, delete, modify data in your database
PHP can be used to control user-access (Session Management)
PHP can encrypt data
With PHP you are not limited to output HTML. You can output
images, PDF files, and even Flash movies. You can also output any
text, such as XHTML and XML.
Why PHP?
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free
PHP is easy to learn and runs efficiently on the server side
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 Introduction <title> PHP Introduction </title>
</title> </head>
</head> <body>
<body> This is HTML! <br />
This is HTML! <br /> This is PHP! <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>
browser
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
PHP is whitespace insensitive
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 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>";
// using y outside the function will generate an error
echo "<p>Variable y outside function is: $y</p>";
?>
<?php
$x = 5;
$y = 10;
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
define(name, value, case-insensitive)
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo GREETING;
?>
PHP divides the operators in the following groups:
Arithmetic operators {+, -, *, /, %, **}
Assignment operators {=, +=, -=, *=, /=, %=}
Comparison operators {==, ===, !=, <>, !==, >,< ..}
Increment/Decrement operators {++, --}
Logical operators {and, or, xor, &&, ||, !}
String operators {. (concatenation) .= (concatenation
assignment)}
Array operators {+, ==, ===, !=, <>,!== } READ!
In PHP there are two basic ways to get output: echo and print
Singly quoted strings are treated literally, whereas doubly quoted strings
replace variables with their values
ECHO PRINT
has no return value has a return value of 1 so it can be used in
expressions
can take multiple parameters
can take one argument
can be used with or without
parentheses: can be used with or without parentheses:
print or print ().
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>"; print "<h2>PHP is Fun!</h2>";
echo “Hello", “World“; print "Hello world!<br>";
echo "<h2>$txt1</h2>"; print "<h2>$txt1</h2>";
echo "Study PHP at $txt2<br>"; print "Study PHP at $txt2<br>";
echo $x + $y; print $x + $y;
Commonly used functions to manipulate strings are
strlen(): returns the length of a string
echo strlen("Hello world!");
str_word_count(): counts the number of words in a string
echo str_word_count("Hello world!");
strrev(): reverses a string
echo strrev("Hello world!");
strpos(): searches for a specific text within a string
echo strpos(" Helloworld!", "world"); // outputs 6
str_replace(): replaces some characters with some other characters in
a string
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
PHP have the following conditional statements:
Use if to specify a block of code to be executed, if a specified
condition is true
Use else to specify a block of code to be executed, if the same
condition is false
Use else if to specify a new condition to test, if the first condition is
false
Use switch to specify many alternative blocks of code to be
executed
<?php <?php
$favcolor = "red";
$t = date("H");
switch ($favcolor) {
if ($t < "10") { case "red":
echo "Have a good morning!"; echo "Your favorite color is
} elseif ($t < "20") { red!";
echo "Have a good day!"; break;
} else { case "blue":
echo "Have a good night!"; echo "Your favorite color is
blue!";
}
break;
?> case "green":
echo "Your favorite color is
green!";
break;
default:
echo "Your favorite color is
neither red, blue,
nor green!";
}
?>
PHP supports different kinds of loops:
for
loops through a block of code a number of times
foreach
loops through elements of an array
while
loops through a block of code while a specified condition is
true
do/while
also loops through a block of code while a specified condition
is true
The for loop has the following syntax:
works only on arrays, and is used to loop
through each key/value pair in an array.
The while loop loops through a block of
code as long as a specified condition is true.
This loop executes the code block at least once,
before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
In PHP, there are three types of arrays:
Indexed arrays - Arrays with a numeric index
Using array() function
$cars = array("Volvo", "BMW", "Toyota");
On the fly
$cars[0]=“Volvo”; $cars[1]=“BMW”;
Associative arrays - Arrays with named keys
Using array() function
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
On the fly
$age['Peter'] = "35"; $age['Ben'] = "37"; $age['Joe'] = "43";
Multidimensional arrays - Arrays containing one
or more arrays
$cars = array (array("Volvo",22,18), array("BMW",15,13));
The count() function is used to return the length of an array
sort() - sort arrays in ascending order , rsort() - sort arrays in
descending order
asort() - sort associative arrays in ascending order, according to the
value
array_keys() - returns all the keys of an array
array_multisort() - sorts multiple or multi-dimensional arrays
array_push() - inserts one or more elements to the end of an array
array_reverse() - returns an array in the reverse order
array_search() - searches an array for a given value and returns the key
array_sum() - returns the sum of the values in an array
array_unique() - removes duplicate values from an array
shuffle() - shuffles an array
Besides the built-in PHP functions, we can create our own functions.
A function will not execute immediately when a page loads. Instead
will be executed by a call to the function
Syntax
function functionName(){ code to be executed; }
Function with parameters
function functionName($param1, $param2){ code to be executed; }
Function with default argument
function functionName($param1=5, $param2){ code to be executed; }
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“
$_GET can also collect data sent along with a URL
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';
The include and require statements are identical, except upon
failure:
If a file is not found require will produce a fatal error and stop the
script whereas include will only produce a warning and the script
will continue
So, if you want the execution to go on and show users the output, even if
the include file is missing, use the include statement.
vars.php
PHP has several functions for creating,
reading, uploading, and editing files.
fopen(filename, openingMode):
opens a file, on a file that does not exist, it will create it,
given that the file is opened for writing (w) or appending
(a).
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
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
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
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 allow neither
read, nor write
flock($fp3, 3); //release lock – releases a shared or
exclusive lock
<?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()”;
functions that return information on files:
“filesize()”, “fileatime()”, “filemtime()”, “filectime()”
copy(), delete(), filetype(), fseek(), ftell(),
mkdir()
HTTP is stateless – it does not keep track of the
client between requests
But sometimes we need to keep track of this
information
Shopping cart
“Remember me” on login sites
2 solutions to this issue
Cookies – small file stored client-side
Sessions – relevant data stored on the server
A cookie is a small file that the server stores on the user's
computer for tracking purposes.
There are three steps involved in identifying returning
users:
Server script sends a set of cookies to the browser. For
example name, age, or identification number etc.
Browser stores this information on local machine for future
use.
When next time browser sends any request to web server
then it sends those cookies information to the server and
server uses that information to identify the user.
A cookie is created with the setcookie() function.
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.
The global variable $_COOKIE[] is used to retrieve value of a
cookie
Syntax
$_COOKIE[cookieName]
Always check with isset($_COOKIE[$cookie_name]) before
trying to use the cookie’s value
The example creates a cookie named "user" with the value "John Doe". The cookie will
expire after 1 day(86400). The "/" means that the cookie is available in entire website
Cookies are usually set in an HTTP header
HTTP response message:
HTTP/1.1 200 OK From Server to Browser
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38
GMT; path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
If a browser is configured to store cookies, it
will then keep this information until the expiry
date.
If the user points the browser at any page that
matches the path and domain of the cookie, it will
resend the cookie to the server. The browser's
headers might look something like this:
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
Sessions store user data on the server
Limited only by server space
Cannot be modified by users
A potential downside to sessions is that they expire when
the browser is closed
Sessions are identified by a session id: often a small cookie!
But the rest of the data is still stored on the server
An alternative way to make data accessible across the various
pages of an entire website is to use a PHP Session
A session creates a file in a temporary directory on the server
where registered session variables and their values are stored.
This data will be available to all pages on the site during that
visit.
The location of the temporary file is determined by a setting in
the php.ini file called session.save_path.
When a session is started, the following actions take place:
PHP first creates a unique identifier for that particular session
which is a random string of 32 hexadecimal numbers such as
3c7foj34c3jj973hjkop2fc937e3443.
A cookie called PHPSESSID is automatically sent to the user's
computer to store unique session identification string.
A file is automatically created on the server in the designated
temporary directory and bears the name of the unique identifier
prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.
session_start() is used to
<?php
create or resume a session // Start the session
The session_start() function session_start();
?>
must be the very first thing in <!DOCTYPE html>
your document. Before any <html>
<body
HTML tags
<?php
Session variables are set with // Set session variables
$_SESSION["favcolor"] = "green";
the PHP global variable $_SESSION["favanimal"] = "cat";
$_SESSION echo "Session variables are set.";
echo $_SESSION["favcolor"];
All session variable values are ?>
stored in the global </body>
$_SESSION variable </html>
To remove all global <?php
session_start();
?>
session variables <!DOCTYPE html>
<html>
and destroy a <body>
<?php
// remove all session variables
session, use session_unset();
// destroy the session
session_unset() session_destroy();
?>
and
</body>
</html>
session_destroy()
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
Size limit? Depends on browser Depends only on server
(practically no size
limit)
Accessing information? $_COOKIE $_SESSION
General use? Remember small things Remembering varying
about the user, such as amount of data about
login name. Remember the user in one
things after re-opening browsing “session”.
browser More sensitive info.
The header() function sends a raw HTTP header to a
client.
header() must be called before any actual output is sent
to the client
Syntax
header(string, replace, http_response_code)
string Required. Specifies the header string to send
replace Optional. Indicates whether the header should replace
previous or add a second header. Default is TRUE (will replace).
FALSE (allows multiple headers of the same type)
http_response_code Optional. Forces the HTTP response code to the
specified value
Prevent page caching:
<?php
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>
<html>
<body>
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
Custom errors and error triggers
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 and
creates an object containing the exception information
<?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();
}
?>