0% found this document useful (0 votes)
175 views69 pages

Essential Unit II

The document discusses scripting languages and PHP. It covers types of scripting languages like Perl, Hypertalk, Lingo, Applescript, JavaScript, and VBScript. It discusses client-side and server-side scripting. For PHP, it outlines variables, constants, operators, functions, file handling, PHP and MySQL, and cookies. It provides questions and answers about scripting languages and PHP concepts.

Uploaded by

karthickamsec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
175 views69 pages

Essential Unit II

The document discusses scripting languages and PHP. It covers types of scripting languages like Perl, Hypertalk, Lingo, Applescript, JavaScript, and VBScript. It discusses client-side and server-side scripting. For PHP, it outlines variables, constants, operators, functions, file handling, PHP and MySQL, and cookies. It provides questions and answers about scripting languages and PHP concepts.

Uploaded by

karthickamsec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

I YEAR / II SEMESTER (INFORMATION TECHNOLOGY)

IT8201- INFORMATION TECHNOLOGY ESSENTIALS

UNIT – II

SCRIPTING ESSENTIALS

Prepared by

M.RANJITHKUMAR, M.E., (AP/IT)

VERIFIED BY

HOD PRINCIPAL CORRESPONDENT

SENGUNTHAR COLLEGE OF ENGINEERING – TIRUCHENGODE

DEPARTMENT OF INFORMATION TECHNOLOGY

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

1. Define script language.


2. What are the types of scripting language?
3. State advantage and disadvantage of scripting language.
4. What are the uses of scripting languages?
5. What is the client side scripting language?
6. What are the new way used by javascript to interact with users?
7. List the different type of test client side script.
8. Differentiate between client side environment and server side environment.
9. What are the methods used to implement client side scripts?
10. Define PHP.
11. What is the different type of coding style of PHP?
12. How PHP program executed?
13. Write the structure of PHP.
14. What is echo system?

4
PART – B

1. Explain detail about Types of scripting languages.


2. Explain detail about Client - Side Scripting.
3. Explain about the Server-Side Scripting.
4. Explain detail about PHP Variables.
5. Explain detail about Constants in PHP.
6. Explain detail about Operators and Conditional Statements in PHP.
7. Explain about Arrays in PHP.
8. Write about the file handling in PHP?
9. Explain detail about the Cookie in PHP.
10. Explain About The PHP MySQL Database.
11. Write to Creating a Simple PHP Script?

5
PART - A

1. Define script language.


A scripting or script language is a programming language that supports scripts:
programs written for a special run-time environment that automate the execution of tasks
that could alternatively be executed one-by-one by a human operator.

2. What are the types of scripting language?


 Perl
 Hypertalk
 Lingo
 Applescript
 Javascript
 VSBScript
3. State advantage and disadvantage of scripting language.
Advantage:

 Easy to learn and use.


 Minimum programming knowledge or experience required.
 Allow complex tasks to be performed in relatively few steps.

Disadvantage:

 Executable code can inadvertently be downloaded from a remote server to a web


browsers machine, installed and run using the local browsers interpreter.
 This is easily done by visiting dubious web sites or downloading programs without valid
authenticity.
 The user is probably unaware of anything devious occurring.

4. What are the uses of scripting languages?


 Image or text rollovers: if the user rolls the mouse over a graphic or hypertext then a
text or graphic box will appear.

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.

5. What is the client side scripting language?


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.

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.

7. List the different type of test client side script.


Test Client-side Scripts
 Run Client-side Scripts
 Access Client-side Scripts

8. Differentiate between client side environment and server side environment.


Client side environment:
 The client side environment used to run scripts is usually a browser.
 The processing takes place on the end users computer.
 The source code is transferred from web server to the user computer over the internet
and run directly in the browser.

Server side environment:

 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.

9. What are the methods used to implement client side scripts?


 Between a pair of script tags.
 From an external file specified by the src attribute of a script tag.
 In an event handler, specified as the value of an HTML attribute such as onclick or
onmouseover.
 In a URL that uses the special javascript:protocol.

10. Define PHP.


PHP is a general-purpose scripting language that is especially suited to server-side web
development, in which case PHP generally runs on a web server. any PHP code in a
requested file is executed by the PHP runtime, usually to create dynamic web page content or
dynamic images used on websites or elsewhere.

11. What are the different type of coding style of PHP?


Traditional coding style
 Short Tags
 HTML Script tag
 ASP Coding Style

12. How PHP program executed?


<?php
echo”Hello DiscussDesk”;
echo”Lets Learn PHP:
?>

13. Write the structure of PHP.


PHP is a scripting language, so the scripts which you create using PHP needs not to be
complied rather its interpreted directly on the go at run time.
PHP supports following set of characters.
 Letters (a....z, A....Z)

