Essential Unit II
Essential Unit II
UNIT – II
SCRIPTING ESSENTIALS
Prepared by
VERIFIED BY
1
UNIT II SCRIPTING ESSENTIALS 9
Need for Scripting languages – Types of scripting languages – Client side scripting – Server
side scripting – PHP – Working principle of PHP – PHP Variables – Constants – Operators –
Flow Control and Looping – Arrays – Strings – Functions – File Handling – PHP and MySQL
– PHP and HTML – Cookies – Simple PHP scripts
2
UNIT II
SCRIPTING ESSENTIALS
Scripting languages
Types of scripting languages
Client/ Server side scripting
PHP
Working principle of PHP
PHP Variables
Constants
Operators
Functions
File Handling
PHP and MySQL
PHP and HTML
Cookies
3
PART - A
4
PART – B
5
PART - A
Disadvantage:
6
Creating a pop-up window to display information in a separate window from the web
page that triggered it.
Validating the content of fields: when filling in forms, each field, especially required
fields denoted by an asterisk, are validated for correct input.
6. What are the new way used by javascript to interact with users?
Hypertext Mark-up Language (HTML) use to create a web document and HTML tags to
describe how you want your document formatted and the browser obeys your commands and
shows the formatted document to the user. Because HTML is a simple text mark-up language, it
can’t respond to the user, make decisions, or automate repetitive tasks.
The server side environment that runs a scripting language is a web server.
A users request is fulfilled by running a script directly on the web server to generate
dynamic HTML pages. This HTML is then sent to the client browser.
7
It is usually used to provide interactive web sites that interface to databases or other
data stores on the server.
8
Numbers (0....9)
Special Symbols (like $, #, &, @ ,- etc)
9
PART B
Advantages:
Disadvantage:
10
The user is probably unaware of anything devious occurring. This is a weakness and
major drawback in the formal rules defining scripting languages like JavaScript and
VBScript.
Image or text rollovers: If the user rolls the mouse over a graphic or hypertext then a text or
graphic box will appear:
Creating pop-up window to display information in a separate window from the web page that
triggered it. This is useful if the user requires performing a simple calculation or consulting a
calendar for inputting dates. This is achieved by embedding ActiveX controls or Java applets into
the script.
Validating the content of fields: when filling in forms each field, especially required fields
denoted by an asterisk, are validated for correct input. If the field if left blank or incorrect
information entered then a user message will be generated and you may not continue.
The client-side environment used to run script is usually a browser. The processing takes
place on the end users computer. The source code is transferred from the web server to the
user’s computer over the internet and run directly in the browser. The scripting language needs to
be enabled on the client computer.
Client side programming has mostly to do with the user interface, with which the user
interacts. In web development its the browser, in the user machine, that runs the code, and its
mainly done in java script, flash, etc. This code must run in a variety of browsers.
Client side scripting environment needed to create, test, run, and access client-side scripts,
such as browsers, editors, graphic packages and as well as other utilities and tools that enable
these tasks. The World Wide Web (WWW) began as a text-only medium-the first browsers didn’t
even support images within web pages.
11
Hypertext Mark-up Language (HTML) use to create a web document and HTML tags to
describe how you want your document formatted and the browser obeys your commands
and shows the formatted document to the user.
Because HTML is a simple text mark-up language, it can’t respond to the user, make
decisions, or automate repetitive tasks.
Interactive tasks such as these require a more sophisticated language: a programming
language or a scripting language.
Although many programming languages are complex, scripting languages are generally
simple.
They have a simple syntax, can perform tasks with a minimum of commands, and are easy
to learn.
Web scripting languages enable you to combine scripting with HTML to create interactive
web pages.
Introducing JavaScript
JavaScript was originally called live Script and was introduced in Netscape
Navigator 2.0 in 1995. Netscape Navigator was an early browser that held a large share of
the browser market. It was soon renamed JavaScript to indicate a marketing relationship
with sun’s Java language.
JavaScript is almost as easy to learn as HTML, and it can be included directly in HTML
documents and following are a few of the things than can be done with JavaScript:
Display message to the user as part of a web page, in the browsers status line or in
alert boxes.
Validate the contents of a form and make calculations.
Animate images or create images that change when you move the mouse over them.
Create and banners that interact with the user, rather than simply displaying a graphic.
12
Detect the browser in use or its features and perform advanced functions only on
browser that support them.
Detect installed plug-ins and notify the user if a plug-in is required.
Modify all or part of a web page without requiring the user to reload it.
Display or interact with data retrieved from a remote server.
Tools for scripting: the first tool need to work with JavaScript is a text editor. Javascript
scripts are stored in simple text files, usually as part of html documents. Any editor than can
store ASCII text files will work.
A variety of dedicated HTML editors is also available and will work with JavaScript. In fact ,
many include features specially for javascript for example, color-coding the various
javascript statements to indicate their purposes or even creating simple script
automatically.
13
Run client-side script : it needs two other things to work with javascript: a web browser and
a computer to run on it.
Browsers
If we are developing a web application using a client-side scripting language than you will
need to ensure cross compatibility amongst browser.
Javascript and VSBscript, the online materials you are reading will focus on javascript
as this language is available across a variety of browsers.
VSBscript is developed by Microsoft and is available only on the internet explorer
browsers.
Editors
Any text editor can be used to write JavaScript code. You can also use some of the
large development packages such as Microsoft Visual Studio, or Adobe Dreamweaver.
The editor used in this tutorial will be programmers notepad. This is an open source
package and is available from http://www.pnotepad.org/
Graphic packages
One use for a client-side language is to perform image replacement when the user
interacts with an object. This can be used to create feedback to the user when the
cursor hovers over a link or menu item.
For good effect, you may need to edit and create the images. Examples for a mouse
over effect, a button click effect and mouse out effect.
Server-side scripting
14
request to the website. The alternative is for the web server itself to deliver a static web
page. Scripts can be written in any of number of server-side scripting languages that are
available.
ASP (*.asp)
ActiveVFP (*.avfp)
ASP.NET (*.aspx)
ASP.NET MVC (*.cshtml)
ColdFusion Markup Language (*.cfm)
Go (*.go)
Google Apps Script (*.gs)
Hack (*.php)
Haskell (*.hs)
PHP (*.php, *.php3, *.php4, *phtml)
SMX (*.smx)
Tcl (*.tcl)
webDNA (*.dna, *.tpl)
Bigwig (*.wig)
Server-side scripting is often used to provide a customized interfaced for the user.
These scripts may assemble client characteristics for use in customizing the response
based on those characteristics, the users requirements, access rights, etc.
Server-side scripting also enables the website owner to hide the source code that
generates the interface, whereas with client-side scripting, the user has access to all the
code received by the client.
15
A down-side to the use of server-side scripting is that the client needs to make further
requests over the network to the server in order to show new information to the user via
the web browser.
These requests can slow down the experience for the user, place more load on the
server, and prevent use of the application when the user is disconnected from the
server.
When the server serves data in a commonly used manner, for example according to the
HTTP or FTP protocols, users may have their choice of a number of client programs.
In the case of more specialized applications, programmers may write their own server,
client, and communications protocol that can only be used with one another.
Programs that run on a users local computer without ever sending or receiving data
over a network are not considered clients, and so the operations of such programs
would not be considered client-side operations.
Server-side scripting was most exclusively performed by using a combination of C
programs, Perl scripts, and shell scripts using the Common Gateway Interface (CGI).
Those scripts were executed by the operating system, and the results were served back
by the web server. many Modern web servers can directly execute on-line scripting
languages such as ASP, JSP, Perl, PHP and Ruby either by the web server itself or via
extension modules to the web server.
For example, WebDNA includes its own embedded database system.
Either form of scripting can be used to build up complex multi-page site, but direct
execution usually results in less overhead because of the lower number of calls to
external interpreters.
Dynamic websites sometimes use custom web application servers, such as Glass-fish,
Plack and Pythons “Base HTTP Server” library, although some may not consider this to
be server-side scripting.
16
For a users action to trigger the execution of server-side code, for example, a developer
working with classic ASP must explicitly cause the users browser to make a request
back to the web server.
Creating such interactions can easily consume much development time and lead to
unreadable code.
Server-side scripts are completely processed by the server instead of clients.
When clients request a page containing server-side scripts, the applicable server
processes the scripts and returns an HTML page to the client.
Variables
A variable is a symbol that can store different values at different times. For example,
suppose you create a web-based calculator capable of performing mathematical tasks.
Variable Declaration A variable always begins with a dollar sign, $, which is then followed
by the variable name. Variable names follow the same naming rules as identifiers. That is,
a variable name can begin with either a letter or an underscore and can consist of letters,
underscores, numbers, or other ASCII characters rangingfrom 127 through 255. The
following are all valid variables:
$color
$operating_system
$_some_variable
model
Note that variables are case sensitive. For instance, the following variables bear no relation
to one another:
$color
$Color
$COLOR
17
Value Assignment
$color = "red";
$number = 12;
$age = 12;
$sum = 12 + "15"; //
$sum = 27.
Reference Assignment
<?php
$value1 = "Hello"; $value2 =& $value1;
// $value1 and $value2 both equal "Hello" $value2 = "Goodbye";
// $value1 and $value2 both equal "Goodbye"
?>
An alternative reference-assignment syntax is also supported, which involves
appending the ampersand to the front of the variable being referenced.
The following example adheres to this new syntax:
<?php
$value1 = "Hello";
18
$value2 = &$value1;
// $value1 and $value2 both equal "Hello" $value2 = "Goodbye";
// $value1 and $value2 both equal "Goodbye"
?>
Variable Scope
Local variables
Function parameters
Global variables
Static variables
Local Variables
<?php
$x = 4; function assignx () {
$x = 0; print "\
$x inside function is
19
?>
This will produce the following result − $x inside function is 0. $x outside of function is 4.
Function Parameters
Function parameters are declared after the function name and inside
parentheses. They are declared much like a typical variable would be
<?php
// multiply a value by 10 and return it to the caller
function multiply ($value) {
$value = $value * 10;
return $value;
}
$retval = multiply (10);
Print "Return value is $retval\n";
?>
Global Variables
20
Variable Variables
On occasion, you may want to use a variable whose content can be treated
dynamically as a variable in itself. Consider this typical variable assignment:
$recipe = "spaghetti";
Interestingly, you can treat the value spaghetti as a variable by placing a
second dollar sign in front of the original variable name and again assigning another
value:
$$recipe = "& meatballs";
This in effect assigns & meatballs to a variable named spaghetti. Therefore,
the following two snippets of code produce the same result:
echo $recipe $spaghetti;
echo $recipe ${$recipe};
The result of both is the string spaghetti & meatballs.
Constants
A constant is a value that cannot be modified throughout the execution of a
program. Constants are particularly useful when working with values that definitely
will not require modification, such as Pi (3.141592) or the number of feet in a mile
(5,280). Once a constant has been defined, it cannot be changed (or redefined) at
any other point of the program. Constants are defined using the define() function.
21
The constant is subsequently used in the following listing:
printf("The value of Pi is %f", PI);
$pi2 = 2 * PI;
printf("Pi doubled equals %f", $pi2);
Expressions
An expression is a phrase representing a particular action in a program. All
expressions consist of at least one operand and one or more operators.
A few examples follow:
$a = 5;
// assign integer value 5 to the variable $a
$a = "5"; // assign string value "5" to the variable $a
$sum = 50 + $some_int;
// assign sum of 50 + $some_int to
$sum
$wine = "Zinfandel"; //
assign "Zinfandel" to the variable $wine $inventory++; //
increment the variable $inventory by 1
Operators :
Operators are used to perform operations on variables and values. PHP divides
the operators in the following groups:
Arithmetic operators
Assignment operators
22
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Arithmetic Operators:
Assignment Operators:
23
Comparison Operators:
Increment/Decrement Operators:
24
Logical Operators :
String Operators:
25
Array Operators :
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.
Syntax:
if (condition) {
26
}
if...else statement - executes some code if a condition is true and another code if the
condition is false
Syntax:
if (condition) {
} else {
false
Syntax:
if (condition) {
} elseif (condition) {
} else {
27
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
} else {
?>
</body>
</html>
Syntax:
switch (n) {
28
case label1:
break;
case label2:
break;
case label3:
break;
...
default:
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$favcolor = "red";
switch ($favcolor) {
29
case "red":
break;
case "blue":
break;
case "green":
break;
default:
?>
</body>
</html>
Loops :
Often when you write code, you want the same block of code to run over and
over again in a row. Instead of adding several almost equal code-lines in a script, we
can use loops to perform a task like this.
30
In PHP, we have the following looping statements:
while - loops through a block of code as long as the specified condition is true
Syntax:
code to be executed;
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
while($x <= 5) {
$x++;
?>
31
</body>
</html>
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
Syntax:
do {
code to be executed;
The for loop is used when you know in advance how many times the script should run.
Parameters:
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
Syntax:
32
Example:
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.
Syntax:
code to be executed;
33
Example:
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
Installation
The array functions are part of the PHP core. There is no installation needed to use
these functions.
34
The following array functions are the part of the PHP core so you can use these
functions within your script without any further installation
Function Description
array() Create an array
Changes the case of all keys in an array (either
array_change_key_case()
lowercase or uppercase)
array_chunk() Split an array into chunks of arrays
Return the values from a single column in the input
array_column()
array
Creates an array by using one array for keys and
array_combine()
another for its values
array_count_values() Counts all the values of an array
array_diff() Compare arrays values, and returns the differences
Compare arrays keys and values, and returns the
array_diff_assoc()
differences
array_diff_key() Compare arrays keys, and returns the differences
Compare arrays keys and values, using a user-defined
array_diff_uassoc()
key comparison function, and returns the differences
Compare array keys, using a user-defined key
array_diff_ukey()
comparison function, and returns the differences
array_fill() Fill an array with values
array_fill_keys() Fill an array with values, specifying keys
Filters elements of an array using a user-defined
array_filter()
function
Flips or Exchanges all keys with their associated
array_flip()
values in an array
array_intersect() Compare arrays values, and returns the matches
Compare arrays keys and values, and returns the
array_intersect_assoc()
matches
35
Function Description
array_intersect_key() Compare arrays keys, and returns the matches
Compare arrays keys and values, using a user-defined
array_intersect_uassoc()
key comparison function, and returns the matches
An array is a data structure that stores one or more similar type of values in a single value.
For example if you want to store 100 numbers then instead of defining 100 variables its easy to
define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c
which is called array index.
Numeric array − An array with a numeric index. Values are stored and accessed in linear
fashion.
Associative array − An array with strings as index. This stores element values in association
with key values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are accessed
using multiple indices
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function
reference.
<html>
<body>
36
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
</body>
</html>
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
37
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they
are different in terms of their index. Associative array will have their index as string so that you can
establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be
the best choice. Instead, we could use the employees names as the keys in our associative array,
and the value would be their respective salary.
NOTE − Don't keep associative array inside double quote while printing otherwise it would not
return any value.
Example
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
38
</body>
</html>
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array are
accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in three
subjects −
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
39
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
?>
</body>
</html>
40
STRING:
NOTE − Built-in string functions is given in function reference PHP String Functions
Singly quoted strings are treated almost literally, whereas doubly quoted strings
replace variables with their values as well as specially interpreting certain character
sequences.
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
print($literally);
?>
There are no artificial limits on string length - within the bounds of available memory, you
ought to be able to make arbitrarily long strings.
41
Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP
Certain character sequences beginning with backslash (\) are replaced with special
characters
Variable names (starting with $) are replaced with string representations of their values.
To concatenate two string variables together, use the dot (.) operator
<?php
$string1="Hello World";
$string2="1234";
42
?>
If we look at the code above you see that we used the concatenation operator two
times. This is because we had to insert a third string.
Between the two string variables we added a string with a single character, an empty
space, to separate the two variables.
<?php
echo strlen("Hello world!");
?>
12
The length of a string is often used in loops or other functions, when it is important to know
when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the
string)
The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match. If no
match is found, it will return FALSE.
43
Let's see if we can find the string "world" in our string −
<?php
echo strpos("Hello world!","world");
?>
As you see the position of the string "world" in our string is position 6. The reason
that it is 6, and not 7, is that the first position in the string is 0, and not.
PHP FUNCTIONS:
PHP functions are similar to other programming languages. A function is a piece of code
which takes one more input in the form of parameter and does some processing and returns a
value.
You already have seen many functions like fopen() and fread() etc. They are built-in
functions but PHP gives you option to create your own functions as well.
In fact you hardly need to create your own PHP function because there are already more
than 1000 of built-in library functions created for different area and you just need to call them
according to your requirement.
Please refer to PHP Function Reference for a complete set of useful functions.
It very easy to create your own PHP function. Suppose you want to create a PHP
function which will simply write a simple message on your browser when you will call it.
44
Following example creates a function called writeMessage() and then calls it just after
creating it.
Note that while creating a function its name should start with keyword function and
all the PHP code should be put inside { and } braces as shown in the following example
below −
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}
</body>
</html>
PHP gives you option to pass your parameters inside a function. You can pass as
many as parameters your like. These parameters work like variables inside your function.
45
Following example takes two integer parameters and add them together and then print
them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
Any changes made to an argument in these cases will change the value of the original
variable. You can pass an argument by reference by adding an ampersand to the variable name
in either the function call or the function definition.
46
Following example depicts both the cases.
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
Original Value is 10
Original Value is 16
47
PHP Functions returning value:
A function can return a value using the return statement in conjunction with a value
or object. return stops the execution of the function and sends the value back to the calling
code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then
returns their sum to the calling program. Note that return keyword is used to return a value
from a function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
</body>
</html>
48
Returned value from the function : 30
You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function printMe($param = NULL) {
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
This is test
It is possible to assign function names as strings to variables and then treat these variables
exactly as you would the function name itself. Following example depicts this behaviour.
49
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello() {
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
Hello
File handling is an important part of any web application. You often need to
open and process a file for different tasks.
PHP has several functions for creating, reading, uploading, and editing files.
The readfile() function reads a file and writes it to the output buffer.
50
Assume we have a text file called "webdictionary.txt", stored on the server, that looks like
this:
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
Open a file for write only. Erases the contents of the file or creates a new file if it
w
doesn't exist. File pointer starts at the beginning of the file
Open a file for write only. The existing data in file is preserved. File pointer starts at the
a
end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
Open a file for read/write. Erases the contents of the file or creates a new file if it
w+
doesn't exist. File pointer starts at the beginning of the file
Open a file for read/write. The existing data in file is preserved. File pointer starts at the
a+
end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
The first parameter of fread() contains the name of the file to read from and the second
parameter specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
51
PHP Close File - fclose()
It's a good programming practice to close all files after you have finished with them.
You don't want an open file running around on your server taking up resources!
The fclose() requires the name of the file (or a variable that holds the filename) we
want to close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
The example below outputs the first line of the "webdictionary.txt" file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
Note: After a call to the fgets() function, the file pointer has moved to the next line.
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
52
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
The example below reads the "webdictionary.txt" file character by character, until
end-of-file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
Note: After a call to the fgetc() function, the file pointer moves to the next character.
File Create/Write
In this chapter we will teach you how to create and write to a file on the server.
53
PHP Create File - fopen()
The fopen() function is also used to create a file. Maybe a little confusing, but in
PHP, a file is created using the same function used to open files.
If you use fopen() on a file that does not exist, it will create it, given that the file is opened
for writing (w) or appending (a).
The example below creates a new file called "testfile.txt". The file will be created in the
same directory where the PHP code resides:
Example
If you are having errors when trying to get this code to run, check that you have
granted your PHP file access to write information to the hard drive.
The first parameter of fwrite() contains the name of the file to write to and the second
parameter is the string to be written.
The example below writes a couple of names into a new file called "newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
54
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the
string $txt that first contained "John Doe" and second contained "Jane Doe". After we finished
writing, we closed the file using the fclose() function.
John Doe
Jane Doe
PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open an
existing file for writing. All the existing data will be ERASED and we start with an empty file.
In the example below we open our existing file "newfile.txt", and write some new data into
it:
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
If we now open the "newfile.txt" file, both John and Jane have vanished, and only the data
we just wrote is present:
55
Mickey Mouse
Minnie Mouse
PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open an
existing file for writing. All the existing data will be ERASED and we start with an empty file.
In the example below we open our existing file "newfile.txt", and write some new data into
it:
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
If we now open the "newfile.txt" file, both John and Jane have vanished, and only the
data we just wrote is present:
Mickey Mouse
Minnie Mouse
However, with ease comes danger, so always be careful when allowing file uploads!
56
Configure The "php.ini" File
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
Next, create an HTML form that allow users to choose the image file they want to
upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Without the requirements above, the file upload will not work.
57
9. Explain detail about the Cookie in PHP.
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
Only the name parameter is required. All other parameters are optional.
The following example creates a cookie named "user" with the value "John Doe".
The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available
in entire website (otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable
$_COOKIE). We also use the isset() function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400
= 1 day
?>
<html>
<body>
58
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie()
instead).
To modify a cookie, just set (again) the cookie using the setcookie() function:
Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
59
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
60
Check if Cookies are Enabled
The following example creates a small script that checks whether cookies are
enabled. First, try to create a test cookie with the setcookie() function, then count the
$_COOKIE array variable:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
61
MySQL uses standard SQL
The data in a MySQL database are stored in tables. A table is a collection of related data, and it
consists of columns and rows.
Databases are useful for storing information categorically. A company may have a database with the
following tables:
Employees
Products
Customers
Orders
PHP combined with MySQL are cross-platform (you can develop in Windows and
serve on a Unix platform)
Database Queries
We can query a database for specific information and have a recordset returned.
62
SELECT LastName FROM Employees
The query above selects all the data in the "LastName" column from the
"Employees" table.
The Hypertext Markup Language or HTML is the oldest and most commonly used method of
creating web pages.
It is very simple and just within a few minutes; a coder can easily create a simple web page
with text and a couple of images.
You can do the same with PHP since its output gets processed by HTML and if you inserted
the same HTML code you would also get the same result.
This is due to the fact that the end product of PHP code, and what gets sent to the browser is
in HTML.
So the browser would get the same HTML code if you set it as the output of your PHP script,
but if you want to take advantage of the advanced features that PHP offers you would need to
spend a little bit more time.
Coding in HTML means that the pages you code would always appear the same depending on
which browser you are using. PHP allows the coder to create an HTML page or section of it
dynamically.
As an example, if you want to create a site that would display all the letters of the alphabet
individually in its own page, you would need to create a page for each letter if you are using
HTML but you would only need one page with PHP.
PHP is also capable of taking data and use or manipulate it to create the output that the user
desires. A web page that can take two numbers, add it, and present the result to the user is
very easy to do with PHP but not with HTML.
63
Because of the additional features of PHP, it needs to implement a proper structure in coding.
Unlike HTML where anything you put in creates an output, PHP would not give you an output if
something is wrong with your code.
You would need a considerably longer time to learn PHP than in learning HTML though you
would still need to learn HTML to learn PHP.
The first thing to understand is the need to use PHP code delimiters to mark
the areas of PHP code within the web page.
By default, the opening delimiter is <?php and the closing delimiter is ?>.
You can insert as many or as few blocks of PHP into a web page as you need
as long as each block is marked by the opening and closing delimiters.
A sample PHP script block would, therefore, appear in an HTML file as follows:
<?php
echo '<p>This is a PHP script</p>';
?>
64
Testing the PHP Installation
Before embarking on even the simplest of examples, the first step on the road to
learning PHP is to verify that the PHP module is functioning on your web server.
To achieve this, we will create a small PHP script and upload it to the web server.
To do this start up your favorite editor and enter the following PHP code into it:
<?php
phpInfo();
?>
This PHP script calls the built-in PHP phpInfo() function, the purpose of which to
output information about the PHP pre-processing module integrated into your web server.
Save this file as phpInfo.php and upload it to a location on your web server
where it will be accessible via a web browser.
Once you have done this open a browser and go to the URL for this file.
If all is well with your PHP installation you will see several pages of detailed
information about your PHP environment covering topics such as how and
when the PHP module was built, the version of the module and numerous
configuration settings.
If you do not see this information it is possible you do not have the PHP
module integrated into your web server.
If you use a web hosting company, check with them to see if your particular
hosting package includes PHP support (sometimes PHP support is only
provided with premium hosting packages so you may need to upgrade).
If you run your own web server consult the documentation for your particular
type of server (Apache, Microsoft IIS etc) for details on integrating the PHP
module.
65
There are vastly superior resources available on the internet to assist in
installing PHP than we could never match in this book.
As you may have realized, by testing the PHP module on your web server you have
already crafted your first PHP script.
We will now go on to create another script that is embedded into an HTML page.
Open your editor and create the following HTML file:
<html>
<head>
<?php
66
echo '<title>My First PHP Script</title>';
?>
</head>
<body>
<?php
echo '<p>This content was generated by PHP</p>';
?>
<p>And this content is static HTML</p>
</body>
</html>
Save this file as example.php and upload it to your web server. When you load this page
into your browser you should see something like the following:
If you see something like the above in your browser then you have
successfully created and executed your first embedded HTML script.
If you do not see the expected output in your browser window then go back
and check your file.
As you will learn with experience, problems are almost always the result of
subtle mistakes in entering the PHP code.
67
Embedding HTML into a PHP Script
In the previous example we embedded some PHP scripts into an HTML web
page.
We can reverse this by putting the HTML tags into the PHP commands.
The following example contains a PHP script which is designed to output the
HTML necessary to display a simple page.
As with the previous examples, create this file, upload it to your web server
and load it into a web browser:
<?php
echo "<html>\n";
echo "<head>\n";
echo "<title>My Second PHP Example</title>\n";
echo "</head>\n";
echo "<body>\n";
echo "<p>Some Content</p>\n";
echo "</body>\n";
echo "</html>\n";
?>
When you load this into your browser it will be as if all that was in the file was HTML,
and if you use the view page source feature of your browser the HTML is, infact, all you will
see.
This is because the PHP pre-processor simply created the HTML it was told to
create when it executed the script:
<html>
<head>
<title>My Second PHP Example</title>
68
</head>
<body>
<p>Some Content</p>
</body>
</html>
69