0% found this document useful (0 votes)
41 views

PHP With Example Code

Example codes of php with basic my sql

Uploaded by

Syed asim
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

PHP With Example Code

Example codes of php with basic my sql

Uploaded by

Syed asim
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

PHP for Server-Side

Preprocessing

Chapter 08
Overview and Objectives
• Present a brief history of the PHP language
• Discuss how PHP fits into the overall web picture
• Discuss PHP script development and testing
• Incorporate into our home page a PHP-generated welcome message
• Show how to cause our home page to be refreshed (reloaded) every so often
• Implement the server-side functionality of our feedback form:
– sending the user’s feedback to the business via email,
– sending a copy of the e-mail to the client,
– storing a copy of the feedback on the server
• Implement an alternate version of our BMI calculator
• Show how to send HTML-encoded e-mail
• Use the POST value of the method attribute of the form element to submit form data
• Discuss several features of the PHP language, as required for our purposes:
– Comments
– variables (including superglobals),
– numerical and string data types,
– expressions and operators, arrays,
– built-in and programmer defined functions,
– file output,
– server-side inclusion of files

Chapter 08: PHP for Server-Side Preprocessing


PHP History
• PHP stood for Personal Home Page, when originally implemented
by Rasmus Lerdorf in 1995 for tracking accesses to his online
resume.
• A revised version was called PHP/FI, where FI stood for Forms
Interpreter.
• Now users prefer to use the recursive name PHP: Hypertext
Preprocessor.
• Perl was the language of choice for server-side computing prior to
PHP.
• Constructs of PHP: Origins in Perl and similar to JavaScript.
• Source code for PHP was made public and that led to a vibrant
community of developers.

Chapter 08: PHP for Server-Side Preprocessing


PHP as a Server-Side
Scripting Language
• Most web servers support a PHP interpreter.
• May not automatically have access to PHP on a server
provided by an ISP.
• PHP has to be activated and configured for use
• A web server may spawn a separate operating system process
to handle PHP requests, or it may be “built-into” the server:
This will be “transparent to the user”.
• PHP-related pages provided on the CD-ROM cannot be
viewed directly from the CD-ROM.
• PHP-related pages will need to be uploaded to a PHP-enabled
web server in order to function properly.

Chapter 08: PHP for Server-Side Preprocessing


PHP: A Simple Example
welcome.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- welcome.php -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Welcome Message with Output from the PHP date()
Function</title>
<meta http-equiv="Content-Type"
content="text/html;charset=utf-8" />
</head>
<body>
<h2>Welcome!</h2>
<?php
echo "<h3>It's ".date("l, F jS").".<br />";
echo "The time is ".date("g:ia").".</h3>";
?>
</body>
</html>
Chapter 08: PHP for Server-Side Preprocessing
Diving Right In:
What do we see in welcome.php?
• A PHP script between the PHP “delimiters”: <?php … ?>
• Two PHP echo statements that send strings containing markup to the web page
(note that statements end with a semicolon).
• The use of the PHP built-in function date() to return a date value for inclusion
in the web page.
– date("l, F jS") returns the current date as a string, with the day in long (l) form,
the full (F) name of the month, the date of the month in the Julian calendar (j), with the
appropriate suffix (S) appended (the comma and two spaces are just literal characters)
– date("g:ia") actually returns a time, rather than a date, again as a string, with g
giving the hour in 12-hour format with no leading zeros, i giving the minutes with leading
zeros, and a causing am or pm to be appended, as appropriate (the colon is a literal
character)
• The (somewhat unorthodox) use of the period (.) as the string concatenation
operator in PHP. Can you spot which periods are used like this, and which are just
periods at the ends of sentences?

Chapter 08: PHP for Server-Side Preprocessing


A Browser Display of welcome.php

Courtesy of Nature’s Source

Chapter 08: PHP for Server-Side Preprocessing


A Browser Display of index.php: Now Contains
A Welcome Message, with Date and Time from the PHP Script Output

Courtesy of Nature’s Source,


(inset) © Photos.com
Chapter 08: PHP for Server-Side Preprocessing
Our New Index File:
index.php (1 of 2)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- index.php for the home page of the current Nature's Source web site -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Nature's Source - Canada's largest specialty vitamin store</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="refresh" content="60" />
<link rel="stylesheet" type="text/css" href="css/default.css" />
<script type="text/javascript" src="scripts/rotate.js"></script>
<script type="text/javascript" src="scripts/menu.js"></script>
</head>
<body onload="startRotation()">
<div id="page">
<?php
include("common/banner.php");
include("common/mainmenu.html");
?>
<div id="content">

Chapter 08: PHP for Server-Side Preprocessing


