Documente Academic
Documente Profesional
Documente Cultură
a) Client Side: the languages that helps you perform different tasks
on the client side for example Javascript helps you to validate your
forms and show message accordingly to your users without submitting
page to your server on the client side. VB Script and Client Side XSLT
are other examples.
b) Server Side Languages:
Server side languages make your website dynamic and intelligent. You
can take input from your users and can perform certain operations on
the input to generate desired output. For example Online Shopping
Stores, Online Examination Applications, Online Reservation Systems,
Database driven websites are a few examples of the applications
powered by Server Side Languages.
PHP is a server side language and it helps you to make your site
intelligent to provide dynamic features to your users. Other examples
of server side languages are ASP, PERL, Cold Fusions and Server Side
Java etc.
<html>
<head>
<title>Example</title>
</head>
<body>
<?php
echo "Hi, I'm a PHP script!";
?>
</body>
</html>
1
In 1995 Rasmus Lerdorf made a set of scripts based on PERL
to access his resume and named it as PHP / FI stands for Personal
Home Page / Forms Interpreter. In 1997 Rasmus released PHP / FI 2.0
with a large C-implementation and it received rapid fame due to its
ease of use and C like syntax as it was easy for C programmers to
adopt and its programming rules were comparatively simple than C
language. After some beta versions of PHP / FI 2.0 finally Alpha PHP
3.0 was released later.
In 1997 Andi Gutmans and Zeev Suraski worked together
with Rasmus to completely rewrite the language and introduce a more
powerful language known as PHP 3.0. Shortly after PHP 3.0 in 1998
PHP 4 came on the screen with improved performance for complex
applications and in 2004 finally PHP 5.0 was released with a new
object model and plenty of new features.
Why PHP?
If you are still confused that why you should use PHP then answer is
very straight forward - if you want to make a web application that can
take input from users and can process it to generate certain output
then you will need PHP to work for you on server side and response to
different events generated from client side accordingly. For example if
you want to make an Online Shopping Store for your Video Games
business where people can browse different categories of games and
can shop of their choice and finally can pay you online in real time.
2
MODULE 2
A PHP file normally contains HTML tags, just like an HTML file, and
some PHP scripting code.
<html>
<body>
<?php echo "Hello World"; ?>
</body>
</html>
A PHP scripting block always starts with <?php and ends with ?>. A
PHP scripting block can be placed anywhere in the document.
Each code line in PHP must end with a semicolon. The semicolon is a
separator and is used to distinguish one set of instructions from
another.
There are two basic statements to output text with PHP: echo and
print. In the example above we have used the echo statement to
output the text "Hello World".
Comments in PHP
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
# This is a comment
?>
</body>
</html>
3
MODULE 3
(Variables in PHP)
All variables in PHP start with a $ sign symbol. Variables may contain
strings, numbers, or arrays.
Below, the PHP script assigns the string "Hello World" to a variable
called $txt:
<html>
<body>
<?php
$txt="Hello World";
echo $txt;
?>
</body>
</html>
<html>
<body>
<?php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2 ;
?>
</body>
</html>
The output of the script above will be: "Hello World 1234".
4
MODULE 4
The most important thing to notice when dealing with HTML forms and
PHP is that any form element in an HTML page will automatically be
available to your PHP scripts.
Example:
</form>
When the user clicks the "Submit" button, the URL sent could look
something like this:
http://www.w3schools.com/welcome.php?name=Peter&age=37
The "welcome.php" file can now use the $_GET variable to catch the
form data (notice that the names of the form fields will automatically
be the ID keys in the $_GET array):
Note: The HTTP GET method is not suitable on large variable values;
5
the value cannot exceed 100 characters.
The PHP $_REQUEST variable can be used to get the result from form
data sent with both the GET and POST methods.
Example:
Example:
When the user clicks the "Submit" button, the URL will not contain any
form data, and will look something like this:
http://www.w3schools.com/welcome.php
The "welcome.php" file can now use the $_POST variable to catch the
form data (notice that the names of the form fields will automatically
be the ID keys in the $_POST array):
6
Look at the following example of an HTML form:
<html>
<body>
<form action="welcome.php" method="POST">
Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
The example HTML page above contains two input fields and a submit
button. When the user fills in this form and hits the submit button, the
"welcome.php" file is called.
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old!
</body>
</html>
Welcome John.
You are 28 years old!
Note: If the method attribute of the form is GET, then the form
information will be set in $_GET instead of $_POST.
HTML has two methods for passing form variables, POST and GET. GET
displays the input in the URL while POST hides it. Variables passed via
POST are represented by $_POST["{name of input tag}"] GET uses
$_GET[] respectively. Also $_REQUEST[] will take the values of either
POST or GET. $_REQUEST also will return variables passed in a URL
not from a form.
7
MODULE 5
(Conditional Statements)
Conditional statements in PHP are used to perform different
actions based on different conditions.
Conditional Statements
Very often when you write code, you want to perform different actions
for different decisions. You can use conditional statements in your
code to do this.
The If Statement
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
8
echo "Have a nice day!";
?>
</body>
</html>
If more than one line should be executed when a condition is true, the
lines should be enclosed within curly braces:
<html>
<body>
<?php
$x=10;
if ($x==10)
{
echo "Hello<br />";
echo "Good morning<br />";
}
?>
</body>
</html>
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}
Example
9
<html>
<body>
<?php
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>
10
MODULE 6
(Looping)
Looping statements in PHP are used to execute the same block
of code a specified number of times.
Looping
Very often when you write code, you want the same block of code to
run a number of times. You can use looping statements in your code to
perform this.
Syntax
while (condition)
code to be executed;
Example
<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
11
}
?>
</body>
</html>
Syntax
Do
{
code to be executed;
}
while (condition);
Example
The following example will increment the value of i at least once, and it
will continue incrementing the variable i while it has a value of less
than 5:
<html>
<body>
<?php
$i=0;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<5);
?>
</body>
</html>
The for statement is used when you know how many times you want
to execute a statement or a list of statements.
12
Syntax
Note: The for statement has three parameters. The first parameter is
for initializing variables, the second parameter holds the condition, and
the third parameter contains any increments required to implement
the loop. If more than one variable is included in either the
initialization or the increment section, then they should be separated
by commas. The condition must evaluate to true or false.
Example
The following example prints the text "Hello World!" five times:
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
?>
</body>
</html>
Loops over the array given by the parameter. On each loop, the value
of the current element is assigned to $value and the array pointer is
advanced by one - so on the next loop, you'll be looking at the next
element.
Syntax
Example
The following example demonstrates a loop that will print the values of
the given array:
<html>
13
<body>
<?php
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
echo "Value: " . $value . "<br />";
}
?>
</body>
</html>
14
MODULE 7
(ARRAYS)
Simple Arrays
Simply arrays store values in a numerical index.
<?
$array=array("Monday","Tuesday","Wendsday","Thursday",
"Friday","Saturday","Sunday");
For ($a=0; $a < count($array); $a++) {
echo "$array[$a]";
}
?>
The array function inserts the values passed to it into $array. We'll
discuss the for loop later on but what happens is if $a is less than the
number of values in the array $array the value of $array with an index
of $a is displayed. Every time the loop is run the value of $a is
incremented.
15
Associative Arrays
Associative arrays store value data in keys
You can specify an initial key with => and then a list of values.
The values are inserted into the array starting with that key, with
subsequent values having sequential keys:
$days = array(1 => 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday', 'Sunday');
// 2 is Tuesday, 3 is Wednesday, etc.
<?
$assoc=array("name" => "Jon Smith",
"phone" => "555-555-1234",
"address" => "1010 Home Cir",
"city" => "Atlanta",
"state" => "GA",
"zipcode" => "30060");
$assoc["email"]="jon@smith.com";
foreach ($assoc as $key => $value) {
echo "$key : $value - ";
}
?>
We'll get into the foreach loop a little later but for every value of
$assoc it set the key equal to $key and the value to $value and then
used the echo statement to display the values
16
Multidimensional arrays
<?
$info = array("Jon" => array("name" => "Jon Smith","address" => "2 Little
St","city" => "Atlanta","state" => "GA",
"zipcode" => "30060"),
"Bob" => array("name" => "Bob Jones","address" => "725 Big Cir","city" =>
"Miami","state" => "FL",
"zipcode" => "33027"),
"Mark" => array("name" => "Mark Klien","address" => "1315 Riverland
Trace","city" => "Boston","state" => "MA",
"zipcode" => "11083");
?>
Function Description
array() Creates an array
array_change_key_cas Returns an array with all keys in lowercase or
e() uppercase
array_chunk() Splits an array into chunks of arrays
array_combine() Creates an array by using one array for keys and
another for its values
17
array_count_values() Returns an array with the number of occurrences for
each value
array_diff() Compares array values, and returns the differences
18
array_pad() Inserts a specified number of items, with a specified
value, to an array
array_pop() Deletes the last element of an array
array_product() Calculates the product of the values in an array
19
array_walk() Applies a user function to every member of an array
20
sizeof() Alias of count()
sort() Sorts an array
uasort() Sorts an array with a user-defined function and
maintain index association
uksort() Sorts an array by keys using a user-defined function
Constant Description
CASE_LOWER Used with array_change_key_case() to convert array
keys to lower case
CASE_UPPER Used with array_change_key_case() to convert array
keys to upper case
SORT_ASC Used with array_multisort() to sort in ascending
order
SORT_DESC Used with array_multisort() to sort in descending
order
SORT_REGULAR Used to compare items normally
SORT_NUMERIC Used to compare items numerically
SORT_STRING Used to compare items as strings
SORT_LOCALE_STRING Used to compare items as strings, based on the
current locale
COUNT_NORMAL
COUNT_RECURSIVE
EXTR_OVERWRITE
EXTR_SKIP
EXTR_PREFIX_SAME
EXTR_PREFIX_ALL
EXTR_PREFIX_INVALID
EXTR_PREFIX_IF_EXIS
TS
EXTR_IF_EXISTS
EXTR_REFS
21
MODULE 8
(Operators)
Operators are used to operate on values.
PHP Operators
Arithmetic Operators
22
Operator Description Example Result
+ Addition x=2 4
x+2
- Subtraction x=2 3
5-x
* Multiplication x=4 20
x*5
/ Division 15/5 3
5/2 2.5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
Assignment Operators
Comparison Operators
23
<= is less than or equal to 5<=8 returns true
Logical Operators
MODULE 9
(Server Includes)
24
are identical in every way, except how they handle errors. The
include() function generates a warning (but the script will continue
execution) while the require() function generates a fatal error (and the
script execution will stop after the error).
Example 1
<html>
<body>
<p>Some text</p>
</body>
</html>
Example 2
Now, let's assume we have a standard menu file that should be used
on all pages (include files usually have a ".php" extension). Look at the
"menu.php" file below:
<html>
25
<body>
<a href="http://www.w3schools.com/default.php">Home</a> |
<a href="http://www.w3schools.com/about.php">About Us</a> |
<a href="http://www.w3schools.com/contact.php">Contact Us</a>
<p>Some text</p>
</body>
</html>
<html>
<body>
<a href="default.php">Home</a> |
<a href="about.php">About Us</a> |
<a href="contact.php">Contact Us</a>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body>
</html>
The include() function generates a warning (but the script will continue
execution) while the require() function generates a fatal error (and the
script execution will stop after the error).
If you include a file with the include() function and an error occurs,
you might get an error message like the following.
26
<html>
<body>
<?php
include("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
Error message:
Hello World!
Now, let's run the same example with the require() function.
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
Error message:
27
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
The echo statement was not executed because the script execution
stopped after the fatal error.
MODULE 10
(PHP Functions)
28
it.
Example
A simple function that writes my name when it is called:
<html>
<body>
<?php
function writeMyName()
{
echo "Kai Jim Refsnes";
}
writeMyName();
?>
</body>
</html>
<html>
<body>
<?php
function writeMyName()
{
echo "Kai Jim Refsnes";
}
29
?>
</body>
</html>
Hello world!
My name is Kai Jim Refsnes.
That's right, Kai Jim Refsnes is my name.
You may have noticed the parentheses after the function name, like:
writeMyName(). The parameters are specified inside the parentheses.
Example 1
The following example will write different first names, but the same
last name:
<html>
<body>
<?php
function writeMyName($fname)
{
echo $fname . " Refsnes.<br />";
}
</body>
</html>
The output of the code above will be:
30
My name is Hege Refsnes.
My name is Stale Refsnes.
Example 2
<html>
<body>
<?php
function writeMyName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}
</body>
</html>
Example:
<html>
31
<body>
<?php
function add($x,$y)
{
$total = $x + $y;
return $total;
}
</body>
</html>
1 + 16 = 17
Function Description
checkdate() Validates a Gregorian date
date_default_timezone_ Returns the default time zone
get()
date_default_timezone_s Sets the default time zone
et()
date_sunrise() Returns the time of sunrise for a given day /
location
date_sunset() Returns the time of sunset for a given day /
location
date() Formats a local time/date
getdate() Returns an array that contains date and time
information for a Unix timestamp
gettimeofday() Returns an array that contains current time
information
gmdate() Formats a GMT/UTC date/time
gmmktime() Returns the Unix timestamp for a GMT date
32
microtime() Returns the microseconds for the current time
Function Description
header() Sends a raw HTTP header to a client
headers_list() Returns a list of response headers sent (or
ready to send)
headers_sent() Checks if / where the HTTP headers have been
sent
setcookie() Sends an HTTP cookie to a client
setrawcookie() Sends an HTTP cookie without URL encoding
the cookie value
Function Description
ezmlm_hash() Calculates the hash value needed by the
EZMLM mailing list system
mail() Allows you to send emails directly from a
script
PHP Math Functions
Function Description
abs() Returns the absolute value of a number
acos() Returns the arccosine of a number
acosh() Returns the inverse hyperbolic cosine of a
number
asin() Returns the arcsine of a number
33
asinh() Returns the inverse hyperbolic sine of a
number
atan() Returns the arctangent of a number as a
numeric value between -PI/2 and PI/2
radians
atan2() Returns the angle theta of an (x,y) point as
a numeric value between -PI and PI
atanh() radians
Returns the inverse hyperbolic tangent of a
number
base_convert() Converts a number from one base to
another
bindec() Converts a binary number to a decimal
number
ceil() Returns the value of a number rounded
upwards to the nearest integer
cos() Returns the cosine of a number
cosh() Returns the hyperbolic cosine of a number
decbin() Converts a decimal number to a binary
number
dechex() Converts a decimal number to a
hexadecimal number
decoct() Converts a decimal number to an octal
number
deg2rad() Converts a degree to a radian number
exp() Returns the value of Ex
expm1() Returns the value of Ex - 1
floor() Returns the value of a number rounded
downwards to the nearest integer
fmod() Returns the remainder (modulo) of the
division of the arguments
getrandmax() Returns the maximum random number that
can be returned by a call to the rand()
function
hexdec() Converts a hexadecimal number to a
decimal number
hypot() Returns the length of the hypotenuse of a
right-angle triangle
is_finite() Returns true if a value is a finite number
is_infinite() Returns true if a value is an infinite number
is_nan() Returns true if a value is not a number
34
lcg_value() Returns a pseudo random number in the
range of (0,1)
log() Returns the natural logarithm (base E) of a
number
log10() Returns the base-10 logarithm of a number
log1p() Returns log(1+number)
max() Returns the number with the highest value
of two specified numbers
min() Returns the number with the lowest value
of two specified numbers
mt_getrandmax() Returns the largest possible value that can
be returned by mt_rand()
mt_rand() Returns a random integer using Mersenne
Twister algorithm
mt_srand() Seeds the Mersenne Twister random
number generator
octdec() Converts an octal number to a decimal
number
pi() Returns the value of PI
pow() Returns the value of x to the power of y
rad2deg() Converts a radian number to a degree
rand() Returns a random integer
round() Rounds a number to the nearest integer
sin() Returns the sine of a number
sinh() Returns the hyperbolic sine of a number
sqrt() Returns the square root of a number
srand() Seeds the random number generator
tan() Returns the tangent of an angle
tanh() Returns the hyperbolic tangent of an angle
Function Description
addcslashes() Returns a string with backslashes in front
of the specified characters
addslashes() Returns a string with backslashes in front
of predefined characters
bin2hex() Converts a string of ASCII characters to
hexadecimal values
chop() Alias of rtrim()
35
chr() Returns a character from a specified ASCII
value
chunk_split() Splits a string into a series of smaller parts
36
metaphone() Calculates the metaphone key of a string
37
MODULE 11
(PHP Classes)
Introduction
What is a class?
38
$steeringwheel, $windscreen, $lights, $pedals and $brakes. The
functions of a car might include Turnleft(),Turnright() and
Accelerate(). The function "Accelerate()" might take arguments such
as $increase_speed. Now, all of the above describes a car and what a
car does in both real terms and in code.
Now you might ask, couldn't this be done with regular functions and
variables? Yes, it could, especially if you were talking about one car.
But if you are talking about more than one car, then it would be
impossible to keep up with all the various variables and functions
associated with multiple cars. This is where classes become very
useful, because classes bring all those variables and functions under
one name. In this case, it's an object named "car." Now if you have
more than one car, all you have to do is instantiate that object. The
term instantiate basically means making a copy of the object. The new
copy will have all the variables and functions of the original object
available to it. You can include the class in any script that you create;
the class will work the same
• Attributes
• Methods
class class_name{
var $variable_name;
functionfunction_name(){
statements;
}
}
Notice that within the class you use the var keyword to identify your
variables. At this point you can also assign a value to your variables.
Try to use the same naming conventions as you would for functions. It
is easier to recognize what a class is if it reflects its purpose(e.g. class
Human_class{). Another keyword, $this, is used to refer to the
39
instances of an object and its attributes e.g. $this->$variable_name.
To instantiate a class means to create a new version of it. Say we
have a class called dog, to instantiate it, we do this:
Now, rex will have all the attributes of the class dog.
Creating a Class
Script: sample_class.php:
<?
class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
$jude = new human();
echo "Jude has " .$jude->legs." legs";
?>
Here we have a new object created from our human class, called jude.
We also have a simple result saying how many legs Jude has. Note
how the variable "legs"(declared in the class) is used without the dollar
sign in the echo statement.
<?
class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
$jude = new human();
< style="color: red;" lang="EN-GB">$jude-
>legs++; //increase legs by one
echo "Jude has " .$jude->legs." legs";
?>
40
OUTPUT:
<?
class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
< style="color: navy;" lang="EN-GB">$jude = new human();
< style="color: navy;" lang="EN-GB">$jane = new human();
< style="color: red;" lang="EN-GB">$jude-
>legs++; //increase legs by one
echo "Jude has " .$jude->legs." Legs<br>";
echo "Jane has " .$jane->legs." legs";
?>
Output:
As you can see from the result, we can modify the instance of a class
without touching the class definition itself. This re-usability is what
makes classes so useful.
Now we can also add a new attribute to any of the objects (jane or
jude). For example, let's add a new attribute to jane. The attribute is
hair color:
<?
class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
$jude = new human();
41
$jane = new human();
< style="color: red;" lang="EN-GB">$jane->haircolor="brown";
$jude->legs++; //increase legs by one
echo "Jude has " .$jude->legs." Legs<br>";
echo "Jane has ".$jane->haircolor." Hair and was created from the
class <b>".get_class($jane)."</b> She also has <b>".$jane->legs."
</b>legs";
?>
So if we wanted to do the same thing for jude, we have to type all that
out again, which is time consuming. Instead, we are going to
automate this process by creating a function that will report on both
jane and jude. So let's change the class to include this function:
<?
class human{
var $legs=2;
< style="color: red;" lang="EN-GB">function report(){
< style="color: red;" lang="EN-GB">return "This <b>".get_class
($this)."</b> has <b>" .$this->haircolor. "</b> hair,and
<b>" .$this->legs. "</b> legs<br>" ;
}
}
//instantiate the class
$jude = new human();
$jane = new human();
$jane->haircolor="brown";
$jude->haircolor="black";
$jude->legs++; //increase legs by one
echo $jane->report();
echo $jude->report();
?>
Constructor Functions
function class_name(){
statements
}
Yes, the constructor function name must be the same as the class
name. And within the function you can include all the attributes that
are going to be included when an instance of the class is made. So,
let's add a constructor function that will sort out our problem:
42
<?
class human{
function human($hcolor){
$this->hcolor=$hcolor;
}
var $legs=2;
function report(){
return "This <b>".get_class($this)."</b> has <b>" .$this-
>haircolor. "</b> hair,and <b>" .$this->legs. "</b> legs<br>" ;
}
}
//instantiate the class
$jude = new human();
$jane = new human();
$jane->haircolor="brown";
$jude->haircolor="black";
$jude->legs++; //increase legs by one
echo $jane->report();
echo $jude->report();
?>
<?
class human{
function human($hcolor){
$this->hcolor=$hcolor;
}
var $legs=2;
function report(){
return "This <b>".get_class($this)."</b> has <b>" .$this-
>hcolor. "</b> hair,and <b>" .$this->legs. "</b> legs<br>" ;}
}
//instantiate the class
$jude = new human("black");
$jane = new human("brown");
$jude->legs++; //increase legs by one
echo $jane->report();
echo $jude->report();
?>
43
MODULE 12
(Cookies)
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that
the server embeds on the user's computer. Each time the same
computer requests a page with a browser, it will send the cookie too.
With PHP, you can both create and retrieve cookie values.
Syntax:
PHP cookies can be set using the setcookie() function. The syntax is as
follows:
44
• [value] The cookie value. It is associated with the cookie
name.
• [expire] The time after which the cookie should expire in
seconds
• [path] Specifies the exact path on the domain that can use the
cookies.
• [domain] The domain that the cookie is available. If not
domain is specified, the default value is the value of the domain
in which cookie was created.
• [security] Specifies whether the cookie will be sent via HTTPS.
A value of 1 specifies that the cookie is sent over a secure
connection but it doesn't mean that the cookie is secure. It's
just a text file like every other cookie. A value of 0 denotes a
standard HTTP transmission.
Example:
<?
//print a cookie
echo $_COOKIE[‘user’];
print_r($_COOKIE);
?>
<html>
<body>
<?php
45
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?></html></body>
Delete example:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
MODULE 13
(Session)
When you are working with an application, you open it, do some
changes and then you close it. This is much like a Session. The
computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: the web
server does not know who you are and what you do because the HTTP
address doesn't maintain state.
46
information on the server for later use (i.e. username, shopping items,
etc). However, session information is temporary and will be deleted
after the user has left the website. If you need a permanent storage
you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store
variables based on this UID. The UID is either stored in a cookie or is
propagated in the URL.
<html>
<body>
</body>
</html>
The code above will register the user's session with the server, allow
you to start saving user information, and assign a UID for that user's
session.
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
47
</html>
Output:
Pageviews=1
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
If you wish to delete some session data, you can use the unset() or
the session_destroy() function.
<?php
unset($_SESSION['views']);
?>
<?php
session_destroy();
?>
Note: session_destroy() will reset your session and you will lose all
your stored session data.
48
MODULE 14
(File Handling)
Since we want to create a file, we must supply a file name and tell PHP
that we want to write to the file. Note: We have to tell PHP we are
writing to the file, otherwise it will not create a new file.
49
PHP Code:
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
• $ourFileName = "testFile.txt";
This bit of code actually has two parts. First we use the function
fopen and give it two arguments: our file name and we inform
PHP that we want to write by passing the character "w".
• fclose($ourFileHandle);
We close the file that was opened. fclose takes the file handle
that is to be closed. We will talk more about this more in the file
closing lesson.
PHP - Permissions
If you are trying to get this program to run and you are having errors,
you might want to check that you have granted your PHP file
access to write information to the hard drive. Setting permissions
is most often done with the use of an FTP program to execute a
command called CHMOD. Use CHMOD to allow the PHP file to
write to disk, thus allowing it to create a file.
Opening a File
50
The first parameter of this function contains the name of the file to be
opened and the second parameter specifies in which mode the file
should be opened in:
<html>
<body>
<?php
$f=fopen("welcome.txt","r");
?>
</body>
</html>
w Write only. Truncates the file (overwriting it). If the file doesn't exist,
fopen() will try to create the file
w+ Read/Write. Truncates the file (overwriting it). If the file doesn't exist,
fopen() will try to create 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
Read/Append. File pointer at the end of the file. If the file doesn't exist,
a+
fopen() will try to create 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
Example
<html>
<body>
<?php
if (!($f=fopen("welcome.txt","r")))
exit("Unable to open file!");
?>
</body>
</html>
51
Closing a File
In PHP it is not system critical to close all your files after using them
because the server will close all files after the PHP code finishes
execution. However the programmer is still free to make mistakes
(i.e. editing a file that you accidentally forgot to close). You should
close all files after you have finished with them because it's a good
programming practice and because we told you to!
fclose($f);
EXAMPLE:
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open
file");
fclose($ourFileHandle);
The function fclose requires the file handle that we want to close down.
In our example we set our variable "$fileHandle" equal to the file
handle returned by the fopen function.
After a file has been closed down with fclose it is impossible to read,
write or append to that file unless it is once more opened up with the
fopen function.
Writing to a file
Now that you know how to open and close a file, lets get on to the
most useful part of file manipulation, writing! There is really only one
main function that is used to write and it's logically called fwrite.
Before we can write information to our test file we have to use the
function fopen to open the file for writing.
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
We can use php to write to a text file. The fwrite function allows data
to be written to any type of file. Fwrite's first parameter is the file
handle and its second parameter is the string of data that is to be
written. Just give the function those two bits of information and you're
52
good to go! Below we are writing a couple of names into our test file
testFile.txt and separating them with a carriage return.
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
The $fh variable contains the file handle for testFile.txt. The file handle
knows the current file pointer, which for writing, starts out at the
beginning of the file.
We wrote to the file testFile.txt twice. Each time we wrote to the file
we sent the string $stringData that first contained Bobby Bopper and
second contained Tracy Tanner. After we finished writing we closed the
file using the fclose function.
Bobby Bopper
Tracy Tanner
The fread function is the staple for getting data out of a file. The
function requires a file handle, which we have, and an integer to tell
the function how much data, in bytes, it is supposed to read.
EXAMPLE:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
echo $theData;
Display:
Flopp
The first five characters from the testFile.txt file are now stored inside
53
$theData. You could echo this string, $theData, or write it to another
file.
If you wanted to read all the data from the file, then you need to get
the size of the file. The filesize function returns the length of a file, in
bytes, which is just what we need! The filesize function requires the
name of the file that is to be sized up.
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
if (feof($f))
echo "End of file";
Reading a Character
Note: After a call to this function the file pointer has moved to the
next character.
Example
The example below reads a file character by character, until the end of
file is true:
<?php
if (!($f=fopen("welcome.txt","r")))
exit("Unable to open file.");
while (!feof($f))
{
$x=fgetc($f);
echo $x;
}
fclose($f);
?>
Deleting a File
54
You know how to create a file. You know how to open a file in an
assortment of different ways. You even know how to read and write
data from a file! Now it's time to learn how to destroy (delete) files.
In PHP you delete files by calling the unlink function.
File Unlink
When you view the contents of a directory you can see all the files that
exist in that directory because the operating system or application that
you are using displays a list of filenames. You can think of these
filenames as links that join the files to the directory you are currently
viewing. If you unlink a file, you are effectively causing the system to
forget about it or delete it!
Before you can delete (unlink) a file, you must first be sure that it is
not open in your program. Use the fclose function to close down an
open file.
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);
$myFile = "testFile.txt";
unlink($myFile);
HTML Code:
<form enctype="multipart/form-data" action="uploader.php"
method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br
/>
<input type="submit" value="Upload File" />
55
</form>
Save that form code into a file and call it upload.html. If you view it in
a browser it should look like this:
• The file is too large and you do not want to have it on your
server.
• You wanted the person to upload a picture and they uploaded
something else, like an executable file (.exe).
• There were problems uploading the file and so you can't keep it.
This example is very simple and omits the code that would add such
functionality.
The $_FILES array is where PHP stores all the information about files.
There are two elements of this array that we will need to understand
for this example.
56
• uploadedfile - uploadedfile is the reference we assigned in our
HTML form. We will need this to tell the $_FILES array which file
we want to play around with.
• $_FILES['uploadedfile']['name'] - name contains the original
path of the user uploaded file.
• $_FILES['uploadedfile']['tmp_name'] - tmp_name contains
the path to the temporary file that resides on the server. The file
should exist on the server in a temporary directory with a
temporary name.
Now we can finally start to write a basic PHP upload manager script!
Here is how we would get the temporary file name, choose a
permanent name, and choose a place to store the file.
NOTE: You will need to create a new directory in the directory where
uploader.php resides, called "uploads", as we are going to be saving
files there.
We now have all we need to successfully save our file to the server.
$target_path contains the path where we want to save our file to.
$target_path = "uploads/";
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'],
$target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try
again!";
}
57
If the upload is successful, then you will see the text "The file filename
has been uploaded". This is because $move_uploaded_file returns true
if the file was moved, and false if it had a problem.
If there was a problem then the error message "There was an error
uploading the file, please try again!" would be displayed.
MODULE 15
(Introduction to MySQL)
What is MySQL?
MySQL is a database. A database defines a structure for storing
information.
In a database, there are tables. Just like HTML tables, database tables
contain rows, columns, and cells.
Database Tables
A database most often contains one or more tables. Each table has a
58
name (e.g. "Customers" or "Orders"). Each table contains records
(rows) with data.
Queries
A query is a question or a request.
With MySQL, we can query a database for specific information and have a
recordset returned.
The query above selects all the data in the LastName column in the Persons
table, and will return a recordset like this:
LastName
Hansen
Svendson
Pettersen
59
Connecting to a MySQL Database
Before you can access and work with data in a database, you must create a
connection to the database.
Syntax
mysql_connect(servername,username,password);
Parameter Description
servername Optional. Specifies the server to connect to.
Default value is "localhost:3306"
username Optional. Specifies the username to log in with.
Default value is the name of the user that owns
password the serverSpecifies
Optional. process the password to log in with.
Default is ""
Note: There are more available parameters, but the ones listed above are
the most important. Visit our full PHP MySQL Reference for more details.
Example
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
60
Closing a Connection
The connection will be closed as soon as the script ends. To close the
connection before, use the mysql_close() function.
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
Create a Database
The CREATE DATABASE statement is used to create a database in MySQL.
Syntax
CREATE DATABASE database_name
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example
61
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_close($con);
?>
Create a Table
The CREATE TABLE statement is used to create a database table in MySQL.
Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
.......
)
Example
The following example shows how you can create a table named "person",
with three columns. The column names will be "FirstName", "LastName" and
"Age":
62
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>
Note: When you create a database field of type varchar, you must specify
the maximum length of the field, e.g. varchar(15).
63
decimal(size,d) Hold numbers with fractions. The maximum number of
double(size,d) digits can be specified in the size parameter. The
float(size,d) maximum number of digits to the right of the decimal is
specified in the d parameter
64
Primary Keys and Auto Increment Fields
Each table should have a primary key field.
A primary key is used to uniquely identify the rows in a table. Each primary
key value must be unique within the table. Furthermore, the primary key
field cannot be null because the database engine requires a value to locate
the record.
The primary key field is always indexed. There is no exception to this rule!
You must index the primary key field so the database engine can quickly
locate rows based on the key's value.
The following example sets the personID field as the primary key field. The
primary key field is often an ID number, and is often used with the
AUTO_INCREMENT setting. AUTO_INCREMENT automatically increases the
value of the field by 1 each time a new record is added. To ensure that the
primary key field cannot be null, we must add the NOT NULL setting to the
field.
Example
mysql_query($sql,$con);
The INSERT INTO statement is used to insert new records into a database
table.
Syntax
65
You can also specify the columns where you want to insert the data:
Note: SQL statements are not case sensitive. INSERT INTO is the same as
insert into.
Example
mysql_select_db("my_db", $con);
mysql_close($con);
?>
66
<html>
<body>
</body>
</html>
When a user clicks the submit button in the HTML form in the example
above, the form data is sent to "insert.php". The "insert.php" file connects
to a database, and retrieves the values from the form with the PHP $_POST
variables. Then, the mysql_query() function executes the INSERT INTO
statement, and a new record will be added to the database table.
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
67
The SELECT statement is used to select data from a database.
Syntax
SELECT column_name(s)
FROM table_name
Note: SQL statements are not case sensitive. SELECT is the same as select.
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example
The following example selects all the data stored in the "Person" table (The
* character selects all of the data in the table):
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysql_close($con);
?>
68
The example above stores the data returned by the mysql_query() function
in the $result variable. Next, we use the mysql_fetch_array() function to
return the first row from the recordset as an array. Each subsequent call to
mysql_fetch_array() returns the next row in the recordset. The while loop
loops through all the records in the recordset. To print the value of each
row, we use the PHP $row variable ($row['FirstName'] and
$row['LastName']).
Peter Griffin
Glenn Quagmire
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Firstname Lastname
69
Glenn Quagmire
Peter Griffin
To select only data that matches a specified criteria, add a WHERE clause to
the SELECT statement.
Syntax
SELECT column FROM table
WHERE column operator value
Operator Description
= Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
Note: SQL statements are not case sensitive. WHERE is the same as where.
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example
The following example will select all rows from the "Person" table, where
FirstName='Peter':
70
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?>
Peter Griffin
Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name
Note: SQL statements are not case sensitive. ORDER BY is the same as
order by.
Example
The following example selects all the data stored in the "Person" table, and
sorts the result by the "Age" column:
71
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br />";
}
mysql_close($con);
?>
Glenn Quagmire 33
Peter Griffin 35
SELECT column_name(s)
FROM table_name
ORDER BY column_name1, column_name2
72
The UPDATE statement is used to modify data in a database table.
Syntax
UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value
Note: SQL statements are not case sensitive. UPDATE is the same as
update.
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_close($con);
?>
After the update, the "Person" table will look like this:
73
FirstName LastName Age
Peter Griffin 36
Glenn Quagmire 33
The DELETE FROM statement is used to delete rows from a database table.
Syntax
DELETE FROM table_name
WHERE column_name = some_value
Note: SQL statements are not case sensitive. DELETE FROM is the same as
delete from.
To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL
connection.
Example
74
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_close($con);
?>
MODULE 16
(MySQL Functions)
75
Function Description
mysql_affected_rows() Returns the number of affected rows in the previous
MySQL operation
mysql_change_user() Deprecated. Changes the user of the current MySQL
connection
mysql_client_encoding() Returns the name of the character set for the current
connection
mysql_close() Closes a non-persistent MySQL connection
76
mysql_field_flags() Returns the flags associated with a field in a
recordset
mysql_field_len() Returns the maximum length of a field in a recordset
77
mysql_tablename() Deprecated. Returns the table name of field. Use
mysql_query() instead
mysql_thread_id() Returns the current thread ID
mysql_unbuffered_query Executes a query on a MySQL database (without
() fetching / buffering the result)
78