Lab Sheet 2
Lab Sheet 2
PHP
1. Basics
PHP is a scripting language designed for web application development. PHP interpreter
resides on the server side with the web server. PHP code can be embedded into HTML to
generate dynamic contents. PHP statements are enclosed in <?php and ?> tag. Most of PHP
syntax is inspired from C programming language.
<!DOCTYPE html>
<html>
<head>
<title>Basic PHP</title>
</head>
<body>
<?php
echo "<h1>Hello, World</h1>";
echo "10 + 20 = ";
echo 10+20;
echo "\n";
?>
</body>
</html>
1
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
On a client’s request, the above HTML page with embedded PHP code is passed to the PHP
interpreter. The interpreter then interprets part of the code surrounded with <?php and ?>
<!DOCTYPE html>
<html>
<head>
<title>Basic PHP</title>
</head>
<body>
<h1>Hello, World</h1>10 + 20 = 30
</body>
</html>
(there can be many of these), generates the output according to what the code does
(printing “Hello, World” in this case), and puts the result back to the HTML page. In the
end, this PHP code yields the following HTML code.
2. Variables
Variables in PHP are denoted by a dollar sign followed by the variable name. The variable
name is case-sensitive, and may compose of alphabets, digits or underscore, but it must
not start with a digit.
<?php
$x = 10;
$y = 'Hello';
$z = $x.$y; // . is used to concatenate strings
echo $z;
//output: 10Hello
?>
3. Strings
We can use both single quotes and double quotes to enclose string literals in PHP. However,
they yield different results.
• A single-quoted string is used for representing a simple string constant. It does not
recognize escape sequences such as \r, \n, except \' for a single quote, and \\ for
a backslash.
• A double-quoted string recognizes all types of escape sequences, as well as variable
substituting.
<?php
$name = 'John';
$age = 20;
$txt = "His name is $name. He is \"{$age}\" years old.";
echo $txt;
//output: His name is John. He is "20" years old.
?>
Strings can be accessed the same way as in the case of arrays. Notice the use of
<?php
$str = "SIIT, TU";
echo $str[0].$str[1].$str[2].$str[3].$str[strlen($str)-1];
//output: SIITU
?>
2
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
4. Arrays
An array in PHP is an ordered map associating key and value. That is, an array in PHP can
act as both usual array and a hash table. In addition to being dynamic in its size, PHP
arrays are inhomogeneous i.e., values of different types can be stored in the same array.
<?php
$arr = array('foo' => 'bar', 12 => true);
The following code demonstrates how PHP arrays can be used in an index-based manner.
<!DOCTYPE html>
<html>
<body>
<?php
$arr = array('a', 2,'b', 'c', 10);
for($i=0; $i < count($arr); ++$i){
echo $arr[$i] . '<br>';
}
?>
</body>
</html>
This prints out a, 2, b, c, 10 on a separate line. Note that index of arrays in PHP starts
from 0. The function count($arr) can be used to find the size of array $arr.
5. If Statement
<!DOCTYPE html>
<html>
<body>
<?php $a = 10; ?>
<?php if ($a == 10) { ?>
<p>The condition is true.</p>
<?php } else { ?>
<p>The condition is false.</p>
<?php } ?>
</body>
</html>
Notice that PHP also allows a dynamic opening and closing of <?php and ?>. In the code
above, “<p>The condition is true.</p>” will be printed out.
3
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
We can write an if statement in an alternative version which is different from C syntax. This
alternative syntax somehow makes the PHP code become clearer and easier to read when
many PHP statements are embedded in HTML page.
<!DOCTYPE html>
<html>
<body>
<?php $a = 10; ?>
<?php if ($a == 10): ?>
<p>The condition is true.</p>
<?php else: ?>
<p>The condition is false.</p>
<?php endif; ?>
</body>
</html>
In multiple nested if-else statements, you may use both “else if” and “elseif” in the C
syntax above. However, in the latter one (i.e. colon syntax), only “elseif” is accepted.
6. While Statement
<!DOCTYPE html>
<html>
<body>
<table border="1">
<?php $i = 1; ?>
<?php while($i <= 10) { ?>
<tr><td><?= $i?></td><td><?= str_repeat("*", $i) ?></td></tr>
<?php $i++; ?>
<?php } ?>
</table>
</body>
</html>
This gives
There is also another version of the while statement using : which gives the same result.
4
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
<!DOCTYPE html>
<html>
<body>
<table border="1">
<?php $i = 1; ?>
<?php while($i <= 10): ?>
<tr><td><?= $i?></td><td><?= str_repeat("*", $i) ?></td></tr>
<?php $i++; ?>
<?php endwhile; ?>
</table>
</body>
</html>
7. For Statement
<!DOCTYPE html>
<html>
<body>
<table border="1">
<?php for($i=1; $i<=10; $i++): ?>
<tr><td><?= $i?></td><td><?= str_repeat("*", $i) ?></td></tr>
<?php endfor; ?>
</table>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php $arr = array('Peter' => 10, 'John' => 15,
'Somsak' => 22, 'Sarah' => 12); ?>
<table border="1">
<?php foreach($arr as $key => $value): ?>
<tr><td><?= $key?></td><td>
<?= str_repeat("*", $value) ?></td></tr>
<?php endforeach; ?>
</table>
</body>
</html>
In each iteration, $key and $value are respectively assigned to the key and the value of an
element in the array. Thus, the code gives the following output.
5
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
8. Query String
Query string is a part of URL that comes after the file name. It is used to pass parameters
to a PHP script file. For example, http://localhost/test.php calls 'test.php' without
passing any parameter. But, http://localhost/test.php?a=10&b=20 passes two
parameters: a=10 and b=20. Passing parameters to the script in this way is referred to as a
“GET request”. These two parameters can be accessed in PHP script through a global
variable $_GET.
<!DOCTYPE html>
<html>
<body>
<?php if (isset($_GET['a']) && isset($_GET['b'])): ?>
<?= $_GET['a'] ?> + <?= $_GET['b'] ?>
= <?= $_GET['a']+$_GET['b'] ?>
<?php else: ?>
Please specify the values of a and b.
<?php endif; ?>
</body>
</html>
isset() is used to check if a variable is available, or if a value has been passed into the
script. When passing a=10 and b=20 to the code above, the output is 10 + 20 = 30
9. Useful Functions
trim($str)
Strip whitespaces (including newlines and tabs) from the beginning and end of a string.
rand($min, $max)
Return a random integer from $min to $max (inclusive). rand() is automatically seeded.
6
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
10 More on PHP
In the previous lab, we have already covered basic constructs in PHP i.e., branching,
statements, iteration, and arrays. Using these basic constructs, you have already created a
fairly simple dynamically generated web page. To facilitate the creation of an even more
complicated system, in this lab, we will dive deeper into some more commonly used
functions in the standard PHP library. We will also introduce the basic concept of object-
oriented programming (OOP) in PHP, as well as how to define classes and create objects in
PHP. Understanding of classes and objects in PHP will allow you to quickly reuse many
more 3rd-party libraries written by other people.
<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n='default_value'){
echo "Example function.<br>";
$retval = ...;
return $retval;
}
?>
Any valid PHP code may appear inside a function, even other functions and class definitions.
Function names follow the same rules as other labels in PHP. A valid function name starts
with a letter or underscore, followed by any number of letters, numbers, or underscores.
Any type of values can be returned with the return keyword. Also, only one value can be
returned. If multiple values are needed to be returned, they can be put in an array first,
then return the array instead.
PHP also supports optional arguments when defining a function. Here is an example.
<?php
There are two arguments needed to call plus(), namely $x and $y. When both of them are
specified, the specified values are used for $x and $y. If only one argument is present, it is
used as the value for $x, and $y is set to 5. Note that optional arguments must come after
mandatory arguments. So, in general, you may want to position variables that have default
values towards the end of the argument list.
Breaking a big system into its smaller components, and implementing them with functions
are common practice in procedural programming. To promote reusability, it is useful to
group these functions into a file and include them when needed. This can be done in PHP
7
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
<?php
// require "lib/library.php";
require_once "lib/library.php";
As you might have already known, PHP allows both “ (double quotes) and „ (single quote)
to be used to specify a string. However, there are some subtle differences between the two
in interpreting characters in the string. The following code will help you in understanding
the differences.
<?php
echo '1. String with single quote <br>';
echo "2. String with double quotes <br>";
echo 'There are
two new lines
in HTML source <br>';
The code will give the following output (already rendered by a web browser).
8
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
In short, double quotes “interpret” special characters a single quote does not. Note that in
the output above, some characters like new lines cannot be seen after the browser renders
them, because they collapsed to a single space. You are advised to try the code by yourself.
Make sure to check the raw output of the produced result (not just rendered result).
Another difference of single and double quotes is variable expansion. With single quote,
variables are not expanded, while double quoted strings will have all variable names
replaced with their values.
<?php
$x = 'here';
echo "Expand with \" like $x <br>";
echo 'Will not expand with \' like $x';
?>
9
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
There are many useful functions which can help you locate bugs quickly.
<?php
?>
When you really cannot catch bugs, putting the following code at the beginning of the main
file may help.
// Turn on displaying errors
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
This will result in more details of errors and notices (potential bugs) produced.
print_r($expression)
print_r() displays information about a variable in a way that is readable by humans. This is
useful for checking whether or not a variable is properly assigned, as the whole structure
will be printed (work even for a nested array).
<?php
$a = array ('a' => 'apple', 'b' => 'banana',
'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
10
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)
You may need to wrap the output in a <pre>..</pre> tag to preserve spaces and newlines.
var_dump($expression) is also another function with similar functionality.
Primitive-typed (int, string) variables in PHP are passed to a function by value, meaning
that their values are copied to the receiving function. Unlike in C, arrays in PHP are also
passed by value. Locally changing a value of the variable which was passed by value does
not have any effect once the function returns. Here is a demonstration.
<?php
$x = 1;
fake_change($x);
echo "After fake_change: ". $x . "<br>";
real_change($x); # Caller side does not need &
echo "After real_change: ". $x . "<br>";
function fake_change($n){
$n = 100;
}
function real_change(&$n){
# There is no return here.
$n = 100;
}
?>
After fake_change: 1
After real_change: 100
.
In order to use a pass by reference, the receiving side must have & prepended to the
variable (&$n in this case). The use of & to denote a variable‟s reference can also be used
without a function like this.
In short, the statement $a = &$b simply means “$a and $b can be used interchangeably”,
as opposed to $a = $b which means “assign the value of $b to $a”.
11
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
Since PHP is an interpreted language, variable interpretation is done at runtime. This allows
a dynamic variable reference (variable variables). Variable variables refer to act of
accessing a variable by using the value of another one. Here is a demonstration
<?php
$x = 'hello';
$hello = 'PHP';
echo $x; // print: hello
echo '<br>';
echo $$x; //print: PHP
?>
Here $$x is not the same as $x. While just $x simply gives „hello‟, with $$x, PHP will first
interpret $x to be „hello‟, which leaves us with $hello. Then, the value in $hello is obtained,
which is „PHP‟ in this case.
The same trick can actually be used to call a function using a variable‟s value to specify the
function name to call.
<?php
$a = 'foo';
$a(); //Same as directly writing foo()
function foo(){
echo 'foo is called!';
}
?>
Dynamically calling functions like this may save us from writing a lot of if-else statements
because the value obtained can be used to directly call a function.
Until now, statements are grouped together into a so called “function” or “procedure”.
Grouping statements into such individual unit has many advantages over inline code. This
includes:
• The semantic of the underlying sequence of statements is labeled with the function
name.
• Reusability and maintainability are promoted.
• Functions act as an abstraction of complicated operations. Users of a well-written
function do not need to care much about how it works as long as it works.
Objects take this concept a step further by incorporating both functions (called “methods”)
and the data (called “properties”) they use, into a single structure called a class. A class
is the template from which objects are created. Programming by organizing real-world
entities into classes, and modeling their actions as methods is referred to as “Object-
oriented Programming (OOP)”.
For example, a class “Human” may have eat(), sleep(), work() as their associated methods.
This basically says that all objects (people) of this class can at least do the action “eat”,
12
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
“sleep”, and “work”. In OOP, although objects from the same class behave similarly, each
object is treated as a unique existence i.e., just like people. In this case, the class “Human”
may have a property “name” as its identity.
Class definitions can be put anywhere in the code, before or after the statements that use
them. Defining a class in PHP is done with the class keyword as follows. The class
definition syntax is similar to that of many popular programming languages e.g., Java,
C++.
<?php
$p = new Person('Smith');
print_r($p); // Output: Person Object ( [name:private] => Smith )
//echo $p->name; //Error: Cannot access private property
class Person{
private $name;
function construct($n){
// construct() is a special function for object constructor
$this->set_name($n);
// $this->name = $n; // is also fine.
}
function get_name(){
return $this->name;
}
function set_name($n){
$this->name = $n;
}
}?>
Here we defined a class Person which has “name” as its property. The property is marked
with the keyword private so that directly accessing the property from outside the class will
give an error. Marking properties as private and providing a getter-setter method (in this
case get_name() and set_name()) is considered a good practice (encapsulation).
construct() is a special function representing the constructor of the class. In this case,
the constructor of class Person also takes one argument, and assigns the value to the
property name using the set_name() method. Notice that the use of $this keyword in
$this->set_name($n) and $this->name is necessary to access the properties or methods
defined in the class scope.
As mentioned before, a class is just a template for objects. To actually use it, an object has
to be created with the new keyword, followed by the class name. If the class constructor
requires parameters, they must be enclosed in parentheses () i.e., new Person(„Smith‟). If
the constructor does not require any parameter, then parentheses are optional. Say, the
class Apple‟s constructor does not require a parameter. Then, both new Apple or new
Apple() are valid for creating an Apple object.
As a side note, any function in PHP starting with two underscores is considered special, and
is referred to as a magic method. Prefixing a newly created function name with two
underscores is completely valid, but is discouraged since it is misleading. Also, in the past,
the constructor function can be named with the class name, just like in Java. However, in
the future version of PHP, naming a method with the class name will not be treated as a
constructor anymore. It will instead be treated as a usual method. So, to create a
constructor, the magic method constructor() should be used.
13
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
Usual properties (instance properties) belong to objects not classes. In the case of the
Person class, each object has its separated “name” property. That is, changing the value of
“name” property of one object does not affect the value in another object. However,
occasionally we may need to maintain data about a whole class. Specifically, we want all
objects of a class to share the same piece of data. This can be achieved through the use of
static keyword.
For example, let‟s say we would like to count the number of Person objects created in the
program. This can be done as follows.
<?php
$people = array(new Person('Smith'), new Person('Yamada'));
$c = Person::person_count(); // $c is 2
class Person{
private static $count = 0;
private $name;
function construct($n){
$this->set_name($n);
//Person::$count++ // is also fine
self::$count++;
}
static function person_count(){
//return Person::$count // is also fine
return self::$count;
}
function get_name(){
return $this->name;
}
function set_name($n){
$this->name = $n;
}
}
?>
In the class definition, we have added a static property called $count (private static
$count = 0) initialized to 0, to keep track of how many Person objects are created. Every
time a new Person object is created, the count is incremented by one (self::$count++;).
In order to access a static method/property, the method/property has to be prefixed with
its class name followed by :: (called scope resolution operator) e.g., Person::. So,
Person::$count would mean the static variable $count defined in Person class. In the
case of accessing such static methods/properties within the same class, the class name
may be replaced with the self keyword, which literally means the class in the current
context.
In the code, two Person objects have been created in the first line into an array. Then,
Person::person_count(); is used to query for the count. person_count() is a static
method which returns the value of $count. So, at the end, $c will contain the value 2.
Notice that if $count is not declared static, then counting Person objects in this way will not
work because each object will have its own $count which will always contain the value 1
(i.e., each object counts itself only once). Apart from being static, $count is also declared
private to prevent code outside the class to change its value.
14
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
There are many occasions in which we need another class which is very similar to an
existing one. Instead of copying the whole class definition, and modifying it, it is better to
create the new class by extending from the original one. Creating a new class in this way is
called “sub-classing”, and is done with extends keyword. There are many advantages with
this approach over redefining the whole thing from scratch.
• Besides additional properties/methods defined in the sub-class, the non-private
properties/methods of the super-class (parent) are automatically inherited.
• The change of definition of the super-class is automatically propagated to its sub-
classes.
• Less coding is involved.
Here is an example of an extended version of Person class which can keep “age”.
function get_age(){
return $this->age;
}
function set_age($a){
$this->age = $a;
}
}
The new class AgePerson extends the Person class by adding the property $age. Sub-
classing Person automatically gives AgePerson the methods get_name(), set_name(), as
well as person_count(). The constructor of AgePerson class explicitly calls the constructor
of Person class by using parent:: construct($n); which also passes $n (name) along.
The parent refers to the super-class (parent class) of the current class, and is the
counterpart of self keyword. Without the statement parent:: construct($n); the
$name property will not be initialized with $n i.e., $name will be blank. Since the
constructor of Person is also called, creation of an AgePerso object will also increment the
count of Person objects. This actually makes sense since “An AgePerson is also a Person”.
So, it should also be counted. The method person_count() is also inheritied to AgePerson
class. In this case, AgePerson::person_count() is exactly the same as
Person::person_count().
11.4 Visibility
PHP provides three keywords to control access to properties or methods of a class. They
are public, protected, and private.
• public allows a direct access from anywhere, inside or outside a class. Methods are
declared as public by default. Sub-classes also inherit public properties/methods
from its parent.
15
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
Object passing works the same way as most other programming languages i.e. Java. A
variable which contains an object is merely a reference to the object. Assigning a variable
containing an object to another variable just results in the same object having two
references. That is, no new object is created or cloned. Here is a code to demonstrate this.
$a = new Person('John');
$b = $a;
print_r($b); //Output: Person Object ( [name:private] => John )
$b->set_name('Dave');
echo '<br>';
print_r($a); //Output: Person Object ( [name:private] => Dave )
It can be seen in the code that $a refers to a Person object. The statement $b = $a;
simply means “assign to $b the same object that $a contains”. You can imagine the object
as an apple, and imagine variables $a, and $b as your hands. In the beginning, one of your
hand ($a) grabs the apple ($a = new Person('John');). We make the other hand ($b)
grab the same apple with the statement $b = $a;. Since the two hands are grabbing the
exact same apple, if the apple is changed in some ways, both hands should feel it. That is
why in this code, even though we change the name through $b with
$b->set_name('Dave');, the change is also seen in $a.
In the case of passing objects to a function, the change made to the objects inside the
function will retain even after the function returns. To prevent the original object from
being changed in a function, we can just create a new object and pass it to the function.
This section lists a few useful functions in PHP. There are many other functions offered in
the standard library.
explode()
array explode ( string $delimiter , string $string)
Split $string into many substrings. $delimiter is a string to be used as the delimiter
(splitting points). $delimiter will not be included in the returned array.
$str = 'Paul,24,A+';
// $pieces = explode(',', $str); // $pieces is an array of 3 elements
list($name, $age, $grade) = explode(',', $str);
echo "Name: $name <br>";
echo "Age: $age <br>";
echo "Grade: $grade <br>";
16
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
Name: Paul
Age: 24
Grade: A+
The list construct is a useful trick to assign multiple values from an array into a list of
variables.
join(), implode()
string implode ( string $glue , array $pieces )
join() is an alias of implode(). They do the same thing. implode() joins array elements
$pieces with $glue. The function can be considered as a reverse operation of explode().
trim()
string trim ( string $str)
Return a string with whitespace (including newlines) stripped from the beginning and end
of $str. This is useful in processing form input as users may accidentally put some spaces
before of after, say, their username.
serialize()
string serialize ( mixed $value )
Generates a storable string representation of a value. This is useful for storing or passing
PHP values (e.g. integers, arrays, objects) around without losing their type and structure.
To make the serialized string into a PHP value again, use unserialize().
unserialize()
mixed unserialize ( string $str )
unserialize() takes a single serialized variable and converts it back into a PHP value.
sprintf()
string sprintf ( string $format [, mixed $args [, mixed $... ]] )
Returns a string produced according to the formatting string $format.
Each conversion specification consists of a percent sign (%), followed by one or more of
these elements, in order:
1. An optional sign specifier that forces a sign (- or +) to be used on a number. By
default, only the - sign is used on a number if it's negative. This specifier forces
positive numbers to have the + sign attached as well.
2. An optional padding specifier that says what character will be used for padding
the results to the right string size. This may be a space character or a 0 (zero
character). The default is to pad with spaces. An alternate padding character can
be specified by prefixing it with a single quote (').
3. An optional alignment specifier that says if the result should be left-justified or
right-justified. The default is right-justified; a - character here will make it left-
justified.
17
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
4. An optional number, a width specifier that says how many characters (minimum)
this conversion should result in.
5. An optional precision specifier in the form of a period („.‟) followed by an optional
decimal digit string that says how many decimal digits should be displayed for
floating-point numbers. When using this specifier on a string, it acts as a cutoff
point, setting a maximum character limit to the string.
6. A type specifier that says what type the argument data should be treated as.
Possible types:
• % - a literal percent character. No argument is required.
• b - the argument is treated as an integer, and presented as a binary number.
• c - the argument is treated as an integer, and presented as the character with
that ASCII value.
• d - the argument is treated as an integer, and presented as a (signed) decimal
number.
• e - the argument is treated as scientific notation (e.g. 1.2e+2). The precision
specifier stands for the number of digits after the decimal point.
• E - like %e but uses uppercase letter (e.g. 1.2E+2).
• u - the argument is treated as an integer, and presented as an unsigned
decimal number.
• f - the argument is treated as a float, and presented as a floating-point
number (locale aware).
• F - the argument is treated as a float, and presented as a floating-point
number (non-locale aware). g - shorter of %e and %f.
• G - shorter of %E and %f.
• o - the argument is treated as an integer, and presented as an octal number.
• s - the argument is treated as and presented as a string.
• x - the argument is treated as an integer and presented as a hexadecimal
number (with lowercase letters).
• X - the argument is treated as an integer and presented as a hexadecimal
number (with uppercase letters).
sprintf() works exactly the same way as printf(). With printf() the result is printed instead
of returning as a string. Here are some examples.
$s = 'monkey';
$t = 'many monkeys';
18
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
[monkey]
[ monkey]
[monkey ]
[0000monkey]
[####monkey]
[many monke]
$n = 4395;
$u = -4395;
$c = 65; // ASCII 65 is 'A'
%b = '1000100101011'
%c = 'A'
%d = '4395'
%e = '4.395000e+3'
%u = '4395'
%u = '4294962901'
%f = '4395.000000'
%o = '10453'
%s = '4395'
%x = '112b'
%X = '112B'
%+d = '+4395'
%+d = '-4395'
in_array()
bool in_array ( mixed $v , array $arr)
Check if the value $v exists in the array $arr. in_array()‟s search is case-sensitive.
file_exists()
bool file_exists ( string $filename )
19
CSS 326 Database Programming Laboratory: (Laboratory #2)
PHP
htmlentities()
string htmlentities ( string $string )
Convert all applicable characters to HTML entities. This function is useful when you need to
display HTML‟s special characters like „<‟, „>‟ as is. For example, when outputting „<b>‟
from PHP, the web browser would interpret „<b>‟ as being a tag to make text bold.
However, in the case that you really want to print out „<b>‟ as is, you should use
htmlentities(‘<b>’)
This will output <b> which renders as „<b>‟ on the screen.
13 File Manipulation
Reading and writing to a file is an essential part in any system. Although a MySQL
database can replace files in most cases, it is still essential to know how to read and write
file in PHP.
In this very brief introduction, we will use only four functions to read and write files.
Specifically, we use fopen() to open a file for mainly for writing. The writing is done with
fwrite(). After we finish writing (presumably each line represents one record), the file is
closed with fclose(). Data in the file is read back with file() function, which automatically
reads all the content into an array. Each element of the array corresponds to a line in the
file, with the newline still attached.
Here is a general coding pattern of how an array can be written to a file, with each element
on one line.
$records = array(
array('John', 24),
array('Steve', 25)
);
// 'w' places the file pointer at the beginning of the file (replace).
// 'a' places the file pointer at the end of the file (append).
$f = fopen('testfile.txt', 'w');
foreach($records as $rec){
$line = implode(',', $rec) . "\n";
fwrite($f, $line); //write: name,age\n
}
fclose($f);
In the code, $records is the array we want to write to the file. The file „testfile.txt‟ is
opened with fopen() with the mode „w‟. The mode „w‟ is used to write to a new file (or
replace an existing one). fopen() then returns a file pointer $f which we can use with
fwrite() for an actual writing. Note that we have to append “\n” for a newline to be
written. At the end, we close the file pointer with fclose(). After the code is executed, the
file „testfile.txt‟ will be created with the content shown as follows.
John,24
Steve,25
To read the content back to an array, the following code can be used.
20
CSS 326 Database Programming Laboratory: (Laboratory #2) PHP
$lines = file('testfile.txt');
foreach($lines as $line){
list($name, $age) = explode(',', $line);
// $age contains newline at the end.
// Remove it.
$age = trim($age);
$records[] = array($name, $age);
}
As you can see, writing to a file in this way requires implode(), and reading the data back
requires explode(). Make sure you understand them along with fopen(), fwrite(),
fclose(), and file().
21