8
 Numbers (0....9)
 Special Symbols (like $, #, &, @ ,- etc)

14. What is echo system?


Echo system is used to display something on the webpage or browser.
 echo statement can display one or more strings.
 Echo statement can be used with or without parenthesis().
 The word echo is a keyword. Keywords in PHP are used not case sensitive and
hence we can write it anyway. For eg: echo, Echo, EcHo etc.
Echo statements can be used to display strings, values of variables.

9
PART B

1. Explain detail about Types of scripting languages

Types of scripting languages

Specialized scripting languages include:


 Perl (Practical Extraction and Report Language). This is a popular string processing
language for waiting small scripts for system administrators and web site maintainers.
Much web development is now done using Perl.
 Hypertalk is another example. It is the underlying scripting language of HyperCard.
 Lingo is the scripting language of Macromedia Director, an authoring system for develop
high performance multimedia content and applications for CDs, DVDs and the Internet.
 AppleScript, a scripting language for the Macintosh allows the user to send commands to
the operating system to, for example open applications, and carry out complex data
operations.
 JavaScript, perhaps the most publicized and well-known scripting language was initially
developed by Netscape as LiveScript to allow more functionality and enhancement to web
page authoring that raw HTML could not accommodate.
 VBScript, a cut-down version of visual Basic, used to enhance the features of web pages
in internet Explorer.

Advantages:

 Easy to learn and use.


 Minimum programming knowledge or experience required.
 Allow complex tasks to be performed in relatively few steps.
 Allow simple creation and editing in a variety of text editors.
 Editing and running code is fast.

Disadvantage:

 Executable code can inadvertently be downloaded from a remote server to a web


browsers machine, installed and run using the local browsers interpreter. This is easily
done by visiting dubious web sites or downloading programs without valid authenticity.

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.

Uses of Scripting Languages

Typical uses of scripting languages including JavaScript include:

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.

2. Explain detail about Client - Side Scripting.

Client-side Scripting Environment (Browsers and editors)

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 developed by Netscape Communications Corporation, the marker of


the Netscape web browser. JavaScript was the first web scripting language to be supported
by browsers, and it is still by far the most popular.

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.

JavaScript and the Document Object Model

 When a JavaScript interpreter is embedded in a web browser, the result is client-side


JavaScript. This is by far the most common variant of JavaScript; when most people
refer to Javascript , they usually mean client-side javascript.
 Client-side javascript combines the scripting ability of a javascript interpreter with the
document object model (DOM) defined by a web browser. Documents may contain
javascripts, and those scripts can use the DOM to modify the document or control the
web browser that displays the document.
 The client-side JavaScript adds behaviour to otherwise static web content. Client-side
JavaScript is at the heart of web development rheniques such as DHTML and
architectures such as Ajax.
 The world wide web consortium (W3C) has published a DOM specification that
standardizes the features a browser must support in its DOM.
 The core portions of the W3C DOM http://www.w3.org/DOM standard are supported in
all major web browsers.

Test Client-side Scripts

 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.

Common scripting languages that run inside browsers are

 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.

3. Explain about the Server-Side Scripting.

Server-side scripting

Server-side scripting is a technique used in web development which involves


employing scripts on a web server which produce a response customized for each users

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.

There are a number of server-side scripting languages available, including:

 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 distinguished from client-side scripting where embedded


scripts, such as JavaScript are run client-side in a web browser, but both techniques are
often used together.

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.

When designing using dynamic web-based scripting techniques developers must


have a keen understanding of the logical, temporal, and physical separation between
the client and the server.

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.

4. Explain detail about PHP Variables.

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

Assignment by value simply involves copying the value of the assigned


expression to the variable assignee. This is the most common type of assignment. A few
examples follow:

$color = "red";

$number = 12;

$age = 12;

$sum = 12 + "15"; //

$sum = 27.

Reference Assignment

PHP 4 introduced the ability to assign variables by reference, which essentially


means that you can create a variable that refers to the same content as another variable
does. Therefore, a change to any variable referencing a particular item of variable content
will be reflected among all other variables referencing that same content. You can assign
variables by reference by appending an ampersand (&) to the equal sign. Let’s consider an
example:

<?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

Scope can be defined as the range of availability a variable has to the


program in which it is declared. PHP variables can be one of four scope types.

Local variables
Function parameters
Global variables
Static variables

Local Variables

A variable declared in a function is considered local; that is, it can be referenced


solely in that function. Any assignment outside of that function will be considered to be an
entirely different variable from the one contained in the function.

<?php

$x = 4; function assignx () {

$x = 0; print "\

$x inside function is

$x. <br />"; } assignx(); print "\

$x outside of function is $x. <br />";

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";
?>

This will produce the following result − Return value is 100

Global Variables

In contrast to local variables, a global variable can be accessed in any


part of the program. However, in order to be modified, a global variable must
be explicitly declared to be global in the function in which it is to be modified.
This is accomplished, conveniently enough, by placing the keyword GLOBAL
in front of the variable that should be recognized as global. Placing this
keyword in front of an already existing variable tells PHP to use the variable
having that name. Consider an example

<?php $somevar = 15;

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.

5. Explain detail about Constants in PHP.

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.

Defining a Constant The define() function defines a constant by assigning a value to a


name. Its prototype follows:

boolean define(string name, mixed value[, bool case_insensitive])


If the optional parameter case_insensitive is included and assigned TRUE,
subsequent references to the constant will be case insensitive.

Consider the following example in which the mathematical constant Pi is


defined: define("PI", 3.141592);

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);

This code produces the following results:

The value of pi is 3.141592.


Pi doubled equals 6.283184.

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

6. Explain detail about Operators and Conditional Statements in PHP.

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.

In PHP we have the following conditional statements:

if statement - executes some code only if a specified condition is true

Syntax:

if (condition) {

code to be executed if condition is true;

26
}

if...else statement - executes some code if a condition is true and another code if the
condition is false

Syntax:

if (condition) {

code to be executed if condition is true;

} else {

code to be executed if condition is false;

if...elseif....else statement - specifies a new condition to test, if the first condition is

false

Syntax:

if (condition) {

code to be executed if condition is true;

} elseif (condition) {

code to be executed if condition is true;

} else {

code to be executed if condition is false;

27
Example:

<!DOCTYPE html>

<html>

<body>

<?php

$t = date("H");

if ($t < "10") {

echo "Have a good morning!";

} elseif ($t < "20") {

echo "Have a good day!";

} else {

echo "Have a good night!";

?>

</body>

</html>

switch statement - selects one of many blocks of code to be executed

Syntax:

switch (n) {

28
case label1:

code to be executed if n=label1;

break;

case label2:

code to be executed if n=label2;

break;

case label3:

code to be executed if n=label3;

break;

...

default:

code to be executed if n is different from all labels;

Example:

<!DOCTYPE html>

<html>

<body>

<?php

$favcolor = "red";

switch ($favcolor) {

29
case "red":

echo "Your favorite color is red!";

break;

case "blue":

echo "Your favorite color is blue!";

break;

case "green":

echo "Your favorite color is green!";

break;

default:

echo "Your favorite color is neither red, blue, or green!";

?>

</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:

while (condition is true) {

code to be executed;

Example:

<!DOCTYPE html>

<html>

<body>

<?php

$x = 1;

while($x <= 5) {

echo "The number is: $x <br>";

$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;

} while (condition is true);

for - loops through a block of code a specified number of times

The for loop is used when you know in advance how many times the script should run.

Parameters:

init counter: Initialize the loop counter value

test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.

increment counter: Increases the loop counter value

Syntax:

for (init counter; test counter; increment counter) { code to be


executed;

32
Example:

<!DOCTYPE html>

<html>

<body>

<?php

for ($x = 0; $x <= 10; $x++) {

echo "The number is: $x <br>";

?>

</body>

</html>

foreach - loops through a block of code for each element in an array

The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.

Syntax:

foreach ($array as $value) {

code to be executed;

33
Example:

<!DOCTYPE html>

<html>

<body>

<?php

$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {

echo "$value <br>";

?>

</body>

</html>

7. Explain about Arrays in PHP.

PHP Array Functions:

The array functions allow you to access and manipulate arrays.

Simple and multi-dimensional arrays are supported.

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

numbers. By default array index starts from zero.

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);

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}

/* Second method to create array. */


$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}
?>

</body>
</html>

This will produce the following result −

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);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */


$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>

38
</body>
</html>

This will produce the following result −

Salary of mohammad is 2000


Salary of qadir is 1000
Salary of zara is 500

Salary of mohammad is high


Salary of qadir is medium
Salary of zara is low

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
),

"zara" => array (


"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);

/* Accessing multi-dimensional array values */


echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for qadir in maths : ";


echo $marks['qadir']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ;


echo $marks['zara']['chemistry'] . "<br />";

?>

</body>
</html>

This will produce the following result −

Marks for mohammad in physics : 35


Marks for qadir in maths : 32
Marks for zara in chemistry : 39

40
STRING:

They are sequences of characters, like "PHP supports string operations".

NOTE − Built-in string functions is given in function reference PHP String Functions

Following are valid examples of string

$string_1 = "This is a string in double quotes";


$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

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 "<br />";

$literally = "My $variable will print!\\n";

print($literally);
?>

This will produce the following result

My $variable will not print!\n


My name will print!\n

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.

The escape-sequence replacements are

 \n is replaced by the newline character

 \r is replaced by the carriage-return character

 \t is replaced by the tab character

 \$ is replaced by the dollar sign itself ($)

 \" is replaced by a single double-quote (")

 \\ is replaced by a single backslash (\)

String Concatenation Operator:

To concatenate two string variables together, use the dot (.) operator

<?php
$string1="Hello World";
$string2="1234";

echo $string1 . " " . $string2;

42
?>

This will produce the following result

Hello World 1234

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.

Using the strlen() function :

The strlen() function is used to find the length of a string.

Let's find the length of our string "Hello world!"

<?php
echo strlen("Hello world!");
?>

This will produce the following result

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)

Using the strpos() function :

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.

There are two parts which should be clear to you

 Creating a PHP Function

 Calling a PHP Function

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.

Creating PHP Function:

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!";
}

/* Calling a PHP Function */


writeMessage();
?>

</body>
</html>

This will display following result

You are really a nice person, Have a nice time!

PHP Functions with Parameters:

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>

This will display following result

Sum of the two numbers is : 30

Passing Arguments by Reference:

It is possible to pass arguments to functions by reference. This means that a


reference to the variable is manipulated by the function rather than a copy of the variable's
value.

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 );

echo "Original Value is $orignum<br />";

addSix( $orignum );
echo "Original Value is $orignum<br />";
?>

</body>
</html>

This will display following result

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

function addFunction($num1, $num2) {


$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);

echo "Returned value from the function : $return_value";


?>

</body>
</html>

This will display following result

48
Returned value from the function : 30

Setting Default Values for Function Parameters:

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 will produce following result

This is test

Dynamic Function Calls :

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>

This will display following result

Hello

8. Write about the file handling in PHP?

File handling is an important part of any web application. You often need to
open and process a file for different tasks.

PHP Manipulating Files

PHP has several functions for creating, reading, uploading, and editing files.

PHP readfile() Function

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:

AJAX = Asynchronous JavaScript and XML


CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

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

PHP Read File - fread()

The fread() function reads from an open file.

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()

The fclose() function is used to close an open file.

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);
?>

PHP Read Single Line - fgets()

The fgets() function is used to read a single line from a file.

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.

PHP Check End-Of-File - feof()

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);
?>

PHP Read Single Character - fgetc()

The fgetc() function is used to read a single character from a file.

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

$myfile = fopen("testfile.txt", "w")

PHP File Permissions

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.

PHP Write to File - fwrite()

The fwrite() function is used to write to a file.

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.

If we open the "newfile.txt" file it would look like this:

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

PHP 5 File Upload

With PHP, it is easy to upload files to the server.

However, with ease comes danger, so always be careful when allowing file uploads!

56
Configure The "php.ini" File

First, ensure that PHP is configured to allow file uploads.

In your "php.ini" file, search for the file_uploads directive, and set it to On:

file_uploads = On

Create The HTML Form

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>

Some rules to follow for the HTML form above:

 Make sure that the form uses method="post"

 The form also needs the following attribute: enctype="multipart/form-data". It specifies


which content-type to use when submitting the form

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.

Create Cookies With PHP

A cookie is created with the setcookie() function.

Syntax

setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.

PHP Create/Retrieve a Cookie

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).