Our new index file:
index.php (2 of 2)
<div id="textLeft">
<h3>Welcome to Nature's Source: Protecting your health naturally!</h3>
<p>Founded in 1998, Nature's Source was created to serve those who
use alternative healing methods. Offering only the highest quality
vitamins, minerals, supplements &amp; herbal remedies, Nature's
Source takes great pride in helping people live healthier, happier
lives.</p>
<p>Many Companies that talk about Customer Service fail to deliver.
Nature's Source exists to truly serve all the needs of their
customers. Each location features dedicated on-site therapists
along with knowledgeable staff who ensure that every customer
receives the best quality information available. Continuing
Education seminars are a regular event at Nature's Source.</p>
</div>
<div id="image">
<img id="placeholder" src="" alt="Healthy Lifestyle"
width="280px" height="160px" />
</div>
</div>
<?php
include("common/footer.html");
?>
</div>
</body>
</html>
Chapter 08: PHP for Server-Side Preprocessing
Markup from Our New Banner File:
Extends the previous logo.html
<!-- banner.php -->
<div id="logo">
<img src="images/naturelogo.gif"
alt="Nature's Source"
width="608px" height="90px" />
</div>
<div id="welcome">
<h3>Welcome!</h3>
<?php
echo "<h5>It's ".date("l, F jS").".<br />";
echo "Our time is ".date('g:ia').".</h5>";
?>
</div>

Chapter 08: PHP for Server-Side Preprocessing


A Firefox browser display of
feedback.php

Courtesy of Nature’s Source

Chapter 08: PHP for Server-Side Preprocessing


The Revised form Tag in feedback.html
Invokes a Server-Side PHP Script for Processing When
the Input Data is Valid

<form id="contactForm" onsubmit="return validateContactForm()"


action="scripts/processFeedback.php" method="post">

Chapter 08: PHP for Server-Side Preprocessing


PHP Code to Process Feedback in processFeedback.php (1 of 2)

<?php
//processFeedback.php

//Construct the message to be sent to the business


$messageToBusiness =
"From: ".$_POST['salute']." "
.$_POST['firstName']." "
.$_POST['lastName']."\r\n" .
"E-mail address: ".$_POST['email']."\r\n".
"Phone number: ".$_POST['phone']."\r\n".
"Subject: ".$_POST['subject']."\r\n".
$_POST['message']."\r\n";

//Send the e-mail feedback message to the business (but here, to the webbook site)
$headerToBusiness = "From: $_POST[email]\r\n";
mail("[email protected]", $_POST['subject'], $messageToBusiness, $headerToBusiness);

//Construct the confirmation message to be e-mailed to the client


$messageToClient =
"Dear ".$_POST['salute']." ".$_POST['lastName'].":\r\n".
"The following message was received from you by Nature's Source:\r\n\r\n".
$messageToBusiness.
"------------------------\r\nThank you for the feedback and your patronage.\r\n" .
"The Nature's Source Team\r\n------------------------\r\n";
if ($_POST['reply'])
$messageToClient .= "P.S. We will contact you shortly with more information.";
Chapter 08: PHP for Server-Side Preprocessing
PHP Code to Process Feedback in processFeedback.php (2 of 2)

//Send the confirmation message to the client


$headerToClient = "From: [email protected]\r\n";
mail($_POST['email'], "Re: ".$_POST['subject'], $messageToClient, $headerToClient);

//Transform the confirmation message to the client into XHTML format and display it
$display = str_replace("\r\n", "<br />\r\n", $messageToClient);
$display =
"<html><head><title>Your Message</title></head><body><tt>".
$display.
"</tt></body></html>";
echo $display;

//Log the message in a file called feedback.txt on the web server


$fileVar = fopen("../data/feedback.txt", "a")
or die("Error: Could not open the log file.");
fwrite($fileVar, "\n-------------------------------------------------------\n")
or die("Error: Could not write to the log file.");
fwrite($fileVar, "Date received: ".date("jS \of F, Y \a\\t H:i:s\n"))
or die("Error: Could not write to the log file.");
fwrite($fileVar, $messageToBusiness)
or die("Error: Could not write to the log file.");
?>
An e-mail Display Showing the e-mail Received by the
Business as a Result of the Form Being Processed by
processFeedback.php

Chapter 08: PHP for Server-Side Preprocessing


An e-mail Display Showing the e-mail Received by the
Client as a Result of the Form Being Processed by
processFeedback.php

Chapter 08: PHP for Server-Side Preprocessing


A Browser Display of Processing from
processFeedback.php Showing Confirmation to the User
That the Feedback Form Input Has in Fact Been Received

Courtesy of Nature’s Source

Chapter 08: PHP for Server-Side Preprocessing


The Feedback Message, with Date of Submission,
As It Is Stored on the Server in a Log File Called
feedback.txt in the Subdirectory nature/data
From: Mr. Pawan Lingras
E-mail address: [email protected]
Phone number: 5798
Subject: Hello
Thank you for providing me with an opportunity
to look at various health alternatives. I was
wondering if you had some products that will
help me reduce my cholesterol.

Thank you for the feedback and your patronage.


--
Naturally Yours! team
P.S. We will contact you shortly with more information.

Chapter 08: PHP for Server-Side Preprocessing


Chapter 08: PHP for Server-Side
Preprocessing
A browser display of bmi.php

Courtesy of Nature’s Source

Chapter 08: PHP for Server-Side Preprocessing


A browser Display of Processing from
processBMI.php

Courtesy of Nature’s Source

Chapter 08: PHP for Server-Side Preprocessing


E-mail Received by the Client As a Result of
Processing from processBMI.php

Courtesy of Nature’s Source

Chapter 08: PHP for Server-Side Preprocessing


The Revised form Tag Which Invokesa PHP Script for
Processing the Form Data from bmi.php

<form id="bmiForm" onsubmit="return validateInput()"


action="scripts/processBMI.php" method="post">

Chapter 08: PHP for Server-Side Preprocessing


PHP Code to Process BMI in processBMI.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- processBMI.php -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Your BMI</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>
<p>
<?php
include 'bmiCalculate.php';
if ($_POST['details'])
$message = detailedMessage($_POST['height'], $_POST['heightUnit'],
$_POST['weight'], $_POST['weightUnit']);
else
$message = simpleMessage($_POST['height'], $_POST['heightUnit'],
$_POST['weight'], $_POST['weightUnit']);
echo $message;
if ($_POST['wantMail'])
{
mailBMI($_POST['email'], $message);
echo "<h2>The report has also been sent to you via e-mail.</h2>";
}
?>
</p>
</body>
</html>
Chapter 08: PHP for Server-Side Preprocessing
PHP Programmer-defined Functions (1 of 4)
<!-- bmiCalculate.php -->

<?php
function simpleMessage($height, $heightUnit, $weight,
$weightUnit)
{
$bmi = sprintf("%.2lf", calculateBMI($height,
$heightUnit, $weight, $weightUnit));
$text =
"<h1>BMI Report</h1>".
"<h3>Your BMI is ".$bmi.".</h3>";
return $text;
}

Chapter 08: PHP for Server-Side Preprocessing


PHP Programmer-defined Functions (2 of 4)

function detailedMessage($height, $heightUnit, $weight, $weightUnit)


{
$bmi = sprintf("%.2lf", calculateBMI($height, $heightUnit, $weight,
$weightUnit));
$text = //"<p> "."<img src = ".
//"
http://cs.smu.ca/~webbook/cdrom/web08/nature/images/naturelogo.gif ".
//" alt = 'Nature's Source Logo' />"."</p>".
"<h1>BMI Report</h1>".
"<h3>Your height: ".$height." ".$heightUnit."<br />".
"Your weight: ".$weight." ".$weightUnit."<br />".
"Your BMI: ".$bmi."</h3>";
if ($bmi < 18.5)
$text .= "<h2>Your BMI suggests that you are underweight.</h2>";
else if ($bmi < 25)
$text .= "<h2>Your BMI suggests that you have a reasonable
weight.</h2>";
else if ($bmi < 29)
$text .= "<h2>Your BMI suggests that you are overweight.</h2>";
else
$text .= "<h2>Your BMI suggests that you may be obese.</h2>";
return $text;
}
Chapter 08: PHP for Server-Side Preprocessing
PHP Programmer-defined Functions (3 of 4)
function inchesToCentimetres($height){return $height*2.54; }
function poundsToKilograms($weight){return $weight/2.2; }

function calculateBMI($height, $heightUnit, $weight,


$weightUnit)
{
if ($heightUnit == "inches") $height =
inchesToCentimetres($height);
if ($weightUnit == "pounds") $weight =
poundsToKilograms($weight);
$height /= 100; //Convert height from centimeters to
meters
$bmi = $weight/($height*$height);
return $bmi;
}

Chapter 08: PHP for Server-Side Preprocessing


PHP Programmer-defined Functions (4 of 4)

function mailBMI($email, $message)


{
$header = 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html;
charset=iso-8859-1' . "\r\n";
$header .= "From: [email protected]\r\n";
mail($email, "BMI report from Nature's
Source", $message, $header);
}
?>

Chapter 08: PHP for Server-Side Preprocessing

You might also like