Modify a Cookie Value

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>

10. Explain about The PHP MySQL Database.

With PHP, you can connect to and manipulate databases.

MySQL is the most popular database system used with PHP.

 MySQL is a database system used on the web

 MySQL is a database system that runs on a server

 MySQL is ideal for both small and large applications

 MySQL is very fast, reliable, and easy to use

61
 MySQL uses standard SQL

 MySQL compiles on a number of platforms

 MySQL is free to download and use

 MySQL is developed, distributed, and supported by Oracle Corporation

 MySQL is named after co-founder Monty Widenius's daughter: My

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 + MySQL Database System

 PHP combined with MySQL are cross-platform (you can develop in Windows and
serve on a Unix platform)

Database Queries

A query is a question or a request.

We can query a database for specific information and have a recordset returned.

Look at the following query (using standard SQL):

62
SELECT LastName FROM Employees

The query above selects all the data in the "LastName" column from the
"Employees" table.

Difference Between PHP and HTML

 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.

 The learning curve of PHP is also much steeper compared to HTML.

 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.

11. Write to Creating a Simple PHP Script?

The PHP Code Delimiters

 Testing the PHP Installation

 Embedding PHP into an HTML File

 Embedding HTML into a PHP Script

The PHP Code Delimiters

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.

A healthy PHP installation should result in output similar to the following:

Embedding PHP into an HTML File

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.

 Something as simple as a missing character can result in no content being


generated by the PHP module.

 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

You might also like